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)
 Creating a hierachy Query

Author  Topic 

Markyboy.sk
Starting Member

2 Posts

Posted - 2008-10-08 : 11:15:25
Hi All,

I have a simple table that contains parentid and orgid

if parentid is 0 then it is a org name as it has no parent
if it has a different number then it is a child of a parent

how do I write a query so it will list each parent with the children below, then the next parent etc?

I have been searching everywhere but cannot see how to do it
I can get the full list, just not in a structured format that makes sense

thanks in advance

spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2008-10-08 : 11:35:21
use Common table expressions (CTE):
http://msdn.microsoft.com/en-us/library/ms190766.aspx

_______________________________________________
Causing trouble since 1980
Blog: http://weblogs.sqlteam.com/mladenp
Speed up SSMS development: www.ssmstoolspack.com <- version 1.1 out!
Go to Top of Page

Markyboy.sk
Starting Member

2 Posts

Posted - 2008-10-08 : 14:09:23
Hi Spirit1

a CTE does seem to be what I need, however I cannot seem to get my head around it.

any ideas how to simplify the basic CTE routine so I can understand it?

thanks
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-08 : 14:13:15
books online has good explanation with example

http://msdn.microsoft.com/en-us/library/ms186243.aspx
Go to Top of Page

spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2008-10-08 : 14:14:48
maybe this will help:
http://www.databasejournal.com/features/mssql/article.php/3502676

basicaly the first select is the recurion starting point. the boss if you will.
the 2nd query which is unioned is the recursive member.
it uses recursion on the previous result from that same 2nd query.

_______________________________________________
Causing trouble since 1980
Blog: http://weblogs.sqlteam.com/mladenp
Speed up SSMS development: www.ssmstoolspack.com <- version 1.1 out!
Go to Top of Page
   

- Advertisement -