I have an SQL table like this
ID | ParentID
1 | null
2 | null
3 | null
4 | 1
5 | 4
6 | 5
7 | 6
8 | 7
9 | 8
Now, as you can see, a child parent relationship is maintained. I want a query to select “all level” children of a given ID.
Suppose if I input ID = 1, the result should be
ID | ParentID
1 | null
4 | 1
5 | 4
6 | 5
7 | 6
8 | 7
9 | 8
So all immediate children, as well as children of their children at any level, should come up.
Is it possible to do this in MS SQL server? I have MS-SQL server 2012.
Here is an example with an extra field Name, but with CTE the recursion is simple: