开发者

SQL recursive query

I h开发者_运维问答ave a Table Category,

1) Id

2) CategoryName

3) CategoryMaster

with data as:

1 Computers 0

2 Software 1

3 Multimedia 1

4 Animation 3

5 Health 0

6 Healthsub 5

and i have created recursive query as:

 ;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 get the results for parent category to bottom, like i get all sub categories for computer

but i want the results from bottom-up like from Animation to Computers, please can some one suggest me right direction.

Thank you in advance :)


Just swap the fields in the join clause:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜