对于存储在列中的 JSON 数组中的每个元素,如何将行拆分为一行?

How can I split rows into one row for each element in a JSON array stored in a column?

好吧,这很难解释,但我会试一试。 Google 没有帮助我所以如果它可以帮助其他人请更新这个问题。

背景

我有一个 table、Persons,其中有一些列,例如 [ID]、[Name] 和 [PhoneNumbers]。 table 正在填充来自第三方系统的数据,因此我无法更改插入数据的方式。

[PhoneNumbers] 列包含一个 JSON 数字数组,如下所示:

{"phonenumbers":[]}

我现在正尝试针对该 table 编写一个视图,目标是每个数字占一行。

问题

我可以使用 T-SQL 实现它吗?它有 JSON 支持?我正在使用 SQL Server 2016。

declare @j nvarchar(max) = N'{"phonenumbers":["1a", "2b", "3c", "4", "5", "6", "7", "8", "9", "10x"]}';

select value, *
from openjson(@j, '$.phonenumbers');

declare @t table
(
id int identity,
phonenumbers nvarchar(max)
);

insert into @t(phonenumbers)
values(N'{"phonenumbers":["1a", "2b", "3c", "4d"]}'), (N'{"phonenumbers":["22", "23", "24", "25"]}'), (N'{"phonenumbers":[]}'), (NULL);

select id, j.value, j.[key]+1 as phone_no_ordinal, t.*
from @t as t
outer apply openjson(t.phonenumbers, '$.phonenumbers') as j;