Click here to Skip to main content
15,891,372 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table with ID column, ParentID column which refer to a parent row in the same table and an IsFavorite column with a true or false value.

I need a query to return all rows which has IsFavorite = True or any of there nested parents rows or any of there nested children has IsFavorite = True?

Note:
There is no limit for nested levels.... may be three or five levels or more.

Thanks Guys :)
Posted

This is called recursive parent child relationship.
Refer given link
1: link
2: link
 
Share this answer
 
What type of issue are you facing now.? As per your requirement you need not worry about parentId and Id the main requirement is filter based on IsFavorite column obviously it should return the parent and child information.

EX:

SQL
select * from tablename
where IsFavorite= true


If this is not your expecting then please elaborate your requirement with some sample data.
 
Share this answer
 
v2
Comments
EiadXP 6-Oct-15 9:01am    
Thanks for your quick response.
Your query will return only favorites row, but i want to get also all its nested children to the last level and all its parents until the root one.
Naveen.Sanagasetti 6-Oct-15 9:17am    
Refer below sample

declare @tab table
(
Id int,
ParentId int,
IsFavorite bit
)

insert into @tab
values (1,null,1),(2,1,1),(3,1,1),(4,2,1),(5,1,1),(6,2,0)

select a.id as Parent, b.id as child
from @tab a,
@tab b
where a.Id=b.ParentId
and a.IsFavorite=1

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