基于链接服务器的存在执行SQL的一部分

基于链接服务器的存在执行SQL的一部分,sql,sql-server,Sql,Sql Server,我正在尝试编写一个可以在不同服务器上运行的查询。我试图检测我在哪台服务器上的一种方法是存在某个链接服务器,即服务器1将链接到服务器2,反之亦然 问题是,我无法让SQL Server忽略/跳过在不存在的链接服务器上运行的代码。有两段几乎相同的代码,一段使用链接的Server1,另一段不使用,因为它已经在Server1上运行 drop table #origdates if exists(select 1 from sys.servers where name = N'Server1') BEGIN

我正在尝试编写一个可以在不同服务器上运行的查询。我试图检测我在哪台服务器上的一种方法是存在某个链接服务器,即服务器1将链接到服务器2,反之亦然

问题是,我无法让SQL Server忽略/跳过在不存在的链接服务器上运行的代码。有两段几乎相同的代码,一段使用链接的Server1,另一段不使用,因为它已经在Server1上运行

drop table #origdates
if exists(select 1 from sys.servers where name = N'Server1')
BEGIN
Select * into #origdates from openquery([Server1],'Select accounts, dates from table1')                                
END

if not exists(select 1 from sys.servers where name = N'Server1')
BEGIN
Select accounts, dates into #origdates from table1
END
如果我执行各个部分,一切都很好;代码要么按指定执行,要么不按指定执行,但当我一起运行整个代码时,服务器似乎忽略了if exists部分,错误如下:

Could not find server 'Server1' 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.
我这样做的原因是,我不必用两个单独的Beginning部分维护两个相同的脚本

使用ELSE代替第二行if not exists会导致服务器抱怨origdates表已经存在,即使在select into命令行之前发出了drop table命令


使用不同的表名会将错误返回到“找不到服务器”消息,尽管它根本不应该执行该代码…

试试看,SQL正在尝试验证OPENQUERY,但它无法验证,因为[Server1]不是有效的链接服务器。将OPENQUERY隐藏在变量中应该可以修复它

注意,您需要在OPENQUERY中从db.owner.table传递,而不仅仅是从表传递


您是否尝试过使用ELSE而不是第二个IF?如果我做ELSE,我不能结束If,让脚本的其余部分执行脚本的其余部分应该为两台服务器执行。按照我的理解,要么执行,要么执行。理论上,这是正确的,但实际上它不是这样工作的……用ELSE替换第二个if-exists语句会导致服务器抱怨表origdates已经存在。很好!没有考虑将查询隐藏为字符串!我认为,如果if语句的第一个分支运行.Yep,您会发现origdates超出范围。这应该行得通。不过,要小心不同用户同时运行的代码。幸运的是,它似乎在范围内,即使它应该在逻辑上。我翻了这两个部分,现在它似乎像写的一样工作@DMason true,如果在多用户场景中,更好的解决方案是在当前spid中构建表,并在if/ELSE中插入。
declare @sql nvarchar(max)

if object_id('tempdb..#origdates') is not null
    drop table #origdates

create table #origdates (accounts int, dates datetime)

if exists(select 1 from sys.servers where name = N'Server1')
BEGIN
    set @sql='insert into #origdates Select * from openquery([Server1],''select accounts, dates from db.dbo.table1'')'
    exec(@sql)
END

else
BEGIN
    insert into #origdates Select accounts, dates from table1
END