SQL Server 2008 R2:准备递归查询

时间:2015-10-02 05:01:06

标签: sql-server sql-server-2008-r2

我的表格包含两列colacolb,如下所示:

表:Test

create table Test
(
   cola int,
   colb int
);

我输入的记录是:

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

注意:现在我想显示与我已通过的值相关联的唯一记录。例如,如果我将值传递给1,那么它应该显示连接的数字,并形成像树一样的连接。

enter image description here

enter image description here

为此,我使用以下脚本:

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;

但是:问题是我只能生成记录直到11,但我想生成所有记录,直到最后找到匹配到最后。那么如何为这种情况编写递归查询呢?

1 个答案:

答案 0 :(得分:1)

    ;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