Click here to Skip to main content
15,890,825 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a table with data.
ID  ParentID    NodeName
1   NULL    Administration
2   NULL    Master Data
3   NULL    Input Forms
4   NULL    User Reports
5   NULL    Other Pages
6   1   Add User
7   2   Product Maintanence
8   2   Product BOM
9   3   Expected Sales
10  3   Product BOM
11  4   Finance
12  4   Manufacturing
13  6   GOGS Report
14  7   Purchase History
15  8   Production Report
16  5   Google
17  5   Company Site

Now I want to write a query which distinguish above query result as per parent-child relationship, as Parent_Original>>Parent1>>Child. If the database child goes upto n level it also result like Parent n> Parent n-1> Parent n-2 > ... > Last Child.

In above table scenario it result like.
Parent              Parent-1               Child

Administration      Add User               GOGS Report
Master Data         Product Maintanence    Purchase History
Master Data         Product BOM            Production Report
........... so on

Can any one suggest me how can we do this. Any suggestion really appreciate.
Posted
Updated 10-Jun-13 3:57am
v2

 
Share this answer
 
Comments
Mas11 11-Jun-13 3:32am    
Hi ! Thanks for ur answer.
Try recursive CTE's or form below query dynamically and execute

SQL
select 	
	p2.Nodename,
	p1.Nodename,
	p.Nodename
from [tablem] p (nolock)
left join [tablem] p1 (nolock) on p.parentid=p1.id
left join [tablem] p2 (nolock) on p1.parentid=p2.id
where p2.Nodename is not null
AND p1.Nodename is not null
AND p.Nodename is not null
 
Share this answer
 
Comments
Mas11 11-Jun-13 3:32am    
Hi Hitesh ! Thanks for ur answer but it doesn't give me exact solution.
Hi guys ! I have solved this with the help of one of the brilliant guy. Please see solution below & enjoy with this solution if you'll face such type of task.

SQL
select r.nodename as root
      ,c1.nodename as [child-1]
      ,c2.nodename as [child-2]
      ,c3.nodename as [child-3]
      ,c4.nodename as [child-4]
      ,c5.nodename as [child-5]
from   @tbl r
       left outer join @tbl c1 on r.id = c1.parentid
       left outer join @tbl c2 on c1.id = c2.parentid
       left outer join @tbl c3 on c2.id = c3.parentid
       left outer join @tbl c4 on c3.id = c4.parentid
       left outer join @tbl c5 on c4.id = c5.parentid
where  r.parentid is null
order by r.nodename, c1.nodename, c2.nodename, c3.nodename, c4.nodename, c5.nodename
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900