How to create query from parent child hierarchy table

后端 未结 1 910
感情败类
感情败类 2020-12-20 07:33

How do I write my query to translate a table with parent / child hierarchy into a table with my hierarchy levels in separate columns?

I have a table in SQL Server (f

相关标签:
1条回答
  • 2020-12-20 08:18

    If you have a fixed or limited number of levels, you may not need DYNAMIC SQL. "Parsing" the path can be accomplished with a little XML.

    Consider the following:

    Example:

    Declare @YourTable Table ([Parent] varchar(50),[Child] varchar(50))
    Insert Into @YourTable Values 
     (null ,'S-1')
    ,('S-1','S-11')
    ,('S-1','S-12')
    ,('S-1','S-13')
    ,('S-1','S-14')
    ,('S-1','S-15')
    ,('S-11','S-111')
    ,('S-11','S-112')
    
    ;with cteP as (
          Select Child
                ,Parent 
                ,PathID = cast(Child as varchar(500))
          From   @YourTable
          Where  Parent is Null
          Union  All
          Select Child  = r.Child
                ,Parent = r.Parent 
                ,PathID = cast(p.PathID+','+cast(r.Child as varchar(25)) as varchar(500))
          From   @YourTable r
          Join   cteP p on r.Parent  = p.Child)
    Select [Group] = Child
          ,B.*
     From  cteP A
     Cross Apply (
                    Select Level1 = xDim.value('/x[1]','varchar(max)')
                          ,Level2 = xDim.value('/x[2]','varchar(max)')
                          ,Level3 = xDim.value('/x[3]','varchar(max)')
                          ,Level4 = xDim.value('/x[4]','varchar(max)')
                          ,Level5 = xDim.value('/x[5]','varchar(max)')
                    From  (Select Cast('<x>' + replace(PathID,',','</x><x>')+'</x>' as xml) as xDim) as X 
                 ) B
      Order By PathID
    

    Returns

    0 讨论(0)
提交回复
热议问题