递归CTE以获得类别及其所有祖先

时间:2016-02-02 20:25:37

标签: tsql common-table-expression

我一直在摆弄this Recursive CTE Example,看看我是否可以从头开始获得层次结构。

在我的场景中,我有一个类别表,如下面的

类别ID
类别名称
ParentCategoryID

我有以下递归CTE查询

;WITH CategoriesCTE AS
( 
 SELECT c.CategoryID, c.CategoryName, c.ParentCategoryID
 FROM Category c
 WHERE c.ParentCategoryID IS NOT NULL

 UNION ALL

 SELECT c.CategoryID, c.CategoryName, c.ParentCategoryID
 FROM Category c
 INNER JOIN CategoriesCTE p
 ON p.CategoryID=c.ParentCategoryID
 WHERE c.ParentCategoryID IS NULL
 )

 -- Get the category with the ID 13 and all its ancestors
 SELECT * FROM CategoriesCTE
 WHERE CategoryID = 13

以上查询不会返回结果,我确定这是因为我的where子句限制了它。我该如何解决?

0 个答案:

没有答案
相关问题