SQL递归查询

时间:2011-01-14 11:01:05

标签: sql sql-server sql-server-2005 recursive-query

我有一个表类别,

1)Id
2)CategoryName
3)CategoryMaster

数据为:

1台电脑0
2软件1
3多媒体1
4动画3
5健康0
6 Healthsub 5

我创建了递归查询:

 ;WITH CategoryTree AS
 (
  SELECT *, CAST(NULL AS VARCHAR(50)) AS ParentName, 0 AS Generation    
  FROM dbo.Category    
  WHERE CategoryName = 'Computers'

  UNION ALL        

  SELECT Cat.*,CategoryTree.CategoryName AS ParentName, Generation + 1    
  FROM dbo.Category AS Cat  INNER JOIN 
  CategoryTree ON Cat.CategoryMaster = CategoryTree.Id
 )

 SELECT * FROM CategoryTree

我得到父类别的结果到底部,就像我得到计算机的所有子类别

但是我希望从动画到计算机的自下而上的结果,请一些人建议我正确的方向。

提前谢谢你:)

1 个答案:

答案 0 :(得分:5)

只需交换join子句中的字段:

WITH CategoryTree AS
        (
        SELECT  *, 0 AS Generation    
        FROM    dbo.Category
        WHERE   CategoryName = 'Animation'
        UNION ALL
        SELECT  Cat.*, Generation + 1    
        FROM    CategoryTree
        JOIN    dbo.Category AS Cat
        ON      Cat.Id = CategoryTree.CategoryMaster
        )
SELECT  *
FROM    CategoryTree