EN VI

Sql-server - Store variable SQL Statement into a json variable?

2024-03-10 22:30:04
How to Sql-server - 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

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login