[英]Cross apply with JSON array
You need two additional APPLY
operators with two different OPENJSON()
calls.您需要两个具有两个不同OPENJSON()
调用的额外APPLY
运算符。 First call is with default schema and the result is a table with columns key
, value
and type
.第一次调用使用默认架构,结果是一个包含key
、 value
和type
列的表。 The second call is with explicit schema with the appropriate columns, defined using the WITH
clause:第二个调用是使用带有适当列的显式架构,使用WITH
子句定义:
Table:桌子:
Table:桌子:
CREATE TABLE Data (
CustomerID int,
City nvarchar(50),
Product nvarchar(max)
)
INSERT INTO Data
(CustomerID, City, Product)
VALUES
(1, N'Delhi', N'[{"Products": [{"Id": "1", "Name": "TV"}, {"Id": "2", "Name": "Laptop"}]}]'),
(2, N'Bamgalore', N'[{"Products": [{"Id": "1", "Name": "TV"}, {"Id": "2", "Name": "Laptop"}, {"Id": "3", "Name": "Mobile"}]}]')
Statement:陈述:
SELECT d.CustomerID, j2.Id, j2.Name
FROM Data d
CROSS APPLY OPENJSON(d.Product, '$') j1
CROSS APPLY OPENJSON(j1.[value], '$.Products') WITH (
Id nvarchar(10) '$.Id',
Name nvarchar(50) '$.Name'
) j2
Result:结果:
----------------------
CustomerID Id Name
----------------------
1 1 TV
1 2 Laptop
2 1 TV
2 2 Laptop
2 3 Mobile
You can apply the arrays, to get to the object values.您可以应用数组来获取对象值。
SELECT t.CustomerId, a.*
FROM YourCustomerProductsTable t
OUTER APPLY
(
SELECT
[ProductId] = CAST(JSON_VALUE(obj.value,'$.Id') AS INT)
, [Product] = JSON_VALUE(obj.value,'$.Name')
FROM OPENJSON(t.Product) AS arr
CROSS APPLY OPENJSON(arr.value, '$.Products') AS obj
) a;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.