Finding Top level parent of each row of a table [SQL Server 2008]

前端 未结 3 763
醉话见心
醉话见心 2021-01-23 12:24

I have following two tables

Table Person

Id   Name
   1    A
   2    B
   3    C
   4    D
   5    E

Table RelationHierarchy



        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-23 12:55

    Another way to do this in a loop if you wanted to work with sets is:

    SELECT *
        INTO #parentchild
    from RelationHierarchy 
    
    
    WHILE EXISTS
    (select 1 from  #parentchild A inner join #parentchild B on A.ChildID = B.ParentID Where A.ParentID <> B.ParentID )
    BEGIN
    update B set B.ParentID = A.ParentID
    from #parentchild A inner join #parentchild B on A.ChildID = B.ParentID
    END
    
    select * from #parentchild
    

提交回复
热议问题