I have the table with the two columns namely cola
and colb
as shown below:
Table : Test
create table Test
(
cola int,
colb int
);
Records I have entered are:
Cola Colb
------------
1 2
1 3
1 4
2 5
2 6
2 3
3 2
3 4
3 7
3 10
10 11
11 12
11 13
11 14
12 15
13 16
14 99
15 88
16 77
Note: Now I want to show the only records who are connected with value I have pass. For example If I pass the value as 1
then it should display me the connected number to it and form connect like a tree.
For this I am using the following script:
WITH CTE
AS
(
SELECT Cola,Colb
FROM Test
WHERE Cola IN
(
SELECT Colb AS Colb
FROM Test
WHERE Cola = '1'
)
),
outerCTE1 AS
(
SELECT Cola,Colb FROM CTE
UNION
SELECT Cola,Colb FROM Test
WHERE Cola IN (SELECT Colb FROM CTE)
),
OuterCTE2 AS
(
SELECT Cola,Colb FROM OuterCTE1
WHERE Colb NOT IN (SELECT Cola FROM CTE)
UNION
SELECT Cola,Colb
FROM Test
WHERE Cola = '1'
),
lastCTE AS
(
SELECT Cola,Colb,ROW_NUMBER() OVER(PARTITION BY Colb ORDER BY Cola) rn FROM outerCTE2
)
SELECT Cola,Colb FROM lastCTE
WHERE rn <=1
ORDER BY CASE WHEN Cola = '1' THEN 1 ELSE 2 END,Cola;
But: The problem is that I am just able to produce records till the 11 but I want to produce all the records till the end whichever match found till the end. So how to write a recursive query for this situation?