0

我有以下 SQL“产品”表结构:

int Id
nvarchar(max) Details

详细信息包含 JSON 一个具有以下结构的字符串:

{
"Id": "10001",
"Description": "example description",
"Variants": [{
        "Title": "ABC / no",
        "Price": "10"
    }, {
        "Title": "ABC / Yes",
        "Price": "20",
    }, {
        "Title": "ABC / Yes",
        "Price": "30",
    }]
}

我需要编写一个 SQL 查询来查看表并返回具有特定标题的所有变体。


以下作品

从表中获取详细信息字段包含特定标题的所有行

SELECT * FROM Products 
WHERE JSON_VALUE(Details, '$.Description') = 'example description'

从表中获取 Details.Variants[0].Title 等于 '{string}' 的所有行

SELECT * FROM Products 
WHERE JSON_VALUE(Details, '$.Variants[0].Title') = 'ABC / no'

从 Details.Variants[0].Title 等于 '{string}' 的表中获取所有Id

SELECT JSON_VALUE(Details, '$.Id') 
FROM Products 
WHERE JSON_VALUE(Details, '$.Variants[0].Title') = 'ABC / no'

我需要从 Product 表中的所有行中获取所有变体,其中 Variant 标题等于“{string}”

文档中有一个类似的示例, 但我无法让它适用于我的特殊情况。

还有这个堆栈帖子

4

1 回答 1

0

您需要使用OPENJSON()显式模式(列定义)和附加APPLYs 来解析输入 JSON 并获得预期结果。请注意,您需要使用AS JSON选项来指定$.Variants存储的 JSON 的一部分是 JSON 数组。

桌子:

CREATE TABLE Products (Id int, Details nvarchar(max))
INSERT INTO Products (Id, Details)
VALUES (1, N'{"Id":"10001","Description":"example description","Variants":[{"Title":"ABC / no","Price":"10"},{"Title":"ABC / Yes","Price":"20"},{"Title":"ABC / Yes","Price":"30"}]}"')

陈述:

SELECT p.Id, j1.Id, j1.Description, j2.Title, j2.Price
FROM Products p
CROSS APPLY OPENJSON (p.Details, '$') WITH (
    Id int '$.Id',
    [Description] nvarchar(100) '$.Description',
    Variants nvarchar(max) '$.Variants' AS JSON
) j1
CROSS APPLY OPENJSON(j1.Variants) WITH (
    Title nvarchar(100) '$.Title',
    Price nvarchar(10) '$.Price'
) j2
WHERE 
   j2.Title = 'ABC / no'
   -- or j1.Description = 'example description'

结果:

Id  Id      Description         Title       Price
1   10001   example description ABC / no    10
于 2020-06-18T12:52:17.063 回答