Author |
Topic |
Neilson
Starting Member
11 Posts |
Posted - 2011-03-18 : 10:28:48
|
I have a table with navigation that joins back on its self using ParentId. I am trying to calculate how many descendent's each record has, I know that I need to increment a counter in the recursion, I'm just not sure how to go about it, and with my example below, I get "Invalid column name 'Level'" where I increment Level + 1!Any help would be greatly appreciated!CREATE TABLE [dbo].[Navigation]( [Id] [int] IDENTITY(1,1) NOT NULL, [AnchorText] [varchar](50) NOT NULL, [ParentID] [int] NULL)insert into Navigationselect 'Level 1', nullunionselect 'Level 2', 1unionselect 'Level 3', 2unionselect 'Level 4', 3WITH NavigationCTE (Id, AnchorText, ParentId, Level) as( Select nav.Id, nav.AnchorText, nav.ParentId, 0 as Level from dbo.Navigation AS nav UNION ALL select nav.Id, nav.AnchorText, nav.ParentId, Level + 1 from dbo.Navigation AS nav join Navigation AS nav2 ON nav.ParentId = nav2.Id)SELECT * FROM NavigationCTE |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2011-03-18 : 10:34:13
|
[code]WITH NavigationCTE (Id, AnchorText, ParentID, [Level]) as( Select nav.Id, nav.AnchorText, nav.ParentID, 0 as [Level] from dbo.Navigation AS nav where ParentID is null UNION ALL select nav.Id, nav.AnchorText, nav.ParentID, nav2.[Level] + 1 from dbo.Navigation AS nav join NavigationCTE AS nav2 ON nav.ParentID = nav2.Id)SELECT * FROM NavigationCTE[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
Neilson
Starting Member
11 Posts |
Posted - 2011-03-18 : 10:40:15
|
Thanks! |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2011-03-18 : 10:41:48
|
Works for meDECLARE @Navigation TABLE ( ID INT NOT NULL, AnchorText VARCHAR(50) NOT NULL, ParentID INT NULL )INSERT @NavigationSELECT 45, 'Level 1', NULL UNION ALLSELECT 19, 'Level 2', 45 UNION ALLSELECT 24, 'Level 3', 19 UNION ALLSELECT -8, 'Level 4', 24;WITH cteNavigation(ID, AnchorText, ParentID, Lvl)AS ( SELECT ID, AnchorText, ParentID, 0 AS Lvl FROM @Navigation WHERE ParentID IS NULL UNION ALL SELECT n.ID, n.AnchorText, n.ParentID, c.Lvl + 1 FROM cteNavigation AS c INNER JOIN @Navigation AS n ON n.ParentID = c.ID)SELECT *FROM cteNavigation N 56°04'39.26"E 12°55'05.63" |
 |
|
|
|
|