0

How to make the query below work?

I used the concept from another question SQL Server 2016 JSON: Select array of strings instead of array of objects

But when I tried the select below it doesn't work

SELECT
    (SELECT line AS "line"  
     FROM
         (SELECT 
              CONCAT('5th', ' ', '566') AS "line"
          UNION ALL
          SELECT 'Complement' AS LINE
         )
     FOR JSON PATH) AS "address.lines"

The version of the SQL Server SELECT @@VERSION = Microsoft SQL Server 2016

The result from the query is

Msg 156, Level 15, State 1, Line 11
Incorrect syntax near the keyword 'FOR'.

The excepted result is [{"line":"5th 566"},{"line":"Complement"}], with this result I will use the function from SQL Server 2016 JSON: Select array of strings instead of array of objects to remove "line" and get the final result ["5th 566","Complement"]

I need to use the UNION ALL because I have two different values from the same table to result in an array called address.lines at the JSON result

2
  • How doesn't it work? Commented Nov 21, 2019 at 13:45
  • What is the expected output? Commented Nov 21, 2019 at 13:48

1 Answer 1

6

If I understand your question correctly, you just need an alias (t) to solve this error:

Statement:

SELECT (
    SELECT [Line] FROM (
        SELECT CONCAT('5th', ' ',  '566') AS [Line]
        UNION ALL
        SELECT 'Complement' AS [Line]
    ) t
    FOR JSON PATH
)
AS "address.lines"

Output:

address.lines
[{"Line":"5th 566"},{"Line":"Complement"}]

Of course, you can use only JSON functions to generate the final JSON output:

Statement:

DECLARE @json nvarchar(max) = N'[]'
SELECT @json = JSON_MODIFY(@json, 'append $', [Line])
FROM (
   SELECT CONCAT('5th', ' ',  '566') AS [Line]
   UNION ALL
   SELECT 'Complement' AS [Line]
) t
SELECT @json AS [address.lines]

Output:

address.lines
["5th 566","Complement"]
Sign up to request clarification or add additional context in comments.

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.