Select all parents or children in same table relation SQL Server

后端 未结 4 2080
日久生厌
日久生厌 2021-02-05 11:10

SQL developers, I have a badly planned database as task to learn a lot about SQL Server 2012.

SO, there is the table Elem:

+-----------+----         


        
4条回答
  •  青春惊慌失措
    2021-02-05 11:40

    I have met this problem,I resolved problem by this way

     --all  "parent + grandparent + etc" @childID Replaced with the ID you need
    
    with tbParent as
    (
       select * from Elem where [KEY]=@childID
       union all
       select Elem.* from Elem  join tbParent  on Elem.[KEY]=tbParent.PARENT_KEY
    )
     SELECT * FROM  tbParent
     --all "sons + grandsons + etc" @parentID Replaced with the ID you need
    
    with tbsons as
    (
      select * from Elem where [KEY]=@parentID
      union all
      select Elem.* from Elem  join tbsons  on Elem.PARENT_KEY=tbsons.[KEY]
    )
    SELECT * FROM tbsons
    

    PS.My English is not good.

提交回复
热议问题