?
Solved

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

Posted on 2013-01-02
6
Medium Priority
?
835 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 23

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
Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

 
LVL 9

Accepted Solution

by:
sognoct earned 2000 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

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is basically a blog post I wrote recently. I've found that SARGability is poorly understood, and since many people don't read blogs, I figured I'd post it here as an article. SARGable is an adjective in SQL that means that an item can be fou…
Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?

839 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