SQL Server中的OpenJson是否可嵌套json数据?

时间:2018-11-14 16:26:10

标签: json sql-server open-json

我有一个像这样的json数据:

[
    {"id": 1}, {"id": 3}, {"id": 2, "children": [{"id": 4}, {"id": 5}]} 
]

请帮助我如何将这些数据解析为关系数据:

Column: Id     Order/Index    ParentId
---------------------------------------
        1      1              0   
        3      2              0
        2      3              0
        4      4              2
        5      5              2  

1 个答案:

答案 0 :(得分:1)

此请求中有两点很重要的事情。首先是按文档位置对结果行进行排序,当您使用OPENJSON…WITH投影列时,该位置不可见。第二个是您需要一个层次查询(假设可能有多个级别)。

无论如何,是这样的:

declare @doc nvarchar(max) = N'[{"id":1},{"id":3},{"id":2,"children":[{"id":4},{"id":5}]}]';

with q as
(
    select [key] nodePath, 
           cast(json_value(d.[value],'$.id') as int) Id,
           cast(null as int) ParentId,
           cast(json_query(d.[value],'$.children') as nvarchar(max)) children
    from openjson(@doc) d
    union all
    select q.nodePath + '.' + d.[key] nodePath, 
           cast(json_value(d.[value],'$.id') as int) Id,
           q.id ParentId, 
           cast(json_query(d.[value],'$.children') as nvarchar(max)) children
    from q
    outer apply openjson(q.children) d
    where q.children is not null
)
select Id, row_number() over (order by nodePath) [Order/Index], ParentId
from q
order by [Order/Index]

输出

Id          Order/Index          ParentId
----------- -------------------- -----------
1           1                    NULL
3           2                    NULL
2           3                    NULL
4           4                    2
5           5                    2

(5 rows affected)