我有一个子表,比如:
select id from (values(1),(3)) as x(id)
我现在希望输出json:
{
"n":"N",
"ids":[1,3]
}
sql 该怎么写呢?
select
'N' as n,
json_query((select id from
(values(1),(3)) as x(id)
for json auto) ) as x
for json path
得到的输出是:
[
{
"n": "N",
"x": [
{
"id": 1
},
{
"id": 3
}
]
}]
非我所愿,就是写不来直接出int数组。
请大神帮忙。
CREATE FUNCTION
[dbo].ufn_RawJsonArray returns nvarchar(max)
AS BEGIN
declare @new nvarchar(max) = replace(@json, CONCAT('},{"', @key,'":'),',')
return '[' + substring(@new, 1 + (LEN(@key)+5), LEN(@new) -2 - (LEN(@key)+5)) + ']'
END
执行
select
'N' as n,
json_query(dbo.ufn_RawJsonArray ) as x
for json path
输出 [{"n":"N","x":[1,3]}]