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

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to get a tree of children for the parent
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

sqlbug
Posting Yak Master

Canada
197 Posts

Posted - 05/16/2013 :  16:04:35  Show Profile  Reply with Quote
I've this table Company with Columns and sample data like below:

CompanyID, CompanyName, ParentCompanyID, UserID....etc.
0, klm, -1, 1000
1, abc, 2, 1001
2, xyz, 0, 1002
3, pqr, 2, 1003
4, mno, 3, 1004

I'm trying to create a procedure that'll return all the children/subchildren for a parent. For example - if we pass 1002 - it should return Company 1,2,3 and 4 - because 2 is the parent of 1 and 3, and 3 is the parent of 4.

Need help please.
Thanks.

TG
Flowing Fount of Yak Knowledge

USA
6059 Posts

Posted - 05/16/2013 :  17:00:24  Show Profile  Reply with Quote
Assuming you have SQL 2005 or later you can use a recursive common table expression (CTE) for this.
You can search here for plenty of examples (search for hierarchy or parent-child).
But here is a quick example of a recursive CTE based on your sample:

declare @t table (CompanyID int, CompanyName varchar(10), ParentCompanyID int, UserID int)
insert @t
select  0, 'klm', -1, 1000
union all select 1, 'abc', 2, 1001
union all select 2, 'xyz', 0, 1002
union all select 3, 'pqr', 2, 1003
union all select 4, 'mno', 3, 1004

;with rcte as 
(
       select companyid, companyname, parentCompanyID, Userid
       from @t
       where  userid = 1002
       union all
       select t.companyid, t.companyname, t.parentCompanyID, t.Userid
       from   rcte r
       join   @t t on t.parentCompanyID = r.companyid
)
select * from rcte

OUTPUT:
companyid   companyname parentCompanyID Userid
----------- ----------- --------------- -----------
2           xyz         0               1002
1           abc         2               1001
3           pqr         2               1003
4           mno         3               1004

Do you need help incorporating this into a stored procedure as well or are you good on that part?

Be One with the Optimizer
TG
Go to Top of Page

sqlbug
Posting Yak Master

Canada
197 Posts

Posted - 05/16/2013 :  17:14:03  Show Profile  Reply with Quote
Hi TG, I'll be able to incorporate it in the procedure.
Then I'll let you know if it's working.
Thanks so much.
Go to Top of Page

sqlbug
Posting Yak Master

Canada
197 Posts

Posted - 05/16/2013 :  19:13:55  Show Profile  Reply with Quote
It worked, thanks again TG.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New 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 0.06 seconds. Powered By: Snitz Forums 2000