我有这张桌子:
Categories( CatId, Name, ParentId NULL )
...这是递归的,因此每个类别都可以命名一个父类别,而该父类别又具有一个父类别,依此类推。像这样:
1, "Sports", NULL
2, "Football", 1
3, "Golf", 1
4, "Handegg", 2
5, "Sex", NULL
6, "On the beach", 5
不久前,我使用 CTE 对类别的父级执行递归查找,如下所示:
WITH Categories(CatId, Name, ParentId, n) AS (
SELECT CatId, Name, ParentId, 1
FROM Categories
WHERE CatId = @categoryId
UNION ALL
SELECT c1.CatId, c1.Name, c1.ParentId, c2.n + 1
FROM Categories AS c1
INNER JOIN Categories AS c2 ON c1.CatId = c2.ParentId
)
但我在想,我不能将其改写为 WHILE 查询吗?
DECLARE @ret TABLE( CatId, Name, ParentId )
DECLARE @tCatId int
DECLARE @tName nvarchar(255)
DECLARE @tParentId int NULL
SELECT @tCatId = CatId, @tName = Name, @tParentId = ParentId
FROM Categories
WHERE CatId = @categoryId
WHILE( @tParentId IS NOT NULL ) BEGIN
INSERT INTO @ret ( CatId, Name, ParentId ) VALUES ( @tCatId, @tName, @tParentId )
SELECT @tCatId = CatId, @tName = Name, @tParentId = ParentId
FROM Categories
WHERE CatId = @tParentId
END
SELECT @ret
显然它的边缘有点粗糙(例如当第一行的 ParentId 为 NULL 时没有完成),而且我无法对其进行测试(因为我的 SQL Server 已关闭以进行重建),但它肯定是正确的?