0

I have a query like (simplified):

SELECT 
    JSON_QUERY(r.SerializedData, '$.Values') AS [Values] 
FROM 
    <TABLE> r 
WHERE ...

The result is like this:

{ "201902":121, "201903":134, "201904":513 }

How can I change this in SQL to:

{ "2019-02-01":121, "2019-03-01":134, "2019-04-01":513 }

Meaning after the year (4 digits) add an '-' and end the key with '-01'.

1
  • What is your SQL Server version? Commented Feb 12, 2020 at 17:05

1 Answer 1

1

For SQL2017 and later, you could use the example of renaming a key (which might be a bit cumbersome and might not work properly in case of duplicate keys)

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);

Or handle json as a string with a simple REPLACE()

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.