Recursive SQL Queries using Common Table Expressions

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’

UNION ALL

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
JOIN CTE
ON childContext.ParentId = CTE.Id
Where childContext.Active = ‘true’

)

Select * from CTE
order by Name
END

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s