Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform json into table rows using sql

My initial table looks like this (values of object are dynamic so it’s not always the same structure):

id  tags 
1   {"tag1": "value1"} 
2   {"tagA": "valueA", "tagB": "valueB"}

And I want to transform it into this:

id tag   value 
1  tag1  value1 
2  tagA  valueA 
2  tagB  valueB

Could anyone help me with the transformation? I tried using OPENJSON like this but it only works if I filter by id (plus I’m not getting the id column in the result):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

DECLARE @json NVARCHAR(MAX)
SET  @json  =  (SELECT tags from auxTagsResources where instanceId = 1)
SELECT \[key\] as tagName, value as tagValue FROM OPENJSON(@json);

Result:

tagName tagValue
tag1    value1

>Solution :

You can apply to the json.

create table auxTagsResources (
 id int identity primary key, 
 instanceId int not null,
 tags nvarchar(max)
);

insert into auxTagsResources (instanceId, tags) values
  (1, N'{"tag1": "value1"}') 
, (1, N'{"tagA": "valueA", "tagB": "valueB"}');
SELECT tag.id, j.[key] as tag, j.[value] 
FROM auxTagsResources tag
CROSS APPLY OPENJSON(tag.tags) j
WHERE tag.instanceId = 1
id tag value
1 tag1 value1
2 tagA valueA
2 tagB valueB

Demo on db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading