Следующее должно работать для любого количества уровней:
DECLARE @t table
(
ID char(1)
, TypeAID char(1)
, TypeBID char(1)
)
INSERT INTO @t (ID, TypeAID, TypeBID)
VALUES
('A', NULL, NULL)
, ('B', NULL, NULL)
, ('C', 'A', NULL)
, ('D', 'B', 'C')
, ('E', NULL, 'C')
;
WITH cte
AS
(
SELECT
Parent
, ID Child
FROM
(
SELECT
ID
, TypeAID
, TypeBID
FROM @t
) D
UNPIVOT
(
Parent FOR TypeID IN (
[TypeAID]
, [TypeBID]
)
) U
)
,
cte2
AS
(
SELECT
Parent
, Child
FROM cte
UNION ALL
SELECT
cte1.Parent
, cte2.Child
FROM
cte2 cte1
JOIN cte cte2 ON cte1.Child = cte2.Parent
)
SELECT
Parent
, Child
FROM cte2
ORDER BY
Parent
, Child