Domanda

Ho una tabella Categoria,

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 Healthsub 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

I ottenere i risultati per la categoria genitore a fondo, come ottengo tutte le sottocategorie per il computer

, ma voglio i risultati dal basso verso l'alto, come da Animazione al computer, si prega di qualcuno può suggerire me giusta direzione.

Grazie in anticipo:)

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top