Select all parents or children in same table relation SQL Server

后端 未结 4 2071
日久生厌
日久生厌 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:20

    I've created a function for finding the parents of a specific child where you have to pass the Id of the child.

    This will return the list of parents as a comma separated string. Try this if it works for you.

    I'm assuming that the parent_key with null value is root.

    CREATE FUNCTION checkParent(@childId INT)
    RETURNS VARCHAR(MAX)
    AS
    BEGIN
        DECLARE @parentId VARCHAR(MAX) = NULL
        DECLARE @parentKey INT = null
        SET @parentId = (SELECT parent_key FROM Elem WHERE [KEY] = @childId)
    
        WHILE(@parentKey IS NOT NULL)
        begin
            SET @parentId = @parentId +  ', ' + (SELECT parent_key FROM Elem WHERE [KEY] = @parentId)
            SET @parentKey = (SELECT parent_key FROM Elem WHERE [KEY] = @parentId)
        END
        RETURN @parentId
    END
    GO
    

提交回复
热议问题