I often work with tables that will have a parent ID that relates to another row within the same table so that I can create a hierarchical relationship within table (a tree). When trying to display this tree I have usually relied a combination of code and calls to the database to get the nodes at each level based on the shared parent ID, however the other day I was in a situation that really needed to retrieve the entire tree with a single query.
Here is the method I found to retrieve an entire tree with a single call. This uses a common table expression. The first select statement will retrieve the initial return set which will be all items at the root (items with no parent), and then the second select statement recursively builds on that set using a UNION ALL and an inner join. In this case, I’m replacing the Name at each level with a concatenated string of ‘Parent Name : Child Name’.
with CTE as
(SELECT c.Id,c.AccountId,c.ParentId,c.Description,c.SortOrder,c.Active, CAST( c.Name as nvarchar(max)) as Name
FROM Context c
WHERE c.AccountId = @accountId
and ParentId = 0
and c.Active = ‘true’
SELECT childContext.Id,childContext.AccountId,childContext.ParentId,childContext.Description,childContext.SortOrder,childContext.Active, CAST( CTE.Name + ‘ : ‘ + childContext.Name as nvarchar(max)) as Name
FROM Context childContext
ON childContext.ParentId = CTE.Id
Where childContext.Active = ‘true’
Select * from CTE
order by Name