Search code examples
sql-servert-sql

Store variable SQL Statement into a JSON variable


I want to store a FOR JSON AUTO output in a variable.

But I want to use a variable select statement.

Something like this:

SET @SQLString = 'SELECT ID, Name FROM ' + @TableName + ' ';

SET @Body = (
   @SQLString + 'FOR JSON AUTO'
); 

Solution

  • Like this

    declare @sql nvarchar(max) = 'select * from sys.objects'
    
    declare @forJsonSql nvarchar(max) = concat('select @json = (',@sql, ' for json auto)')
    
    --print @forJsonSql
    
    declare @json nvarchar(max)
    exec sp_executesql @forJsonSql, N'@json nvarchar(max) output', @json=@json output
    
    select @json