如何在 SQL Server 中使用 OPENQUERY 设置变量

Jay*_*len 2 sql sql-server scalar openquery

我正在尝试从表中读取数据。这个表有一个表名列表。

对于数据集的每一行,我想运行几个查询来提取数据并将其插入到临时表中。

这是我所做的

DECLARE @campName varchar(255);
DECLARE @sqlCommand varchar(1000);
DECLARE @sqlCommandMySQL varchar(1000);
DECLARE @LastRun varchar(60);
DECLARE @OPENQUERY varchar(1000);


DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT LTRIM(RTRIM(CallListName)) AS CallListName
FROM [SMSQL1].[RDI_System].[dbo].[Campaigns]
WHERE dialer_campaign = 1 AND i3Server ='I3New' AND ClientID = 111 AND (EndDate IS NULL OR EndDate >= getdate() - 7)

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @campName
WHILE @@FETCH_STATUS = 0
BEGIN 
    --SET @LinkedServer = 'GUARDIAN';
    SET @OPENQUERY = 'SELECT @LastRun = lr FROM OPENQUERY(GUARDIAN,''';
    SET @sqlCommandMySQL = 'SELECT IFNULL(MAX(lastRun), DATE_SUB(NOW(), INTERVAL 7 DAY) ) AS lr
                            FROM guardian_dynamo.runtimes_i3
                            WHERE CampaignListName = "'+@campName+'" '')';

    print @OPENQUERY + @sqlCommandMySQL;

    EXEC(@OPENQUERY + @sqlCommandMySQL);


    SET @sqlCommand = ' INSERT INTO #finalList(Attemtps, CAMPAIGNNAME, FINISHCODE, CALLDATE, AGENTID, RDINotes, PHONE, MERCHANTAccount)
                        SELECT ATTEMPTS, CAMPAIGNNAME, FINISHCODE, CALLDATE, AGENTID, RDINotes, PHONE, MERCHANTAccount 
                        FROM [I3_IC4].[dbo].['+ @campName +']
                        WHERE CALLDATE > '''+@LastRun+''' AND ISNULL(status, ''C'') IN (''U'', ''E'', ''A'', ''F'')   ';
    EXEC (@sqlCommand);


    FETCH NEXT FROM MY_CURSOR INTO @campName
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR;
Run Code Online (Sandbox Code Playgroud)

每次运行此查询时,我都会收到此错误

Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@LastRun".
Run Code Online (Sandbox Code Playgroud)

我不知道为什么,因为我在顶部声明了这个变量,正如你在我上面的代码中看到的那样。

获取输出print @OPENQUERY + @sqlCommandMySQL;并手动执行。它没有问题,变量@LastRun将具有它应该的日期时间值。

Pரத*_*ீப் 5

您需要使用sp_executesql来执行动态查询,这有助于您 output了解变量(@LastRun)

Declare @OPENQUERY Nvarchar(max), @sqlCommandMySQL Nvarchar(max), @OPENQUERYFINAL Nvarchar(max)
....
SET @OPENQUERY = 'SELECT @LastRun = lr FROM OPENQUERY(GUARDIAN,''';
SET @sqlCommandMySQL = 'SELECT IFNULL(MAX(lastRun), DATE_SUB(NOW(), INTERVAL 7 DAY) ) AS lr
                            FROM guardian_dynamo.runtimes_i3
                            WHERE CampaignListName = "'+@campName+'" '')';

    --print @OPENQUERY + @sqlCommandMySQL;
    SET @OPENQUERYFINAL = @OPENQUERY + @sqlCommandMySQL;

    EXEC sp_executesql @OPENQUERYFINAL, 
                       N'@LastRun varchar(10) OUTPUT',
                         @LastRun output
Run Code Online (Sandbox Code Playgroud)

演示

DECLARE @str VARCHAR(10),
        @sql NVARCHAR(max)

SET @sql= 'select @str=1 '

EXEC Sp_executesql
  @sql,
  N'@str varchar(10) OUTPUT',
  @str output

PRINT @str 
Run Code Online (Sandbox Code Playgroud)