Recursive same-table query in SQL Server 2008

后端 未结 4 1566
谎友^
谎友^ 2020-12-01 02:28

I have the following table in a SQL Server 2008 database:

Id  Name       ParentFolder
--  ----       ------------
1   Europe     NULL
2   Asia       NULL
3           


        
4条回答
  •  臣服心动
    2020-12-01 02:51

    I tried the solution above, but found that this only worked for me to 2 levels. (Perhaps I have not understood or missed something.)

    In order to get the fully qualified path for m solution I have succeeded with this custom function:

    CREATE FUNCTION GetFQN(@recid int)
    RETURNS VARCHAR(1000)
    
    AS
    
    BEGIN
        DECLARE @path AS VARCHAR(1000)
        DECLARE @parent_recid AS INT
    
        SET @path           =   (SELECT BranchName FROM Branches WHERE Recid = @recid)
        SET @parent_recid   =   (SELECT recid_parent FROM Branches WHERE Recid = @recid)
    
    
        WHILE @parent_recid != -1
        BEGIN
            SET @path = (SELECT BranchName FROM Branches WHERE recid = @parent_recid) + '/' + @path 
            SET @parent_recid = (SELECT recid_parent FROM Branches WHERE recid = @parent_recid)
        END
    
        RETURN (@Path)
    END
    

提交回复
热议问题