如何使用服务器 2016 中的新 tsql json 获取结果中的 json 数组值?

How can I get json array values in result using the new tsql json from server 2016?

我有一个简单的 json,里面有一个数组。

{
  "state": "Succeeded",
  "ip": [
    "137.117.198.99","137.117.198.100"
  ]  
}

我想通过简单的 sql 将其转换为 tsql 结果。结果应该看起来像一个简单的主从关系。

我希望是这样的:

state        ip
Succeeded    137.117.198.99
Succeeded    137.117.198.100

我从 2016 年开始用 tsql json 尝试过,交叉应用如下:

declare @json nvarchar(max) =  '{
  "state": "Succeeded",
  "ip": [
    "137.117.198.99","137.117.198.100"
  ]  
}';

select
    network.[state], 
    ips.ip
from  openjson (@json)
with
(
    [state] nvarchar(100),
    ip nvarchar(max) as json
)
as network
cross apply openjson (network.ip)
with
(
    ip nvarchar(100)
) as ips
;

结果似乎朝着正确的方向发展(2 行,但数组中的值是 null),但是对于数组我无法映射值。

有没有人运行遇到同样的情况并且知道解决办法?

感谢 Dietmar

你的查询几乎是准确的,我认为你只需要删除第二个 with 子句(因为你的内部数组中没有 ip 字段)和 select value 列来自 ips 而不是 ip:

declare @json nvarchar(max) =  '{
  "state": "Succeeded",
  "ip": [
    "137.117.198.99","137.117.198.100"
  ]  
}';

select
    network.[state], 
    ips.value as ip
from  openjson (@json)
with
(
    [state] nvarchar(100),
    ip nvarchar(max) as json
)
as network
cross apply openjson (network.ip)
as ips
;

这是此命令的输出: