I'm trying to flatten out an object array that is constructed by FOR JSON
.
My query looks like:
select
(
select id from MyTable
where id in (select value from OPENJSON(@jsonArray))
FOR JSON PATH
) existing,
(
select value id from OPENJSON(@jsonArray)
where value not in (select Id from MyTable)
FOR JSON PATH
) missing
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
The resulting JSON is:
{
"existing": [
{
"id": "a00cd8f6-d1c6-4604-b235-59d3cacd5bcc"
},
{
"id": "052455b6-6bf5-47d3-8bee-7ba98d7fbd50"
}
],
"missing": [
{
"id": "328add2d-e8f2-4a0e-af54-5b1733310170"
}
]
}
What I would like instead is:
{
"existing": [
{
"id": "a00cd8f6-d1c6-4604-b235-59d3cacd5bcc"
},
{
"id": "052455b6-6bf5-47d3-8bee-7ba98d7fbd50"
}
],
"missing": [
"328add2d-e8f2-4a0e-af54-5b1733310170"
]
}
The missing array should not contain json-objects, just values. Any suggestions?
This is not as easy as it should be...
AFAIK there's no way to create a naked json array with sql-server. But you can trick this out on string level:
--This will create the object array you want
--And this will create the naked array using some rather ugly tricks.
--Now we have to combine both. And again we need a trick. We use
JSON_QUERY()
on the JSON literal to avoid escaped quotes.This ist the result
I have no idea, why this can't be done out-of-the-box...