-2

没有递归 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
4

1 回答 1

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
于 2013-06-10T07:15:23.817 回答