I've a requirement to load the json input into a table which has multiple arrays
declare @json nvarchar(max);
set @json =
'{
"method":"email",
"value":"xxx@gmail.com",
"options":[
{
"type":"Regular",
"alerts":true,
"subsciptions":true
},
{
"type":"service",
"alerts":false,
"subsciptions":false
}
]
}'
So i wrote the below query to achieve that
SELECT a.Method,value
FROM
OPENJSON(@json)
WITH
(
method varchar(10) N'$.method'
,value varchar(100) N'$.value'
,options NVARCHAR(MAX) AS JSON
) AS a
CROSS APPLY
OPENJSON(a.options)
WITH
(
type varchar(100) N'$.type'
,alerts INT N'$.alerts'
,subscription varchar(10) N'$.subscription'
) AS b;
So, I'm getting the output as expected
method, value, type, alerts, subscription
email, xxx@gmail.com, Regular, true, true
email, xxx@gmail.com, service, true, true
Now the requirement has been changed regarding the multiple arrays, so sometimes the options array is available and sometimes they are not available,
I'm trying to write a query which can work for both the logics, so when there is no options array, the output should be like,
method, value, type, alerts, subscription
email, xxx@gmail.com, NULL, NULL, NULL
email, xxx@gmail.com, NULL, NULL, NULL
and when the options array is available, the output should be like,
method, value, type, alerts, subscription
email, xxx@gmail.com, Regular, true, true
email, xxx@gmail.com, service, true, true
Could you please help me write a query to achieve this logic