[英]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
. 然而,有时(但不是所有的时间!),当我运行它,它抛出一个错误告诉我,它无法找到该
TIMECLOCK
在服务器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. 不一致使我感到困惑,因为我已经尝试了许多场景(在运行过程之前有和没有实例化链接的情况下),它们都大约有70%的时间有效。
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
. 这是
opendatasource
和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. 但是,如果必须这样做,则可以将代码括在while循环中。 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(). 因此,如果不是NOT EXISTS(),请执行WHILE NOT EXISTS()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.