Please start any new threads on our new site at http://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 previous id until parentid is NULL
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Nira
Starting Member

Denmark
2 Posts

Posted - 02/04/2010 :  17:58:51  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

4614 Posts

Posted - 02/04/2010 :  18:20:26  Show Profile  Reply with Quote
Check out Recursive CTE's.
Go to Top of Page

Nira
Starting Member

Denmark
2 Posts

Posted - 02/04/2010 :  18:53:32  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 4.06 seconds. Powered By: Snitz Forums 2000