在删除之前将重复记录移动到另一个表

时间:2016-02-16 10:24:56

标签: sql-server duplicates insert-into

我发现这个很棒的代码可以删除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;

现在我想在删除之前将重复记录移动到另一个表。任何帮助将非常感激。感谢。

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;