Create nested JSON arrays using FOR JSON PATH

前端 未结 2 1694
不知归路
不知归路 2020-12-01 18:20

I need to create a JSON output from a query that uses inner join between two tables with a one to many relationship.
I would like the values of the secondary table to be

2条回答
  •  再見小時候
    2020-12-01 18:52

    You can use the following query:

    SELECT pr.person_id AS [person.id], pr.person_name AS [person.name],
        (
            SELECT pt.pet_id AS id, pt.pet_name AS name 
            FROM @Pets pt WHERE pt.pet_owner=pr.person_id 
            FOR JSON PATH
        ) AS [person.pet]
    FROM @Persons pr 
    FOR JSON PATH, ROOT('pet owners')
    

    For more information, see https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/10/09/returning-child-rows-formatted-as-json-in-sql-server-queries/

提交回复
热议问题