SQL 服务器链接服务器更新

SQL server linked server update

目前正在编写一个脚本,该脚本可以跨链接服务器更新许多不同的表。我使用 08/12 SQL 服务器管理工​​作室。

我在尝试将链接服务器字符串设置为变量时遇到问题,因此我可以在开头设置它并在需要时通过脚本进行引用。我一直在假设我可以将其声明为局部变量,就像我对正在更新本地 table/server 的脚本的其他部分所做的那样,但是当 运行 脚本时,我收到一个不正确的我的链接服务器字符串变量所在的代码部分存在语法错误。

我的代码结构如下:

declare @string varchar(max)

set @string = '[server,instance].[database].dbo.table1'

update @string
set field = updatevariable
where record = identifier

是否可以使用链接服务器作为变量?

可以动态构造SQL更新字符串,然后传给exec。示例:

declare 
  @srv nvarchar(max) = N'[server].[db].[dbo].[table]',
  @id int = 100,
  @value nvarchar(max) = N'some value',
  @sql nvarchar(max)

set @sql = N'update ' + @srv 
         + ' set field = ''' + @value + ''' '
         + ' where record = ' + cast(@id as nvarchar)

exec(@sql)