Solved

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

Posted on 2013-01-02
6
760 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
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 
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

Back Up Your Microsoft Windows Server®

Back up 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.

Question has a verified solution.

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

Suggested Solutions

I have written a PowerShell script to "walk" the security structure of each SQL instance to find:         Each Login (Windows or SQL)             * Its Server Roles             * Every database to which the login is mapped             * The associated "Database User" for this …
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 gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

809 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