How to Set a variable using OPENQUERY in SQL Server

牧云@^-^@ 提交于 2019-12-06 09:38:56
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 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!