Assign result of dynamic sql to variable

前端 未结 5 1106
难免孤独
难免孤独 2020-11-30 06:20

I\'m doing dynamic SQL to convert all columns in a table a string

so After after all I do

EXEC(@template); 

where @template is the

5条回答
  •  孤街浪徒
    2020-11-30 06:59

    Most of these answers use sp_executesql as the solution to this problem. I have found that there are some limitations when using sp_executesql, which I will not go into, but I wanted to offer an alternative using EXEC(). I am using SQL Server 2008 and I know that some of the objects I am using in this script are not available in earlier versions of SQL Server so be wary.

    DECLARE @CountResults TABLE (CountReturned INT)
    DECLARE 
        @SqlStatement VARCHAR(8000) = 'SELECT COUNT(*) FROM table'
        , @Count INT
    
    INSERT @CountResults
    EXEC(@SqlStatement)
    
    SET @Count = (SELECT CountReturned FROM @CountResults)
    SELECT @Count
    

提交回复
热议问题