SQL recursive query

后端 未结 1 373
无人共我
无人共我 2021-01-18 05:28

I have a Table Category,

1) Id
2) CategoryName
3) CategoryMaster

with data as:

1 Computers 0
2 Software 1
3 Multimedia 1

相关标签:
1条回答
  • 2021-01-18 06:14

    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 讨论(0)
提交回复
热议问题