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 |
|
tiffiny
Starting Member
7 Posts |
Posted - 2007-07-05 : 12:03:09
|
| I have a table that represents a tree structure via a self-join. e.g. givenid parentid1 NULL2 13 24 25 16 47 NULL8 79 710 911 10 I need to get the root of the given child. for example: if the given child is 6 then return 1. if child=10 then return 7. I need this in a single query only, is it possible? |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2007-07-05 : 12:17:19
|
| http://msdn2.microsoft.com/en-us/library/ms186243.aspxMadhivananFailing to plan is Planning to fail |
 |
|
|
tiffiny
Starting Member
7 Posts |
Posted - 2007-07-05 : 12:30:32
|
quote: Originally posted by madhivanan http://msdn2.microsoft.com/en-us/library/ms186243.aspxMadhivananFailing to plan is Planning to fail
The recursive example given in http://msdn2.microsoft.com/en-us/library/ms186243.aspx only for the whole structure of the tree result. It can't produce what i expected also. thanks Madhivanan |
 |
|
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2007-07-05 : 13:56:41
|
I think this is what you are looking for. Note: you should be able to replace the hard coded 7 with a variable if that is what you are trying to get to:DECLARE @T TABLE (ID INT, ParentID INT)INSERT @TSELECT 1, NULLUNION ALL SELECT 2, 1UNION ALL SELECT 3, 2UNION ALL SELECT 4, 2UNION ALL SELECT 5, 1UNION ALL SELECT 6, 4UNION ALL SELECT 7, NULLUNION ALL SELECT 8, 7UNION ALL SELECT 9, 7UNION ALL SELECT 10, 9UNION ALL SELECT 11, 10;WITH Parent AS( SELECT ID, ParentID FROM @T t WHERE ID = 7 UNION ALL SELECT t1.ID, t1.ParentID FROM @T t1 INNER JOIN Parent AS p ON t1.ParentID = p.ID)SELECT *FROM ParentWHERE ParentID IS NULL -Ryan |
 |
|
|
DaleJ
Starting Member
7 Posts |
Posted - 2007-07-05 : 14:57:24
|
| See if this suits the need...DECLARE @T TABLE (ID INT, ParentID INT)INSERT @TSELECT 1, NULLUNION ALL SELECT 2, 1UNION ALL SELECT 3, 2UNION ALL SELECT 4, 2UNION ALL SELECT 5, 1UNION ALL SELECT 6, 4UNION ALL SELECT 7, NULLUNION ALL SELECT 8, 7UNION ALL SELECT 9, 7UNION ALL SELECT 10, 9UNION ALL SELECT 11, 10;with uptheladder(anchor, id, parentid, lvl)as( select id, t1.*, 0 from @t t1 union all select anchor, t2.*, lvl + 1 from @t t2 inner join uptheladder l on t2.id = l.parentid),ladderchainas( select anchor, max(lvl) as lvl from uptheladder group by anchor),laddertopas ( select l.anchor as id, l.id as parentid from uptheladder l inner join ladderchain c on l.anchor = c.anchor and l.lvl = c.lvl)select id, parentidfrom laddertopwhere id = 10 |
 |
|
|
|
|
|
|
|