首页 > 解决方案 > 获取 MS SQL Server 中多个 JSON 字符串中数组中多个 Int 的计数

问题描述

我一直在搜索这个主题,我正在寻找处理字符串但不是关于数组的示例。我从存储在单个列中的 JSON 字符串开始,看起来像这样......

查询一

然后我可以使用这个查询来提取每条记录的 Ids 部分......

SELECT Id, Message,
    JSON_QUERY(Message, 'strict$.Ids') AS Ids
FROM ActionQueue
WHERE Status = 1
    AND (Action = 'Approve' OR Action = 'Reject')

识别结果

我现在需要将这些数组(不确定它们是否是看起来像数组的字符串?)组合成一个数组。

我需要使用该 Id 列表来传递给存储过程以及获取 Id 的计数。

标签: sqlsql-server

解决方案


declare @t table(thejsoncolumn nvarchar(max));

insert into @t(thejsoncolumn)
values(N'{"Ids":[1, 2, 3, 4, 5]}'), (N'{"Ids":[7]}'), (N'{"Ids":[6, 9, 10, 11]}');

select stuff(
(select concat(',', value)
--string_agg(value, ',') within group (order by cast(value as int)) AS thelist
from
(
select distinct j.value
from @t as t
cross apply openjson(t.thejsoncolumn, '$.Ids') as j
) as src
order by cast(value as int)
for xml path('') --..numbers only
), 1, 1, '');

推荐阅读