I'm trying to take a JSON object which has an array inside of it, and break it out into corresponding rows.
I Have the following JSON object:
{
"CompID":["1","20","22"],
"Date":"21122005",
"ID":"12",
"Total":"5"
}
This is what I'm trying to get this from the JSON object:
Date ID Total CompID 21122005 12 5 1 21122005 12 5 20 21122005 12 5 22
This is my SQL Code:
Declare @Json varchar(max) = '{"CompID":["1","20","22"],
"Date":"21122005",
"ID":"12",
"Total":"5"}'
Select A.Date, A.ID, A.Total,
B.CompID
From OpenJson(@Json)
With(
Date varchar(12)
,ID varchar(10)
,Total varchar(4)
,CompID varchar(3) '$.CompID'
)A
OUTER APPLY OPENJSON(JSON_QUERY(@Json,'$.CompID'))
WITH(CompID NVARCHAR(MAX) AS JSON) B
With the above code it returns the three rows that I need, but I get Null values in the CompID column.
Date ID Total CompID 21122005 12 5 NULL 21122005 12 5 NULL 21122005 12 5 NULL
How do I replace the Null values with the correct CompID numbers?