I am trying to read data from a table. This table have a list of table name.
for each row of the data set I want to run a couple of queries to pull data and insert it into a temporary table.
Here is What I have done
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;
every time I run this query I get this error
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@LastRun".
I am not sure why since I am declaring this variable on the top as you can see in my code above.
the took the output of print @OPENQUERY + @sqlCommandMySQL;
and executed that manually. It worked with no issue and the variable @LastRun
will have a datetime value as it should.
Pரதீப்
You need to use sp_executesql
to execute the dynamic query which helps you output
the variable(@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
Demo
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
来源:https://stackoverflow.com/questions/28327092/how-to-set-a-variable-using-openquery-in-sql-server