2011-01-14 6 views
7

Ho una tabella Categoria,SQL query ricorsiva

1) Id
2) NomeCategoria
3) CategoryMaster

con dati come:

1 Computer 0
2 Software 1
3 Multimedia 1
4 Animazione 3
5 Salute 0
6 Healt hsub 5

e ho creato query ricorsive come:

;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 

ottengo i risultati per la categoria genitore a fondo, come ottengo tutte le sottocategorie per il calcolatore

ma voglio i risultati dal basso verso l'alto come da Animation to Computers, per favore qualcuno può suggerirmi la giusta direzione.

Grazie in anticipo :)

risposta

5

Basta scambiare i campi nella clausola 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