Skip to content
Advertisement

How to split an array of objects in SQL?

I have a table in my database which has the following columns:

Now, I want to split the data column into two columns in a select statement (which is used elsewhere). The first column Score1 will have the data present in the first object’s answer field i.e 1.5 for the ID=1 and the second column Score2 will have the data present in the second object’s answer field i.e 0.5 for ID=1, if there is null then the value should be null/0.

The maximum number of scores will be 2 i.e two objects. So, I will need to extract two columns called Score1 and Score2

The result of the select statement should be like this:

select ID, ‘some magic happens here’ as Score1, ‘some magic again’ as Score2 from score;

Any help is appreciated. Thank you

Advertisement

Answer

If you use SQL Server 2016+, you may use JSON_VALUE() to parse the stored JSON and extract the values. Note, that the result from JSON_VALUE() is a single text value of type nvarchar(4000).

Table:

Statement:

Result:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement