Solved

Get all child records of a record from a self referencing table

Posted on 2013-01-02
6
753 Views
Last Modified: 2013-01-03
Hi Experts,

          I have a self referencing table (each record may or may not have a reference to another record within the same table) and I want to be able to get all child records for a particular record!  I am looking for a script for the best way to accomplish this!

Ex:

ID     ParentID     Name
1       NULL           U.S.A.
2       1                   PA
3       2                   Pittsburgh
4       2                   Harrisburg

So if I would pass the stored procedure the ID=1, it would retrun PA, Pittsburgh, and Harrisburg, while if I pass it the ID=2, it would only retrun Pittsburgh, and Harrisburg


Any help would be greatly appreciated!

Thanks!
0
Comment
Question by:axnst2
6 Comments
 

Author Comment

by:axnst2
ID: 38738268
Oh, I forgot to mention that we have no idea "how deep the rabbit hole goes"!  So the number of tiers is n!
0
 
LVL 22

Expert Comment

by:Steve Wales
ID: 38738420
Sounds like what you need is a recursive query with a common table expression (CTE).

I don't claim to be an expert on CTE's and their syntax but there's a detailed example in the Microsoft documentation on doing pretty much want you want, but with an employee hierarchy, instead of a geographical one.

http://msdn.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx?ppud=4
0
 
LVL 9

Expert Comment

by:sognoct
ID: 38738449
for a dirty fast solution
just something like

WHILE (SELECT count(0) from mytable where parentid=@val)>0
BEGIN  
      select @val = min(id) from mytable where parentid = @val
      select * from mytable Where parentid=@val;
END
0
Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
LVL 9

Accepted Solution

by:
sognoct earned 500 total points
ID: 38739372
create procedure getAllChilds (@val as int)
as
BEGIN  
        DECLARE @TempTable table (id int, ParentID int, Name nvarchar(80))
        insert into  @TempTable (id, ParentID, Name )
                  select id, ParentID, Name  
                        from mytable
                        Where ParentID = @val
      WHILE (SELECT count(0) from @TempTable t1
                        INNER JOIN  mytable t2 ON t1.id = t2.parentid
                        LEFT JOIN @TempTable t3 ON t2.id = t3.id
                        WHERE t3.id IS NULL )>0
        BEGIN  
            insert into  @TempTable (id, ParentID, Name )
                  select t2.id, t2.ParentID, t2.Name
                  from @TempTable t1
                  INNER JOIN  mytable t2 ON t1.id = t2.parentid
                  LEFT JOIN @TempTable t3 ON t2.id = t3.id
                  WHERE t3.id IS NULL
        END
        select * FROM @TempTable
END
0
 
LVL 12

Expert Comment

by:Saurabh Bhadauria
ID: 38739380
You need a recursive CTE... here is a example code....
Here is a example code..

First create Sp...
create procedure your_proc (@id int)
as
begin
;with cte_h
as 
    (   select t1.name,id  from #tt t1
              where t1.ParentID=@id
         union all 
         select a.name,a.id  from #tt  a join cte_h b on a.ParentID=b.id
         
     )
select name from cte_h option (maxrecursion 1000)

end 

go

Open in new window

Then exec below code....
create table #tt (ID int,     ParentID int     ,Name varchar(20))
insert into #tt
select 1,       NULL   ,        'U.S.A.'
union all select 2       ,1                   ,'PA'
union all select 3       ,2                   ,'Pittsburgh'
union all select  4,       2                   ,'Harrisburg'


select * from #tt

exec your_proc 1

Open in new window

0
 

Author Closing Comment

by:axnst2
ID: 38741839
Worked like a charm Sir/Ma'am!
0

Featured Post

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

Long way back, we had to take help from third party tools in order to encrypt and decrypt data.  Gradually Microsoft understood the need for this feature and started to implement it by building functionality into SQL Server. Finally, with SQL 2008, …
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now