0

Given the following test data:

declare @mg nvarchar(max);
set @mg = '{"fiskepind":["ko","hest","gris"]}';

select @mg, JSON_VALUE(@mg,'$.fiskepind')

How do i get returned a column with:

   ko,hest,gris

Example returns: NULL, and i dont want to [index] to only get one returned.

2
  • Return each value as a dataset and then (string) aggregate. Commented Dec 2, 2022 at 10:49
  • 1
    What is your SQL Server version? Commented Dec 2, 2022 at 12:14

2 Answers 2

1

Starting from SQL Server 2017, a possible solution is a combination of OPENJSON() and STRING_AGG().

SELECT STRING_AGG([value], ',') WITHIN GROUP (ORDER BY CONVERT(int, [key])) AS Result
FROM OPENJSON(@mg, '$.fiskepind')

Note, that JSON_VALUE() returns a scalar value, so the NULL value is the expected result when you try to extract a JSON array ('$.fiskepind') from the input JSON text.

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

Comments

0

If you just want a combine list, you can use OPENJSON to get a table and then use FOR XML PATH or STRING_AGG to combine into a single string.

declare @mg nvarchar(max);
set @mg = '{"fiskepind":["ko","hest","gris"]}';

select @mg, JSON_VALUE(@mg,'$.fiskepind')
  , STUFF((
    SELECT
      ',' + value
    FROM OPENJSON(@mg, '$.fiskepind')
    FOR XML PATH('')
  ),1,1,'') as combined_list

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.