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

前端 未结 3 764
醉话见心
醉话见心 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:33

    You could try to use a loop. As you will get many levels of recursion with your approach:

    declare @child int = 0
    declare @parent int = 1 --child to search
    while @child <> @parent 
    BEGIN
    set @child = @parent
    select  @parent = Parentid from @parentchild  where ChildID = @child
    END
    select @parent
    

提交回复
热议问题