没有递归CTE使用如何得到低于预期的结果

时间:2013-06-10 07:04:56

标签: sql sql-server

如果没有递归CTE,请使用如何获得低于预期的结果..

DECLARE @temp TABLE 
(
      ParentCode VARCHAR (100)
    , ChildCode VARCHAR(100)
) 

INSERT INTO @temp
SELECT '101', '102' UNION ALL 
SELECT '102', '101' UNION ALL 
SELECT '103', '104' UNION ALL 
SELECT '104', '103' UNION ALL 
SELECT '105', '106' UNION ALL 
SELECT '106', '105'

SELECT * FROM @temp

输出:

ParentCode 
101
103
105

1 个答案:

答案 0 :(得分:1)

试试这个 -

<强>查询:

DECLARE @temp TABLE 
(
      ParentCode VARCHAR (100)
    , ChildCode VARCHAR(100)
) 

INSERT INTO @temp
SELECT '101', '102' UNION ALL 
SELECT '102', '101' UNION ALL 
SELECT '103', '104' UNION ALL 
SELECT '104', '103' UNION ALL 
SELECT '105', '106' UNION ALL 
SELECT '106', '105'

;WITH cte AS 
(
    SELECT 
          ParentCode
        , ChildCode
        , rn = ROW_NUMBER() OVER (ORDER BY ParentCode, ChildCode)
    FROM @temp 
)    
SELECT t.ParentCode 
FROM cte t
WHERE EXISTS(
    SELECT 1 
    FROM cte t2 
    WHERE t.ParentCode = t2.ChildCode
        AND t.rn < t2.rn
)

<强>输出:

ParentCode
----------
101
103
105