On demand linked server creation in SP

  • I have a stored procedure that creates a linked server as one of the first lines of the procedure and then proceeds to use it for some calculations.

    It worked great in SQL 2005, but now that I've upgraded to SQL 2012 it will not allow me to execute, telling me that my linked server does not exist.

    Is there a way around this in 2012?

  • The creation of the linked server fails for some reason.

    You didn't post the actual error message, so it's nearly impossible to give sensible advice.

    -- Gianluca Sartori

  • The creation of the linked server does not fail. I copied the exact line of code and ran it separately on a SQL 2012 machine to create the linked server for a test and that succeeded. It just doesn't like it in the procedure in 2012. The same procedure has been running in SQL 2005 for years.

    The error I get is:

    Msg 7202, Level 11, State 2, Procedure ,<my procedure>, Line 49

    Could not find server 'MyLinkedServer' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.

    I'll add that if I create the linked server first and execute the procedure it does allow me to execute and I get the expected error that I explicitly raise telling me that the linked server already exists.

  • Weird. Can you post the code?

    -- Gianluca Sartori

  • I have figured something out.

    If I create the linked server manually and then run the procedure I get an explicitly raised error that I wrote in to tell me that the server already exists.

    If I manually drop the linked server and then execute the procedure it works as expected. I ran it several times with success.

    I then ran <dbcc freeproccache>, attemped the procedure again and the <Could not find server 'MyLinkedServer' in sys.servers> error returned.

    So the question becomes, how can I force this procedure to compile without the linked server present at the time of compilation?

  • Use dynamic sql.

    -- Gianluca Sartori

  • Sounds good. I don't know why I didn't think of that.

    Thanks!

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply