I have a categories table with a father-son relationship which looks something like this:
Table name:
tblCategories
Columns:
catID
catFatherID – This column has a relationship to catID
What I need is to select for each category it’s entire family childs (including itself) in the following way:
Original table rows:
| catID | catFatherID |
= = = = = = = = = = = =
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 3 |
| 6 | 4 |
What I want to get:
| Category ID | Family Category ID |
= = = = = = = = = = = = = = = = = =
| 1 | 1 | (Yes, I want it to include itself in the return family members)
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 1 | 6 |
| 2 | 2 |
| 2 | 4 |
| 2 | 6 |
| 3 | 3 |
| 3 | 5 |
| 4 | 4 |
| 4 | 6 |
| 5 | 5 |
| 6 | 6 |
Ask if I didn’t explain something enough.
A CTE would be a good match to solve this. The trick is to retain a
rootID while executing the CTE.SQL Statement
Test script