I am trying to create a JSON object containing an array using SQL Server 2016.
The source data for the array is JSON itself, so I use JSON_QUERYthe select statement inside, and the FOR JSON clause applies to the select statement.
Everything works beautifully until I complete the sentence JSON_QUERYin the instruction CASE(in some cases, the array should not be included, i.e. it should be zero).
The following code illustrates the problem:
declare @projects nvarchar(max) = '{"projects": [23439658267415,166584258534050]}'
declare @id bigint = 123
SELECT
[data.array1] = JSON_QUERY(@projects, '$.projects')
, [data.array2] = CASE WHEN 1 is NOT NULL
THEN JSON_QUERY(@projects, '$.projects')
ELSE NULL END
, [data.array3] = CASE WHEN @id is NOT NULL
THEN JSON_QUERY(@projects, '$.projects')
ELSE NULL END
FOR JSON PATH, without_array_wrapper
This code returns the following JSON:
{
"data":{
"array1": [23439658267415,166584258534050],
"array2": [23439658267415,166584258534050],
"array3":"[23439658267415,166584258534050]"
}
}
The problem is that the third "array" is returned as a string object.
I expect it to return the following JSON:
{
"data":{
"array1": [23439658267415,166584258534050],
"array2": [23439658267415,166584258534050],
"array3": [23439658267415,166584258534050]
}
}
FOR JSON PATH..., , , (.. nvarchar, JSON_QUERY, ).
, JSON?