0

In SQL Server 2016, FOR JSON PATH allows for the whole result set returned as a JSON string. Is there a way to get a regular record set with some columns as JSON?

For e.g. for a Products (Master) and Orders (Details) table when joined together, I would like the query to return the result set from the Products table as regular tabular columns, but those multiple rows for each product from the Orders table returned as a JSON column.

Until now I have been doing this using a user-defined scalar function to which the product ID was passed and it returned JSON formatted Orders data, but I was hoping if there was a cleaner way of doing it.

1 Answer 1

2

Yes. Something like:

select SalesOrderId, OrderDate, TotalDue, d.Details
from SalesLT.SalesOrderHeader h
cross apply 
(
    select * 
    from SalesLT.SalesOrderDetail d
    where d.SalesOrderId = h.SalesOrderId
    for json path
)  d(details)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Never thought of CROSS APPLY. I wonder if the execution plan is efficient than the inline scalar user-defined function I have been using. If nothing else, your solution helps me avoid creating UDFs in the database if there is only one time use for them.

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.