I have a table that contains the following data:
+----+----------+
| ID | ParentID |
+----+----------+
| 27 | 0 |
| 38 | 27 |
| 45 | 38 |
| 86 | 0 |
| 92 | 45 |
| 48 | 86 |
| 62 | 92 |
| 50 | 62 |
-----------------
I would like to be able to pass any ID to a stored procedure and get the entire chain of IDs (parents and children) of that given ID.
ie. if I pass ID = 45, I should get:
27
38
45
92
62
50
Similarly, if I pass ID = 86, I should get:
86
48
Any help would be greatly appreciated!
You can use two recursive CTE’s. The first finds the root node and the second builds the chain.
Version 2
A bit shorter and query plan suggests more effective but you never know without testing on real data.