Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I have table :

C#
ID      Person_ID        Person_Relative_ID
 1         10                   20
 2         20                   30
 3         13                   15
 4         30                   40 
 5         55                   56
 6         40                   50       


Here we can see the person & person_relative_id chain is going like 10 - 20 - 30 - 40 - 50

Now if user search Person_Relative_ID of person_id = 20 then result would be like: [All its relation]
C#
Person_Relative_ID
             10
             30
             40
             50



Or user want to search Person_Relative_ID for person_id = 40 . then result like

C#
Person_Relative_ID
            10
            20
            30
            50


Or user want to search Person_Relative_ID for person_id = 50 . then result like

C#
Person_Relative_ID
             10
             20
             30
             40


Any suggestion really appreciated!
Posted
Updated 19-May-14 21:09pm
v3
Comments
Mycroft Holmes 20-May-14 3:40am    
In SQL Server you have "Common Table Expressions" CTE which allows you to create a recursive query

Have a look here: SQL Wizardry Part Three - Common Table Expressions (CTEs)[^]. There you'll find a sample query to get hierarchical data.
 
Share this answer
 
Comments
Mas11 21-May-14 2:38am    
thx a lot for your suggestion,
Try this

SQL
DECLARE @PersonId INT =10;
WITH ForwardRelationsCTE AS(
    SELECT Person_ID, Person_Relative_ID FROM dbo.Relations_Table WHERE Person_ID = @PersonId
    UNION ALL
    SELECT t1.Person_ID  , t1.Person_Relative_ID FROM dbo.Relations_Table AS t1
    JOIN ForwardRelationsCTE AS cte
    ON t1.Person_ID = cte.Person_Relative_ID

),
BackwardRelationsCTE AS(
    SELECT Person_ID, Person_Relative_ID FROM dbo.Relations_Table WHERE Person_Relative_ID = @PersonId
    UNION ALL
    SELECT t1.Person_ID  , t1.Person_Relative_ID FROM dbo.Relations_Table AS t1 JOIN BackwardRelationsCTE AS cte
    ON t1.Person_Relative_ID = cte.Person_ID
)
SELECT Person_ID FROM BackwardRelationsCTE WHERE Person_ID <> @PersonId
UNION
SELECT Person_ID FROM ForwardRelationsCTE WHERE Person_ID <> @PersonId
UNION
SELECT  A.Person_Relative_ID FROM ForwardRelationsCTE AS A
LEFT OUTER JOIN Relations_Table AS B ON A.Person_Relative_ID=B.Person_ID Where B.Person_ID IS NULL



The last union query is to include the last node like person 50 in your example.
 
Share this answer
 
v2
Comments
pkarthionline 21-May-14 4:56am    
hi,
Are you got result or not?
soumyajayaraj 21-May-14 5:18am    
yes I did

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