Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hi,I have a classic Id, parentId, col3, col4 type table and I'm trying to get all parentId's for a given Id all the way up to the top most level. LikeId, parentId ...1, 02, 13, 14, 35, 36, 4For 6 I would get the 4, 3, 1, 0Thanks for any help.
kbhere
Yak Posting Veteran
58 Posts
Posted - 2009-11-24 : 04:53:51
SELECT DISTINCT parentId FROM table WHERE id <= 6Balaji.K
bklr
Master Smack Fu Yak Hacker
1693 Posts
Posted - 2009-11-24 : 04:55:27
try this
declare @t table (Id int, parentId int)insert into @t select 1, 0 union all select 2, 1 union all select 3, 1 union all select 4, 3 union all select 5, 3 union all select 6, 4declare @id intselect @id = 6;with cte (id,parentid)as(select id,parentid from @t where id = @id union all select t.id,t.parentidfrom @t t join cte c on t.id = c.parentid and t.parentid <> c.parentid)select * from cte
kingjeremy
Starting Member
10 Posts
Posted - 2009-11-24 : 05:14:30
Thanks bklr for the quick reply this is what I needed.
bklr
Master Smack Fu Yak Hacker
1693 Posts
Posted - 2009-11-24 : 05:59:40
Welcome but it will works in 2005 and above versions only.