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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 previous id until parentid is NULL

Author  Topic 

Nira
Starting Member

2 Posts

Posted - 2010-02-04 : 17:58:51
I have a table that looks like this where I need previous id until refid is NULL.

My table looks like this:
---------------------------------
| id | refid | Title |
---------------------------------
| 1 | NULL | Group1 |
| 2 | NULL | Group2 |
| 3 | 1 | Undergroup1 |
| 4 | 1 | Undergroup2 |
| 6 | NULL | Group3 |
| 7 | 3 | Underundergroup1 |
| 8 | 3 | Underundergroup2 |
| 9 | NULL | Group3 |
| 11 | NULL | Group3 |
---------------------------------



Now if I choose ID 7, my resultset should be:
---------------------------------
| id | refid | Title |
---------------------------------
| 1 | NULL | Gruppe1 |
| 3 | 1 | Undergruppe1 |
| 7 | 3 | Underundergruppe1|
---------------------------------


if I choose ID 3, my resultset should be:
---------------------------------
| id | refid | Title |
---------------------------------
| 1 | NULL | Gruppe1 |
| 3 | 1 | Undergruppe1 |
---------------------------------


How can this be done? I'm a bit stuck here...







/Niras

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2010-02-04 : 18:20:26
Check out Recursive CTE's.
Go to Top of Page

Nira
Starting Member

2 Posts

Posted - 2010-02-04 : 18:53:32
Thank you Lamprey... I't might be the word i was looking for... I will try google Recursive CTE...

/Niras
Go to Top of Page
   

- Advertisement -