Display Parent-Child relationship when Parent and Child are stored in same table

前端 未结 7 1956
生来不讨喜
生来不讨喜 2020-12-09 19:03

I have SQL Server table structure like below:

ID    Name     ParentID
-----------------------
1     Root       NULL
2     Business   1
3     Finance    1
4           


        
7条回答
  •  独厮守ぢ
    2020-12-09 19:32

    Like someone posted earlier, it needs to be a recursive function. There can be multiple scenarios - One Parent to Multiple Child (Level 1 Hierarchy) Parent 1 has Child 1 Parent 1 has Child 2 Child to Multiple Child (Level 2 Hierarchy) And so on.

    My example has parent curve id and child curve id. For example,

    WITH hierarchy AS
    (select UT.parent_curve_id as origin, UT.*
    from myTable UT
    WHERE UT.parent_curve_id IN ( 1027455, 555)
    UNION ALL
    select h.origin, UT.*
    from myTable UT
    JOIN hierarchy h ON h.child_curve_id = UT.parent_curve_id
    )
    SELECT *
    from hierarchy 
    order by unique_key
    

提交回复
热议问题