小编典典

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

sql

我正在尝试从表中读取数据。该表具有表名列表。

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

这是我所做的

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;

每次我运行此查询时,都会出现此错误

Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@LastRun".

我不知道为什么,因为我在上面的代码中看到了在顶部声明此变量的原因。

取得输出print @OPENQUERY + @sqlCommandMySQL;并手动执行。它没有问题,并且该变量@LastRun将具有应有的datetime值。


阅读 550

收藏
2021-04-28

共1个答案

小编典典

您需要使用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

演示版

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
2021-04-28