Click here to Skip to main content
15,665,942 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

nokia Lumia
nokia Lumia520

is it possible?

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
utm 11-Mar-14 10:37am    
i never heard about this..
i got new things to learn..
use this:

with cte(parent_id,id)
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
select *from cte
Share this answer
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. :)

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