1

例如,如果我有如下表:-

    create table Categories(CategoryId int primary key,
 ParentCategoryId int foreign key references Categories(CategoryId))

例如,如果我的表中有以下数据:-

CategoryID  ParentCategoryId
1           2
2           3
3           4
4           NULL

Result:     

CategoryId  ParentCategoryId
1           2
1           3
1           4
2           3
2           4
3           4
4           NULL

谢谢你的帮助!

4

1 回答 1

2

像这样的东西:

DECLARE @MyTable TABLE(CategoryID INT, ParentCategoryID INT);

INSERT @MyTable VALUES(1, 2);
INSERT @MyTable VALUES(2, 3);
INSERT @MyTable VALUES(3, 4);
INSERT @MyTable VALUES(4, NULL);

; WITH CTE(RootCategory,CategoryID,ParentCategoryID,depth) AS (
    SELECT      CategoryID,CategoryID,ParentCategoryID,1
    FROM        @MyTable
    UNION ALL
    SELECT      CTE.RootCategory, t.CategoryID, t.ParentCategoryID,CTE.depth + 1
    FROM        CTE
    JOIN        @MyTable t  ON t.CategoryID = CTE.ParentCategoryID
)
SELECT      CategoryID = RootCategory
            , ParentCategoryID 
FROM CTE
WHERE       ParentCategoryID IS NOT NULL OR depth = 1
ORDER BY    RootCategory

结果:

CategoryID  ParentCategoryID
----------- ----------------
1           2
1           3
1           4
2           4
2           3
3           4
4           NULL
于 2012-06-17T13:44:27.440 回答