Give the table structure, as something like:
ID ParentID Name 1 NULL A root 2 NULL Another root 3 1 Child of 1 4 3 Grandchild of 1 5 4 Great grandchild of 1 6 1 Child of 1 7 NULL Another root 8 7 Child of 6
I am looking for an elegant (if possible) solution for a single Sql statement/function that would return all data in the table when given an ID = 1
So my result would look something like:
ID ParentID Name 1 NULL A root 3 1 Child of 1 4 3 Grandchild of 1 5 4 Great grandchild of 1 6 1 Child of 1
I've seen similar questions on SO though for the most part they only seem to be looking at a given number of levels.
This structure can, ultimately, be limitless - folder with children, with many other children
Is this possible? If so, how would I accomplish it?
What you need is a recursive query. This Microsoft Technet example does exactly what you want, though in the example, we're going for a hierarchy of employees, not folders.
From the linked page:
and then
and your result is
So referencing this answer:
Sql Server CTE Parent Child recursive
Here's a working version with your schema:
Table Creation Script
Recursive CTE
The key part is in the
CTE
creation where theUNION ALL
joins back on to the result set, joiningID
toParentId
, which doesn't limit the number of level.