Following is the given JSON data:
DECLARE @Jdata NVARCHAR(MAX) =
'{
"EmployeeDetails": {
"BusinessEntityID": 3,
"NationalIDNumber": 509647174,
"JobTitle": "Engineering Manager",
"BirthDate": "1974-11-12",
"MaritalStatus": "M",
"Gender": "M",
"StoreDetail": {
"Store": [
{
"AnnualSales": 800000,
"AnnualRevenue": 80000,
"BankName": "Guardian Bank",
"BusinessType": "BM",
"YearOpened": 1987,
"Specialty": "Touring",
"SquareFeet": 21000
},
{
"AnnualSales": 300000,
"AnnualRevenue": 30000,
"BankName": "International Bank",
"BusinessType": "BM",
"YearOpened": 1982,
"Specialty": "Road",
"SquareFeet": 9000
}
]
}
}
}';
Need to display:
BusinessEntityID | AnnualSales | BusinessType
-------------------------------------------------
3 300000 BM
3 800000 BM
My try:
select *
from OPENJSON(@jdata)
WITH(
BusinessEntityID VARCHAR(20) '$.EmployeeDetails.BusinessEntityID',
AnnualSales integer '$.EmployeeDetails.StoreDetail.Store.AnnualSales',
BusinessType VARCHAR(100) '$.EmployeeDetails.StoreDetail.Store.BusinessType'
) as a
But getting wrong output.
BusinessEntityID | AnnualSales | BusinessType
-------------------------------------------------
3 NULL NULL
3
Answers
You need an additional
OPENJSON()
call and anAPPLY
operator to parse the nested JSON content. In this case you need to use theAS JSON
modifier in theWITH
clause to specify that the referenced property ($.EmployeeDetails.StoreDetail.Store
) contains an inner JSON array.Of course, a combination of
JSON_VALUE()
and oneOPENJSON()
call is also an option:You need two levels of
OPENJSON
. The first one needs to retrieve the inner array usingAS JSON
. Then you feed that into the next usingCROSS APPLY
.You can also put the
'$.EmployeeDetails'
path into theOPENJSON
call itself to avoid having to repeat itdb<>fiddle
To transform the given array of JSON objects into a table format in SQL Server, you can use the OPENJSON function. Here’s an example of how you can extract the desired columns BusinessEntityID, AnnualSales, and BusinessType:
This will give you the result in a table format with columns BusinessEntityID, AnnualSales, and BusinessType:
Make sure to replace
@Jdata
with the actual variable or JSON string you want to parse.