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)
 Hierarchical Query

Author  Topic 

BeTheBall
Starting Member

1 Post

Posted - 2010-07-29 : 11:50:15
Way over my head here. I have a table that looks like this:

officeID | officeName | parentOfficeID
1 Main NULL
2 Sub1 1
3 Sub2 1
4 Sub1ofSub1 2
5 Sub2ofSub1 2
6 Sub1ofSub2 3
7 Sub1ofSub1ofSub2 6

I want to be able to pass in an officeID and have the db return the office that matches the officeID I pass in plus all it's parents. So, if I pass in officeID 7, the query needs to return officeID7, officeID6, officeID3 and officeID1.

I know the query has to be recursive, but that's about as much as I know. My experience thus far has been limited to pretty straight-forward SELECT, UPDATE and DELETE statements.

Any help will be appreciated.

- Duane -

X002548
Not Just a Number

15586 Posts

Posted - 2010-07-29 : 12:17:30
You need to use a Common Table Expression..you are using sql server 2005 or greater correct?

Look up CTE in BOL or Google it

I'll see if I can dig something up....






Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page

Vinnie881
Master Smack Fu Yak Hacker

1231 Posts

Posted - 2010-07-29 : 12:28:02
Anyone that is looking into hierarchy, should be aware of this method. I really like this method if you are going to be running a lot of queries where you want to return all child nodes.

It's written for mysql, but same principals work for sql server 2005

http://dev.mysql.com/tech-resources/articles/hierarchical-data.html


Success is 10% Intelligence, 70% Determination, and 22% Stupidity.
\_/ _/ _/\_/ _/\_/ _/ _/- 881
Go to Top of Page
   

- Advertisement -