如果没有递归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
答案 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