简体   繁体   English

具有@variable服务器名称的存储过程

[英]Stored procedure with @variable server name

I am trying to create a new stored procedure sp_sync_table (in SQL Server 2012) which accepts one parameter (linked server name). 我正在尝试创建一个新的存储过程sp_sync_table (在SQL Server 2012中),该存储过程接受一个参数(链接的服务器名称)。 However jut declaring the @linkedServerName variable is not enough. 但是, @linkedServerName声明@linkedServerName变量是不够的。 The CREATE PROCEDURE directive fails because it cannot resolve the @linkedServerName unless @linkedServerName is SET to a specific name. CREATE PROCEDURE指令失败,因为除非将@linkedServerName 设置为特定名称,否则它无法解析@linkedServerName

It fails with error: 它因错误而失败:

Msg 102, Level 15, State 1, Procedure sp_sync_table, Line 31 消息102,级别15,状态1,过程sp_sync_table,第31行
Incorrect syntax near '.'.) '。'附近的语法不正确。)

Obviously I cannot provide a specific name, that has to be passed in through the 显然,我无法提供一个特定的名称,该名称必须通过

exec sp_sync_table server_name

This is the failing part: 这是失败的部分:

CREATE  PROCEDURE sp_sync_table
    @linkedServerName AS VARCHAR(50)
AS BEGIN
.
.
.
DECLARE cursorX CURSOR FOR

SELECT col1, col2, col3, col4 FROM @linkedServerName.[db-name].[dbo].[table]

OPEN cursorX
.
.
.

What would be the workaround for this scenario ? 这种情况下的解决方法是什么?

Could you use dynamic sql? 您可以使用动态SQL吗? I know it's not the safe way to go about doing it, but you could place your query in a string and execute the string. 我知道这不是执行此操作的安全方法,但是您可以将查询放入字符串中并执行该字符串。 Just be super careful of what the user passes in for the @linkedServerName. 请超级小心用户为@linkedServerName传递的内容。 Obviously you will be executing whatever you allow your user to enter. 显然,您将执行允许用户输入的任何内容。 Not sure how this will work with a cursor though - I've never tried. 但是不确定如何使用游标-我从未尝试过。

CREATE  PROCEDURE sp_sync_table

    @linkedServerName AS VARCHAR(50)

AS BEGIN

.
.
.
DECLARE queryToExecute varchar(max)
select  queryToExecute = 'DECLARE cursorX CURSOR FOR'
select queryToExecute = queryToExecute + 'SELECT col1, col2, col3, col4 FROM'
select queryToExecute = queryToExecute + ' ' + @linkedServerName + '.[db-name].[dbo].[table]'
select queryToExecute = queryToExecute + 'OPEN cursorX...'
exec(queryToExecute)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM