无法在动态 SQL 中使用完全限定表名

发布于 2024-08-11 21:38:34 字数 648 浏览 2 评论 0原文

我试图通过迭代服务器名称列表并执行一些动态 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一花一树开 2024-08-18 21:38:34

如何使用括号:

EXEC(@sql);

How about using parantheses:

EXEC(@sql);
如果没结果 2024-08-18 21:38:34

你试过括号吗?

[SomeServer].[dba_sandbox].[dbo].[SomeTable]

Have you tried brackets?

[SomeServer].[dba_sandbox].[dbo].[SomeTable]

陌伤ぢ 2024-08-18 21:38:34

不确定是什么原因造成的,但您是否尝试过以这种形式创建更新:

更新
设置 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

A君 2024-08-18 21:38:34

问题是我使用的是

EXEC @Sql

Not

Exec(@sql)

The issue was I was using

EXEC @Sql

Not

Exec(@sql)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文