SQL Server 2008 R2: Prepare a recursive query

2019-08-10 21:26发布

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.

enter image description here

enter image description here

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?

1条回答
\"骚年 ilove
2楼-- · 2019-08-10 21:58
    ;WITH CTE AS
    (
       SELECT COLA,COLB,','+CAST(COLA AS VARCHAR(MAX))+',' AS CHCK FROM TEST WHERE COLA=1
       UNION ALL
       SELECT C1.COLA,C1.COLB,C.CHCK+CAST(C1.cola AS VARCHAR(MAX))+','
       FROM CTE C INNER JOIN TEST C1 ON  C.colb = C1.cola
       WHERE CHARINDEX(','+CAST(C.colb AS VARCHAR(MAX))+',',C.CHCK)=0
    )

   SELECT DISTINCT COLA,COLB FROM CTE ORDER BY COLA
查看更多
登录 后发表回答