I'm using Microsoft SQL Server 2016. This version supports JSON.
I have a Person table with the following data:
| PersonId | FatherId | Name |
|---|---|---|
| 1 | NULL | 4th Grand Father |
| 2 | 1 | 3rd Grand Father |
| 3 | 2 | 2nd Grand Father |
| 4 | 3 | Grand Father |
| 5 | 4 | Father |
| 6 | 4 | Uncle |
| 7 | 6 | Cousin |
| 8 | 5 | Brother |
| 9 | 5 | Me |
I run the following query:
WITH Persons_CTE AS(
SELECT PersonId, FatherId, Name FROM Persons WHERE FatherId IS NULL
UNION ALL
SELECT P.PersonId, P.FatherId, P.Name FROM Persons P JOIN Persons_CTE PCTE
ON PCTE.PersonId = P.FatherId)
SELECT P.Name as Name, PCTE.Name as Children FROM Persons_CTE PCTE LEFT JOIN Persons P
ON P.PersonId = PCTE.FatherId
FOR JSON PATH
The query generates the following result:
[
{
"Children":"4th Grand Father"
},
{
"Name":"4th Grand Father",
"Children":"3rd Grand Father"
},
{
"Name":"3rd Grand Father",
"Children":"2nd Grand Father"
},
{
"Name":"2nd Grand Father",
"Children":"Grand Father"
},
{
"Name":"Grand Father",
"Children":"Father"
},
{
"Name":"Grand Father",
"Children":"Uncle"
},
{
"Name":"Uncle",
"Children":"Cousin"
},
{
"Name":"Father",
"Children":"Brother"
},
{
"Name":"Father",
"Children":"Me"
}
]
I want the query result to the following hierarchical format. How can I do it?
[
{
"Name":"4th Grand Father",
"Children":[
{
"Name":"3rd Grand Father",
"Children":[
{
"Name":"2nd Grand Father",
"Children":[
{
"Name":"Grand Father",
"Children":[
{
"Name":"Father",
"children":[
{
"Name":"Brother"
},
{
"Name":"Me"
}
]
},
{
"Name":"Uncle",
"children":[
{
"Name":"Cousin"
}
]
}
]
}
]
}
]
}
]
}
]
