Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
JoeJack222
Starting Member
3 Posts |
Posted - 2010-02-19 : 11:15:38
|
| I know that recursive is useful for creating tree structures, or when it relates back to itself. I received a question that I do not understand.recursive select for the following tabletable CategoriesCategoryID intParentCategoryId intCategoryName nvarcharJust need some guidance |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
|
|
JoeJack222
Starting Member
3 Posts |
Posted - 2010-02-19 : 12:02:36
|
So far I have WITH Categories (CategoryID, ParentCategoryID, CategoryName, Level)AS(-- Anchor member definition SELECT e.CategoryID, e.ParentCategoryID, e.CategoryName, 0 AS Level FROM Categories AS e UNION ALL-- Recursive member definition SELECT e.CategoryID, e.ParentCategoryID, e.CategoryName, Level + 1 FROM Categories AS e I get "Incorrect syntax near 'e'." which is for my second e. Any help? |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-02-19 : 12:08:03
|
quote: Originally posted by JoeJack222 So far I have WITH Categories (CategoryID, ParentCategoryID, CategoryName, Level)AS(-- Anchor member definition SELECT e.CategoryID, e.ParentCategoryID, e.CategoryName, 0 AS Level FROM Categories AS e UNION ALL-- Recursive member definition SELECT e.CategoryID, e.ParentCategoryID, e.CategoryName, Level + 1 FROM Categories AS e I get "Incorrect syntax near 'e'." which is for my second e. Any help?
it should beWITH Categories_CTE (CategoryID, ParentCategoryID, CategoryName, Level)AS(-- Anchor member definition SELECT e.CategoryID, e.ParentCategoryID, e.CategoryName, 0 AS Level FROM Categories AS e WHERE e.ParentCategoryID IS NULL UNION ALL-- Recursive member definition SELECT c.CategoryID, c.ParentCategoryID, c.CategoryName, cc.Level + 1 FROM Categories AS c INNER JOIN Categories_CTE cc ON cc.CategoryID= c.ParentCategoryID)SELECT CategoryID, ParentCategoryID, CategoryName, LevelFROM Categories_CTE OPTION (MAXRECURSION 0) ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
JoeJack222
Starting Member
3 Posts |
Posted - 2010-02-19 : 12:31:55
|
| Thank you, works well. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-02-19 : 12:32:27
|
welcome ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|
|