我的表中有一个列保存的json数据:
rxjs@^5.0.0
是否可以获得如下结果:
declare @json nvarchar(max)
set @json = N'
{
"Companies": [
{
"CompanyId": "A",
"Employee": null
},
{
"CompanyId": "B",
"Employee": [
{
"EmployeePictureId": null,
"Name": "Employee1"
},
{
"EmployeePictureId": "PictureId2",
"Name": "Employee2"
}
]
},
{
"CompanyId": "C",
"Employee": [
{
"EmployeePictureId": null,
"Name": "Employee3"
},
{
"EmployeePictureId": null,
"Name": "Employee4"
}
]
}
]
}
'
使用{
"EmployeePictureIds": ["PictureId2"]
}
,Json_Query
,Json_Value
...
仅获取OPENJSON
并跳过空(null)数据
顺便说一下,数组中元素的数量是不确定的。
答案 0 :(得分:0)
在SQL Server 2017中,您可以使用以下查询:
select json_query(QUOTENAME(STRING_AGG('"' + STRING_ESCAPE( A.EmployeePictureId , 'json')
+ '"', char(44)))) as [EmployeePictureIds]
FROM OPENJSON(@json, '$.Companies')
WITH
(
CompanyId NVARCHAR(MAX),
Employee NVARCHAR(MAX) as json
) as B
cross apply openjson (B.Employee)
with
(
EmployeePictureId VARCHAR(50),
[Name] VARCHAR(50)
) as A
where A.EmployeePictureId is not null
for json path , WITHOUT_ARRAY_WRAPPER
您提供的JSON的结果:
添加另一个非空EmployeePictureId
的结果: