1

I want to convert value of column into an array. But I don't know how. Can anyone help?

Below is the structure of table that I want to change.

enter image description here

[{"entity":"Job","value":"400072 "},{"entity":"Job","value":"400087"}]

Expected result:

enter image description here

[{"entity":"Job","value":[400072, 400087]}]

The code I tried :

SELECT (
   SELECT ose.TaggedEntity AS 'entity', ose.TaggedEntityId AS 'value'
   FROM #OldSharedEntity AS ose
   WHERE ose.TaggedEntityId NOT IN (
      SELECT nse.TaggedEntityId 
      FROM #NewSharedEntity AS nse
   ) 
   FOR JSON PATH, INCLUDE_NULL_VALUES
) AS json
6
  • What is your SQL Server version and do you want to generate a JSON array? Commented Apr 18, 2020 at 16:19
  • My SQL Server version is Microsoft SQL Server 2016 (SP2-CU2) (KB4340355) - 13.0.5153.0 (X64). Is it possible?? Commented Apr 18, 2020 at 16:23
  • yes... but i want those value to be in comma separated [a,b,c] not as a string Commented Apr 18, 2020 at 16:25
  • the code convert that into JSON array but i want the value in [a,b,c] format... Commented Apr 18, 2020 at 16:27
  • Thank You @Zhorov I have edited m question and included the code that I tried. Commented Apr 18, 2020 at 16:39

1 Answer 1

2

If your table's name #yourtable You can try this

   SELECT entity,
      (Select  JSON_QUERY('['+ STRING_AGG(value,',')+']') 
        FROM #yourtable t2 where t2.entity=entity)  value
     FROM #yourtable t 
     GROUP BY entity FOR JSON PATH
Sign up to request clarification or add additional context in comments.

1 Comment

It's worth highlighting that STRING_AGG isn't available on SQL Server 2016 (the version mentioned by the question author in the question 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.