Is there an “IF EXISTS” test for a linked server?

时光怂恿深爱的人放手 提交于 2019-11-26 17:22:57

问题


I want to be able to programmatically (in T-SQL) check if a specific linked server already exists for my current server and database (so that if the link doesn't exist yet, I can create it). I tried stuff like this:

IF OBJECT_ID('myserver\devdb_1') IS NULL
BEGIN
  PRINT 'Does not exist, need to create link'
  EXEC master.dbo.sp_addlinkedserver @server = N'myserver\devdb_1', 
                                     @srvproduct=N'SQL Server'
END
ELSE
  PRINT 'Link already exists'

But the OBJECT_ID test always returns null, even if the link already exists. Any way to do this check in T-SQL, so that the rest of my code can assume the link always exists?


回答1:


Check in sys.servers:

if not exists(select * from sys.servers where name = N'myserver\devdb_1')



回答2:


IF NOT EXISTS ( SELECT TOP (1) * FROM sysservers WHERE srvname = 'myserver\devdb_1' )


来源:https://stackoverflow.com/questions/3104186/is-there-an-if-exists-test-for-a-linked-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!