Вы можете попробовать следующий подход, который вернет полные данные:
DECLARE @json nvarchar(max)
SET @json = N'[ { "id": 1, "fruit": "orange", "values": [ { "name": "Colour", "value": "Orange" }, { "name": "Weight", "value": "16" }, { "name": "Calories", "value": "25" } ] }, { "id": 23, "fruit": "Banana", "values": [ { "name": "Colour", "value": "Yellow" }, { "name": "Weight", "value": "30" }, { "name": "Calories", "value": "250" } ] } ]'
SELECT i.id, i.fruit, v.[name], v.[value]
FROM OPENJSON(@json)
WITH (
id int '$.id',
fruit nvarchar(50) '$.fruit',
[values] nvarchar(max) '$.values' AS JSON
) AS i
CROSS APPLY (
SELECT *
FROM OPENJSON(i.[values])
WITH (
[name] nvarchar(max) '$.name',
[value] nvarchar(max) '$.value'
)
) v
Вывод:
id fruit name value
1 orange Colour Orange
1 orange Weight 16
1 orange Calories 25
23 Banana Colour Yellow
23 Banana Weight 30
23 Banana Calories 250
Если вы хотите выводить информацию о цвете и весе, попробуйте это:
DECLARE @json nvarchar(max)
SET @json = N'[ { "id": 1, "fruit": "orange", "values": [ { "name": "Colour", "value": "Orange" }, { "name": "Weight", "value": "16" }, { "name": "Calories", "value": "25" } ] }, { "id": 23, "fruit": "Banana", "values": [ { "name": "Colour", "value": "Yellow" }, { "name": "Weight", "value": "30" }, { "name": "Calories", "value": "250" } ] } ]'
SELECT i.id, i.fruit, v1.[value] AS Colour, v2.[value] AS Weight
FROM OPENJSON(@json)
WITH (
id int '$.id',
fruit nvarchar(50) '$.fruit',
[values] nvarchar(max) '$.values' AS JSON
) AS i
OUTER APPLY (
SELECT *
FROM OPENJSON(i.[values])
WITH (
[name] nvarchar(max) '$.name',
[value] nvarchar(max) '$.value'
)
WHERE [name] = 'Colour'
) v1
OUTER APPLY (
SELECT *
FROM OPENJSON(i.[values])
WITH (
[name] nvarchar(max) '$.name',
[value] nvarchar(max) '$.value'
)
WHERE [name] = 'Weight'
) v2
Вывод:
id fruit Colour Weight
1 orange Orange 16
23 Banana Yellow 30