2011-08-15

SQL Server中删除重复记录的SQL

0

常有时候遇到需要删除SQL Server中的重复记录,这里有一些常用的删除重复记录的SQL,收藏备用,转自(loveyuki.com),感谢。

最常用的 T-SQL 语句:

DELETE FROM [dbo].[myTable] WHERE 主键 NOT IN 
    (SELECT MAX(主键) FROM [dbo].[myTable] GROUP BY1,2,3)

从 SQL Server 2005 以后,用 CTE:

WITH tmpOrderdTable 
AS 
( 
  SELECT  
    GroupID = ROW_NUMBER() OVER (PARTITION BY 列1, 列2, 列3 ORDER BY 主键) 
  FROM 
    [dbo].[myTable] 
) 
 
DELETE FROM tmpOrderdTable WHERE GroupID > 1

为了提高效率可以先开启单人存取模式,删除完再恢复多人存取模式:

# 开启单人存取模式  
USE [master]  
ALTER DATABASE [myDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE  
 
# 开启多人存取模式  
USE [master]  
ALTER DATABASE [myDB] SET MULTI_USER WITH ROLLBACK IMMEDIATE