Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
this is my table structure..


id name parentid
1 Mobile null
2 Nokia 1
3 nokia lumia 2
4 nokia Lumia520 3
5 computer null
6 dell 5
7 lenovo 5
8 dell 697 6
9 lenovo 220 7

now if i select mobile I want output like

mobile
nokia
nokia Lumia
nokia Lumia520

is it possible?
Posted

use this:

SQL
with cte(parent_id,id)
as
(
select parent_id,Id from table where parent_id is null
union all

select parent_id,ID from table as a inner join cte as b on b.id=a.parent_id
)
select *from cte
 
Share this answer
 
Comments
Ankur\m/ 11-Mar-14 9:24am    
I left that for the user to understand and try himself/herself.
Tom Marvolo Riddle 11-Mar-14 9:29am    
I agree with you.+5 for that
Ankur\m/ 11-Mar-14 9:31am    
Thank you!
King Fisher 11-Mar-14 9:32am    
i hope he will learn from your link .i thought he stuck with that. :)
Yes, it is possible. You will need to use Common Table Expressions (CTE)[^] here. For more details see the MS Technet article - Recursive Queries Using Common Table Expressions
[^]
 
Share this answer
 
Comments
utm 11-Mar-14 10:37am    
thanks..
i never heard about this..
i got new things to learn..

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