这个请求中有一些重要的事情。首先是按文档位置对结果行进行排序,当您使用 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)