I have a query that dynamically builds a SELECT statement in SQL, and outputs as per the example below (note there can be as many as 50 select statements, each unique per email);
Age | Gender | |
---|---|---|
[email protected] | 96 | Male |
Age | AddressLine1 | Country | |
---|---|---|---|
[email protected] | 36 | 1 Laneview Way | England |
I would like to combine the output of the two (or more) queries, into one JSON object, if possible, so it would output like below;
[
{
"Email":"[email protected]",
"Age":"96",
"Gender":"Male"
},
{
"Email":"[email protected]",
"Age":"36",
"AddressLine1":"1 Laneview Way",
"Country":"England"
}
]
My current attempt in SQL is as follows;
SELECT User_Alias = JSON_QUERY(query1.json_result), User_Alias2 = JSON_QUERY(query2.json_result) FROM
(
SELECT Email,
Age,
Gender
FROM tableAbc
WHERE Email = '[email protected]'
FOR JSON PATH
) AS query1 (json_result)
,(
SELECT Email,
Age,
AddressLine1,
Country
FROM tableAbc
WHERE Email = '[email protected]'
FOR JSON PATH
) AS query2 (json_result)
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
2
Answers
It was written in two ways with two values and one value
Two values(User_Alias,User_Alias2)
one values
dbfiddle:https://dbfiddle.uk/tZaEDwIE
It looks like what you should actually be doing is just using
NULL
for the columns you don’t want to show. Any null columns are simply not serialized into the JSON at all, unless you specifyINCLUDE_NULL_VALUES
.This assumes those columns are already null for those rows. If they are not then you need some
CASE
expressionsdb<>fiddle