简体   繁体   中英

Create and Destroy Linked Server in Stored Procedure

I have a stored procedure that needs to touch some data on two different servers. One of these servers contains somewhat sensitive information, and we would rather not have this server linked to the other all the time.

In order to deal with this, I wrote the calls to link and destroy the server directly into the stored procedure, like so:

IF NOT EXISTS (
        SELECT NAME
        FROM sys.servers
        WHERE NAME = 'TIMECLOCK'
        )
    EXEC sys.sp_addlinkedserver @server = 'TIMECLOCK'
        ,@srvproduct = 'SQL Server';

/* a select statement */
EXEC sys.sp_dropserver [TIMECLOCK]

However, sometimes (but not all the time!) when I run this, it throws an error telling me that it can't find the TIMECLOCK server in sys.servers . The inconsistency confuses the hell out of me, as I've tried numerous scenarios (both with and without instantiating the link prior to running the procedure) and they all work about 70% of the time.

Any idea what could be causing this?

One of these servers contains somewhat sensitive information, and we would rather not have this server linked to the other all the time.

Rubbish. If you do care about security, you should have tighten the security once and be done with it, rather than choosing a worst possible solution for an imaginary problem.

Having said that, there are alternatives to linked servers designed specifically for this purpose - when you have to query external data but don't want to create a persistent link. These are opendatasource and openrowset . You can choose any one you like most.

I agree with the sentiments expressed by Roger Wolf above.

However, if you must do it this way, you can enclose your code in a while loop. It's not efficient, but it will guarantee that if adding the linked server fails, it will continue to try before attempting to access it.

So rather than IF NOT EXISTS(), do WHILE NOT EXISTS().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM