当前位置:Gxlcms > mysql > SQLServer中删除重复记录的SQL语句

SQLServer中删除重复记录的SQL语句

时间:2021-07-01 10:21:17 帮助过:132人阅读

本文章来详细的给各位朋友来介绍SQL Server中删除重复记录的SQL语句方法总结,一般情况下,我们会有两种情况的删除操作,一种是完全重复的记录,所有字段都重复的情况,另一种是部分关键字段重复的记录,其他字段不重复,或重复但可以忽略。

方法:

代码如下

distinct * into #tmp from tablename drop table tablename select * into tablename from #tmp
drop table # tmp


常有时候遇到需要删除SQL Server中的重复记录,这里有一些常用的删除重复记录的SQL,


最常用的 T-SQL 语句:

代码如下

DELETE FROM [dbo].[myTable] WHERE 主键 NOT IN
(SELECT MAX(主键) FROM [dbo].[myTable] GROUP BY 列1, 列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 IMMEDIATERelated Posts


SQL存储过程删除

代码如下


declare @max integer,@id integer
declare cur_rows cursor local for select 主字段,count(*) from 表名 主字段 having count(*) > 1
open cur_rows
fetch cur_rows into @id,@max
while @@fetch_status=0
begin
select @max = @max -1
set rowcount @max
delete from 表名 where 主字段 = @id
fetch cur_rows into @id,@max
end
close cur_rows
set rowcount 0

A:保留id最大的行,删除其它行
方法1

代码如下

delete [user] from [user] t
inner join(select name,max(id) as id from [user] group by name) a
on t.name = a.name and t.id <> a.id


B:保留id最小的行,删除其它行

方法1

代码如下
delete [user] from [user] t
inner join(select name,min(id) as id from [user] group by name) a
on t.name = a.name and t.id <> a.id

人气教程排行