无法在动态 SQL 中使用完全限定表名
我试图通过迭代服务器名称列表并执行一些动态 SQL 来更新多个远程服务器上的表。见下文。
DECLARE @Sql NVARCHAR(4000)
DECLARE @Server_Name VARCHAR(25)
SET @Server_Name='SomeServer'
SET @Sql='UPDATE ' + @Server_Name + '.dba_sandbox.dbo.SomeTable SET SomeCol=''data'''
PRINT @Sql
EXEC @Sql
产生以下输出:
UPDATE SomeServer.dba_sandbox.dbo.SomeTable SET SomeCol='data'
Msg 7202, Level 11, State 2, Line 7
Could not find server 'UPDATE SomeServer' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.
现在 SomeServer 是链接服务器。如果我执行打印出来的 SQL 语句,它就可以正常工作。另请注意,在错误消息中,它认为远程服务器是“UPDATE SomeServer”,而不是“SomeServer”。
I'm trying to update a table on several remote servers by iterating over a list of server names and executing some dynamic SQL. See below.
DECLARE @Sql NVARCHAR(4000)
DECLARE @Server_Name VARCHAR(25)
SET @Server_Name='SomeServer'
SET @Sql='UPDATE ' + @Server_Name + '.dba_sandbox.dbo.SomeTable SET SomeCol=''data'''
PRINT @Sql
EXEC @Sql
Which produces the following output:
UPDATE SomeServer.dba_sandbox.dbo.SomeTable SET SomeCol='data'
Msg 7202, Level 11, State 2, Line 7
Could not find server 'UPDATE SomeServer' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.
Now SomeServer is a linked server. If I execute the printed out SQL statement it works fine. Note also, in the error message, it thinks the remote server is 'UPDATE SomeServer', rather than 'SomeServer'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如何使用括号:
How about using parantheses:
你试过括号吗?
[SomeServer].[dba_sandbox].[dbo].[SomeTable]
Have you tried brackets?
[SomeServer].[dba_sandbox].[dbo].[SomeTable]
不确定是什么原因造成的,但您是否尝试过以这种形式创建更新:
更新
设置 somecol = '数据'
来自 someserver.dba_sandbox.dbo.SomeTable a
Not sure what is causing it but have you tried creating the update in this form:
update a
set somecol = 'data'
from someserver.dba_sandbox.dbo.SomeTable a
问题是我使用的是
Not
The issue was I was using
Not