Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create one json per one table row

I would like to create jsons from the data in the table. Table looks like that:

|code  |
+------+
|D5ABX0|
|MKT536|
|WAEX44|

I am using FOR JSON PATH which is nice:

SELECT [code]
FROM feature
FOR JSON PATH

but the return value of this query are three concatenated jsons in one row:

   |JSON_F52E2B61-18A1-11d1-B105-00805F49916B              |
+----------------------------------------------------------+
1  |[{"code":"D5ABX0"},{"code":"MKT536"},{"code":"WAEX44"}]|

I need to have each row to be a separate json, like that:

   |JSON_return       |
+---------------------+
1  |{"code":"D5ABX0"} |
2  |{"code":"MKT536"} |
3  |{"code":"WAEX44"} |

I was trying to use splitting function (CROSS APPLY) which needs to have a separator as a parameter but this is not a robust solution as the json could be more expanded or branched and this could separate not the whole json but the json inside the json:

;WITH split AS (
SELECT [json] = (SELECT code FROM feature FOR JSON PATH)
)
SELECT
     T.StringElement
FROM split S
CROSS APPLY dbo.fnSplitDelimitedList([json], '},{') T

The output is:

   |StringElement     |
+---------------------+
1  |[{"code":"D5ABX0" |
2  |"code":"MKT536"   |
3  |"code":"WAEX44"}] |

Is there a way to force sqlserver to create one json per row?

like image 924
PierekEast Avatar asked Dec 24 '22 07:12

PierekEast


1 Answers

You'll need to use as subquery to achieve this; FOR JSON will create a JSON string for the entire returned dataset. This should get you what you're after:

CREATE TABLE #Sample (code varchar(6));
INSERT INTO #Sample
VALUES ('D5ABX0'),
       ('MKT536'),
       ('WAEX44');

SELECT (SELECT Code
        FROM #Sample sq
        WHERE sq.code = S.code
        FOR JSON PATH)
FROM #Sample S;
DROP TABLE #Sample;
like image 103
Larnu Avatar answered Jan 03 '23 00:01

Larnu