We have a table where rows recursively link to another row. I want to pull data associated with a given parentId and all it's children. Where parentId is one from the root row.
I thought I have seen or done something like that before, but I am unable to find it now. Can this be done in SQL or is it better to do this in code?
I want the list to look like this when I'm done:
- Parent
- Child
- Grandchild
This can be done in SQL Server 2005 and above using Common Table Expressions (CTEs). Here is a great link from MSDN describing recursive queries: Recursive Queries Using Common Table Expressions
Here is an example:
If you imagine a hierarchical line of people, this query will let you see the complete line of any person AND calculates their place in the hierarchy. It can be modified to find any child relationship.
Instead of the ID of the person, you swap in the ID of the row you are using as your parent.