SQL Server CTE -Find top parentID forEach childID?

后端 未结 9 1089
Happy的楠姐
Happy的楠姐 2020-12-08 08:24

I have a table which contains hierarchy data - something like:

childID  |  parentID
____________________
  1      |     5
  5      |     9
  9      |     20         


        
9条回答
  •  星月不相逢
    2020-12-08 09:07

    I have not yet the time to look further into your question and am not sure whether or not i've understood your problem, but couldn't you use this svf to get the top father's id?

    CREATE FUNCTION [dbo].[getTopParent] (
        @ChildID INT
    )
    
    RETURNS int
    AS
    BEGIN
        DECLARE @result int;
        DECLARE @ParentID int;
    
        SET @ParentID=(
            SELECT ParentID FROM ChildParent
            WHERE ChildID = @ChildID 
        )
    
        IF(@ParentID IS NULL)
            SET @result = @ChildID 
        ELSE
            SET @result = [dbo].[getTopParent](@ParentID)
    
        RETURN @result    
    END
    

    Then you should be able to find each top parent in this way:

    SELECT ChildID
        ,  [dbo].[getTopParent](ChildID) AS TopParentID
    FROM ChildParent
    

提交回复
热议问题