Попробуйте этот запрос
create table hierarchy (Parent varchar(3), child varchar(10))
insert into hierarchy values
('A','AB')
,('A','AC')
,('A','AD')
,('A','AE')
,('AB','ABC')
,('AB','ABD')
,('AB','ABE')
,('ABC','ABCD')
,('ABC','ABCE')
GO
; WITH cte_Hierarchy
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY [name]) Id
, t.[name]
FROM(
SELECT Parent [name] FROM hierarchy t
UNION
SELECT child FROM hierarchy t
)t
)
SELECT t.Id
, t.[name]
, h.Parent
, p.Id ParentId
FROM cte_Hierarchy t
LEFT JOIN hierarchy h ON h.child = t.[name]
LEFT JOIN cte_Hierarchy p on p.[name] = h.Parent