2011-01-14 214 views
7

我有一個表的類別,SQL遞歸查詢

1)標識
2)類別名稱
3)CategoryMaster

用數據爲:

1計算機0
2軟件1
3多媒體1
4動畫3
5健康0
6治療hsub 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 

我得到父類的結果,底部,像我得到的所有子類別計算機

,但我想要的結果,從自下而上從動畫到電腦,請有人建議我正確的方向。

預先感謝您:)

回答

5

只是交換聯接子句中的字段:

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