将包含COALESCE的动态sql语句的结果分配给变量

时间:2018-09-10 22:07:59

标签: exec variable-assignment dynamic-sql coalesce sp-executesql

我有一个使用COALESCE构建的动态SQL语句。我需要将执行此动态sql语句的结果分配给变量。我尝试了以下代码,但未将输出分配给变量@result。执行完成后,exec将显示正确的结果,但“ select @result”的输出始终为NULL

DECLARE @SQL NVARCHAR(MAX)
DECLARE @result int  


SELECT   @SQL = COALESCE('select '+ @SQL + CHAR(13) + ' + ' + CHAR(13),'' ) 
                       +
                       '(SELECT case when count(distinct ' + convert(varchar(10),object_id) + ' ) > 0 then 1 else 0 end from sys.dm_db_index_usage_stats 
                         WHERE object_id = '+convert(varchar(10),object_id)
                         +'AND last_user_update > dateadd(minute, -1, getdate()) 
                         )'                         
FROM sys.dm_db_index_usage_stats
WHERE object_id in (object_id('table1'),object_id('table2'))
AND database_id = db_id(db_name())

EXEC sp_executesql @SQL, N'@result int output', @result out 

select @result

1 个答案:

答案 0 :(得分:0)

以下代码帮助我解决了此问题。

DECLARE @SQL NVARCHAR(MAX)
DECLARE @result int  
DECLARE @parms nvarchar(1000)

SELECT   @SQL = COALESCE('select @cnt='+ @SQL + CHAR(13) + ' + ' + CHAR(13),'' ) 
                       +
                       '(SELECT case when count(distinct ' + convert(varchar(10),object_id) + ' ) > 0 then 1 else 0 end from sys.dm_db_index_usage_stats 
                         WHERE object_id = '+convert(varchar(10),object_id)
                         +'AND last_user_update > dateadd(minute, -1, getdate()) 
                        )'                          
FROM sys.dm_db_index_usage_stats
WHERE object_id in (object_id('table1'),object_id('table2'))
AND database_id = db_id(db_name())

SET @parms = N'@cnt int out'

EXEC sp_executesql @SQL, @parms, @cnt = @result out

select @result