Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT query to print as JSON list in one row [duplicate]

How to print names in string list in a single row?

Suppose that I have data like this:

SELECT XName FROM X_Table --(table has other columns too)

XName
-------------
Foo
Bar

How to get values like this:

["foo", "bar"]
like image 832
Chenna Avatar asked Nov 07 '25 08:11

Chenna


2 Answers

From the example given in G.Stoynev link, you can do the following:

SELECT JSON_QUERY
(
    (
        SELECT JSON_QUERY
        (
            '[' + STUFF(( SELECT ',' + '"' + convert(varchar(10), XName) + '"' 
            FROM dbo.X_Table
            FOR XML PATH('')),1,1,'') + ']' 
        ) Categories  
        FOR JSON PATH , WITHOUT_ARRAY_WRAPPER 
    ), '$.Categories' 
)
like image 146
gotqn Avatar answered Nov 09 '25 23:11

gotqn


I think you are looking at combination of JSON conversion and de-conversion syntax like below

See working demo

Declare @js nvarchar(max)

SET @js= (SELECT XName FROM X_Table for json path)

select * from  OPENJSON (@js) WITH ( Xname nvarchar(max) N'$.XName')

And if you want to avoid using a variable @js you can do

select * from  OPENJSON 
((SELECT XName FROM XTable for json path))-- note double parenthesis
WITH ( Xname nvarchar(max) N'$.XName')
like image 38
DhruvJoshi Avatar answered Nov 09 '25 23:11

DhruvJoshi