Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2013-01-02
6
Medium Priority
?
821 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 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
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 
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

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

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…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

636 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