1

I am really new to Json & SQL Server. Since SQL Server 2016 can support Json values, i have a task in hand.

I have a SQL table with a CustomeID (int) Field & another field that holds a json array value which holds different elements that belongs to that unique customer.

Ex:

Customer ID | JsonCol 
55          | [{"Id":"12","Height":"150","Weight":"75","Colour":"White"}, 
              {"Id":"15","Height":"160","Weight":"85","Colour":"Brown"}]
65          | [{"Id":"16","Height":"155","Weight":"65","Colour":"Red"}, 
              {"Id":"20","Height":"167","Weight":"55","Colour":"Black"}]

I would like to do a query in SQL Server to get the following outcome, I dont know how to insert tables into this. But basically the output should repeat the Customer for every combination of data that the array has in the Json field

CustomerID   | ID | Height | Weight | Colour
55           | 12 | 150    | 75     | White
55           | 15 | 160    | 85     | Brown
65           | 16 | 155    | 65     | Red
65           | 20 | 167    | 55     | Black

Can someone so kindly give me an idea where to start. I have already tried all Microsoft articles around Json support.

Thank you in advance.

1 Answer 1

4

Use OPENJSON with the default output to get the array elements and then OPENJSON output with an explicit structure to get the elements. Put it together with CROSS APPLYs.

SELECT CustomerID,
       x.Id,
       x.Height,
       x.Weight,
       x.Colour
       FROM Customer C
       CROSS APPLY (SELECT *
                           FROM OPENJSON(C.JsonCol)
                           CROSS APPLY OPENJSON(value)
                                 WITH (Id integer '$.Id',
                                       Height integer '$.Height',
                                       Weight integer '$.Weight',
                                       Colour nvarchar(8) '$.Colour')) x;

SQL Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. The more i read it - the more i understood what it was doing. Thank you so much. Really appreciated!

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.