我有以下数据;
DECLARE @json NVARCHAR(2048) = N'{
"searchId": -1,
"statuses": [
33,
85,
90
]
}';
并使用以下命令执行返回;
SELECT searchID
,x.statuses
FROM OpenJson(@json) WITH (
searchID VARCHAR(200) '$.searchId'
,statuses NVARCHAR(MAX) '$.statuses' AS JSON
)
CROSS APPLY OPENJSON(statuses, '$') WITH (statuses int '$') AS x
返回;
searchID statuses
-1 33
-1 85
-1 90
它可以工作,但是id像返回一样是一行,因此“状态”列将显示为
searchID statuses
-1 33,85,90
我主要使用Stuff()和ForXML进行了一些实验,但是我认为必然会有更清洁的方式来处理json吗?
答案 0 :(得分:1)
您可以仅将状态保留为JSON,然后将演示文稿保留在前端。
DECLARE @json NVARCHAR(2048) = N'{
"searchId": -1,
"statuses": [33,85,90]
}';
SELECT searchID
,x.statuses
FROM OpenJson(@json) WITH (
searchID VARCHAR(200) '$.searchId'
,statuses NVARCHAR(MAX) '$.statuses' AS JSON
) x
输出
searchID statuses
--------------------- -----------
-1 [33,85,90]
或者只是从JSON数组中删除“ [”和“]”:
DECLARE @json NVARCHAR(2048) = N'{
"searchId": -1,
"statuses": [33,85,90]
}';
SELECT searchID
,substring(x.statuses,2,LEN(x.statuses)-2) statuses
FROM OpenJson(@json) WITH (
searchID VARCHAR(200) '$.searchId'
,statuses NVARCHAR(MAX) '$.statuses' AS JSON
) x
输出
searchID statuses
--------------------- -----------
-1 33,85,90
答案 1 :(得分:0)
STRING_AGG
返回到varchar
。
DECLARE @json NVARCHAR(2048) = N'{
"searchId": -1,
"statuses": [
33,
85,
90
]
}';
--
SELECT searchID, string_agg(x.statuses, ',') statuses
FROM OpenJson(@json) WITH (
searchID VARCHAR(200) '$.searchId'
,statuses NVARCHAR(MAX) '$.statuses' AS JSON
)
CROSS APPLY OPENJSON(statuses, '$') WITH (statuses int '$') AS x
GROUP BY searchID;