Reputation: 41
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?
Upvotes: 1
Views: 123
Reputation: 370
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().
Upvotes: 0
Reputation: 7702
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.
Upvotes: 1