1

I would like to create a column that contains JSON with fields calculated based on another table columns. Of course, I can make that as below but that works fine only if the case is quite simple, and still, it is easy to make mistake. Is it a more convenient way to build JSON inside of query?

SELECT 
    1 AS id, 'AAA' AS ProductCode, 
    'Camera' AS Product, 5000 AS Price 
INTO
    #tmp
UNION
SELECT 
    2 AS id, 'BBB' AS ProductCode, 
    'Tripod ' AS Product, 80 AS Price
UNION
SELECT 
    3 AS id, 'CCC' AS ProductCode, 
    'Objective ' AS Product, 7000 AS Price

 
SELECT 
    ProductCode,
    '{' +  '"Product":"' + Product + '"' + ', '
        +  '"Price":"' + cast (Price as nvarchar) 
        +  '"}' AS Details     
FROM  
    #tmp

1 Answer 1

4

You may use FOR JSON, but you need at least SQL Server 2016:

SELECT 
   ProductCode,
   (SELECT Product, Price FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) AS Details      
FROM #tmp

Starting from SQL Server 2022, you may use JSON_OBJECT():

SELECT 
   ProductCode,
   JSON_OBJECT('Product': Product, 'Price': Price) AS Details      
FROM #tmp
Sign up to request clarification or add additional context in comments.

1 Comment

This is a fantastic method for creating a query that returns a mix of standard columns and JSON columns.

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.