Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving and using the output from a "FOR JSON" query in a variable

I'm aware of the option to output a query formatted as JSON, like the following example from the from MSDN page:

SELECT name, surname  
FROM emp  
FOR JSON AUTO 

There are a lot of samples on how to use the resulting json from apps but my question is, how can I store the resulting json in a varchar variable, let's say to store in another table?

like image 419
Alberto Silva Avatar asked Jan 05 '23 03:01

Alberto Silva


1 Answers

DECLARE @Json nvarchar(MAX) = (
    SELECT name, surname  
    FROM emp  
    FOR JSON AUTO
);

Dan Guzman replied in the MSDN Forum with this neat solution, which corresponds also to @FDavidov's suggestion in his last comment

like image 109
Alberto Silva Avatar answered Jan 14 '23 06:01

Alberto Silva