我正在尝试从表中读取数据。该表有一个表名列表。
对于数据集的每一行,我想运行几个查询来提取数据并将其插入临时表。
这就是我所做的
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
将具有应该的日期时间值。
你需要使用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