使用变量名称在远程服务器中执行存储过程

时间:2012-12-04 10:23:44

标签: sql sql-server sql-server-2012

我有一个游标及其获取数据库名称和链接服务器名称,以便在每个游标中执行一个过程

Declare getDBLinkServer cursor for  
select DatabaseName, LinkServerName from DBnLinkServer  
Open getDBLinkServer  
fetch next from getDBLinkServer into @DatabaseName, @LinkServerName  
While @@FETCH_STATUS = 0  
Begin  
    exec @LinkServerName.@DatabaseName.dbo.someProcedure 'some' 
    fetch next from getDBLinkServer into @DatabaseName, @LinkServerName  
End  
Close getDBLinkServer  
Deallocate getDBLinkServer

这显示Incorrect syntax near '.'我该如何避免它?

1 个答案:

答案 0 :(得分:1)

使用动态sql。像这样:

declare @sql nvarchar(max)
set @sql = 'exec ' + @LinkServerName + '.' + @DatabaseName + '.dbo.'+@someProcedure+' ''some''' 

exec sp_executeSQL @sql