?
Solved

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

Posted on 2013-01-02
6
Medium Priority
?
804 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

     When we have to pass multiple rows of data to SQL Server, the developers either have to send one row at a time or come up with other workarounds to meet requirements like using XML to pass data, which is complex and tedious to use. There is a …
After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

764 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