我有一个类似(简化)的查询:
SELECT
JSON_QUERY(r.SerializedData, '$.Values') AS [Values]
FROM
<TABLE> r
WHERE ...
结果是这样的:
{ "201902":121, "201903":134, "201904":513 }
如何在SQL中将其更改为:
{ "2019-02-01":121, "2019-03-01":134, "2019-04-01":513 }
在年份之后(4位数字)意味着添加“-”并以“ -01”结束键。
答案 0 :(得分:1)
对于SQL2017及更高版本,您可以使用renaming a key的示例 (这可能有点麻烦,并且在键重复的情况下可能无法正常工作)
declare @j1 nvarchar(max);
select @j1 = N'{"201902":121, "201902":145, "201903":134, "201904":513}';
select @j1 as before;
select @j1 = JSON_MODIFY(JSON_MODIFY(@j1, concat('$."', left(a.[key], 4), '-', right(a.[key], 2), '-01"'), CAST(a.value AS int)), concat('$."', a.[key], '"'), null)
from openjson(@j1) as a;
select @j1 as after, isjson(@j1);
或使用简单的REPLACE()将json作为字符串处理
declare @j2 nvarchar(max);
select @j2 = N'{"201902":121, "201902":145, "201903":134, "201904":513}';
select @j2 as before;
select @j2 = replace(@j2, a.[key], concat(left(a.[key], 4), '-', right(a.[key], 2), '-', '01'))
--if keys appear as values...
--replace(@j2, concat('"', a.[key], '"'), concat('"', stuff(a.[key],5, 0, '-'), '-01"'))
from openjson(@j2) as a;
select @j2 as after, isjson(@j2);