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 |
|
dlouche
Starting Member
9 Posts |
Posted - 2008-11-25 : 13:26:46
|
| Is there a way to make a recursive call in in SQL?I have a table that refers to itself:ID | ParentID | Name0 | null | 'first'1 | 0 | 'second'2 | 1 | 'third'and I would like to output of my select to be. ID | Name | NameChain0 | 'first' | 'first'1 | 'second'| 'first, second'2 | 'third' | 'first, second, third'Right now I am building the namechain in code (not sql), but I would like to sort on that column so it would be better if it were done in sqlThanks a tonDan L |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-11-25 : 13:30:31
|
;With CTE (ID,Name,NameChain)AS(SELECT ID,Name,Name FROM YourTableWHERE ParentID IS NULLUNION ALLSELECT t.ID,t.Name,c.Name +','+t.NameFROM YourTable tINNER JOIN CTE cON c.ID=t.ParentID)SELECT * FROM CTE |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-11-25 : 13:31:24
|
| Also see thishttp://msdn.microsoft.com/en-us/library/ms186243.aspx |
 |
|
|
dlouche
Starting Member
9 Posts |
Posted - 2008-11-25 : 13:54:48
|
| Thanks for the help. I have never heard of CTE before.When I try your query I get the following error:Msg 240, Level 16, State 1, Line 1Types don't match between the anchor and the recursive part in column "NameChain" of recursive query "CTE".Here is your query as I have entered it:;With CTE (ID,Name,NameChain)AS(SELECT ID,Name,Name FROM Categories WHERE ParentCategoryID IS NULL UNION ALL SELECT t.ID,t.Name,c.Name + ',' + t.Name FROM Categories t INNER JOIN CTE c ON c.ID = t.ParentCategoryID)SELECT * FROM CTE Thanks again! |
 |
|
|
dlouche
Starting Member
9 Posts |
Posted - 2008-11-25 : 14:05:00
|
| It doesn't seem to like the use of 't.name' in the recursive part |
 |
|
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2008-11-25 : 14:09:26
|
Please show the structure of Categories.Webfred No, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
|
dlouche
Starting Member
9 Posts |
Posted - 2008-11-25 : 14:16:54
|
| I got it! SQL didn't like the type of the concat?? Here is what ended up working:;With CTE (ID,Name,Name2)AS(SELECT ID,Name,Name FROM Categories WHERE ParentCategoryID IS NULL UNION ALL SELECT t.ID,t.Name,CONVERT(nvarchar(128), c.Name + ',' + t.Name) FROM Categories t INNER JOIN CTE c ON c.ID = t.ParentCategoryID)SELECT * FROM CTEThanks again! |
 |
|
|
|
|
|
|
|