我发现这个很棒的代码可以删除SQL Server表中的重复行。
;WITH x AS
(
SELECT col1, col2, col3, rn = ROW_NUMBER() OVER
(PARTITION BY col1, col2, col3 ORDER BY id)
FROM dbo.tbl
)
DELETE x WHERE rn > 1;
现在我想在删除之前将重复记录移动到另一个表。任何帮助将非常感激。感谢。
答案 0 :(得分:2)
您可以简单地复制粘贴CTE并使用它两次:
;WITH x AS
(
SELECT col1, col2, col3, rn = ROW_NUMBER() OVER
(PARTITION BY col1, col2, col3 ORDER BY id)
FROM dbo.TableName1
)
INSERT INTO dbo.TableName2
SELECT columns FROM x WHERE rn > 1;
;WITH x AS
(
SELECT col1, col2, col3, rn = ROW_NUMBER() OVER
(PARTITION BY col1, col2, col3 ORDER BY id)
FROM dbo.TableName1
)
DELETE FROM x WHERE rn > 1;