0

I have the following table:

+-----------+------------+
| ChildCode | ParentCode |
+-----------+------------+
| AUSNZ     |   APACZ    |
| EASIAZ    |   APACZ    |
| SEASIAZ   |   APACZ    |
| AUSTR     |   AUSNZ    |
| NZ        |   AUSNZ    |
| PACISZ    |   AUSNZ    |
| TOGO      |   PACISZ   |
+-----------+------------+

I would like to have all ChildCodes with the ParentCode APACZ. However, the problem is that the ChildCode again can be a ParentCode (see AUSNZ) - there are multiple layers. Anyone an idea how to get all ChildCodes/ParentCodes belonging to APACZ, i.e. to get the entire list of Codes which have APACZ as a root?

Thanks in advance!

AVK
  • 3,893
  • 1
  • 22
  • 31
Lejahn
  • 9
  • 2

1 Answers1

0

This is a straightforward recursive CTE. There are many examples on stackoverflow. In your case, if you just want the list of children, you could do something like this....

;WITH list_structure AS
(
SELECT
    l.Child_Code,
    l.Parent_Code
    FROM [YOUR_TABLE_NAME_OF_VALUES_HERE] l
    WHERE l.Parent_Code ='APACZ'
UNION ALL
SELECT
    l.child_Code,
    l.Parent_Code
    FROM list_hierarchy l
    INNER JOIN list_structure
    ON l.Parent_Code = list_structure.child_Code
)

SELECT Child_Code FROM list_structure
Robert Sievers
  • 1,277
  • 10
  • 15