Recursive same-table query in SQL Server 2008

后端 未结 4 1564
谎友^
谎友^ 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

    Try this one:

        DECLARE @tbl TABLE (
             Id INT
            ,[Name] VARCHAR(20)
            ,ParentId INT
            )
    
        INSERT INTO @tbl( Id, Name, ParentId )
        VALUES
         (1, 'Europe', NULL)
        ,(2, 'Asia',   NULL)
        ,(3, 'Germany', 1)
        ,(4, 'UK',      1)
        ,(5, 'China',   2)
        ,(6, 'India',   2)
        ,(7, 'Scotland', 4)
        ,(8, 'Edinburgh', 7)
        ,(9, 'Leith', 8)
    
        ;
    WITH  abcd
            AS (
                  -- anchor
                SELECT  id, [Name], ParentID,
                        CAST(([Name]) AS VARCHAR(1000)) AS "Path"
                FROM    @tbl
                WHERE   ParentId IS NULL
                UNION ALL
                  --recursive member
                SELECT  t.id, t.[Name], t.ParentID,
                        CAST((a.path + '/' + t.Name) AS VARCHAR(1000)) AS "Path"
                FROM    @tbl AS t
                        JOIN abcd AS a
                          ON t.ParentId = a.id
               )
    SELECT * FROM abcd
    
    0 讨论(0)
  • 2020-12-01 02:51

    Sounds like you should checkout CLR support for Sql Sever.

    CLR integration means that you can now write stored procedures, triggers, user-defined types, user-defined functions (scalar and table-valued), and user-defined aggregate functions using any .NET Framework language, including Microsoft Visual Basic .NET and Microsoft Visual C#.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-01 03:10

    I'm not sure if this will work in your case, but in this example http://www.pure-performance.com/2009/03/managing-hierarchical-data-in-sql/ there is something about using an extra column, called lineage.

    I have used this method with success.

    0 讨论(0)
提交回复
热议问题