在SQL Server中除了对拥有十几条记录的表进行人工删除外,实现删除重复记录一般都是写一段代码,用游标的方法一行一行检查,删除重复的记录。因为这种方法需要对整个表进行遍历,所以对于表中的记录数不是很大的时候还是可行的,如果一张表的数据达到上百万条,用游标的方法来删除简直是个噩梦,因为它会执行相当长的一段时间。
轻松消除重复记录
在SQL Server中有一种更为简单的方法,它不需要用游标,只要写一句简单插入语句就能实现删除重复记录的功能。为了能清楚地表述,我们首先假设存在一个产品信息表Products,其表结构如下:
CREATE TABLE Products (
ProductID int,
ProductName nvarchar (40),
Unit char(2),
UnitPrice money
)
一、建立一张具有相同结构的临时表
CREATE TABLE Products_temp (
ProductID int,
ProductName nvarchar (40),
Unit char(2),
UnitPrice money
)
二、为该表加上索引,并使其忽略重复的值
三、拷贝产品信息到临时表
insert into Products_temp Select * from Products
此时SQL Server会返回如下提示:
服务器: 消息 3604,级别 16,状态 1,行 1
已忽略重复的键。
它表明在产品信息临时表Products_temp中不会有重复的行出现。
四、将新的数据导入原表
将原产品信息表Products清空,并将临时表Products_temp中数据导入,最后删除临时表Products_temp。
delete Products
insert into Products select * from Products_temp
drop table Products_temp
这样就完成了对表中重复记录的删除。无论表有多大,它的执行速度都是相当快的,而且因为几乎不用写语句,所以它也是很安全的。
小提示:上述方法中删除重复记录取决于创建唯一索引时选择的字段,在实际的操作过程中读者务必首先确认创建的唯一索引字段是否正确,以免将有用的数据删除。
------------------------------------------------------------------------------
方法二:group by
查数据:
select count(num), max(name) from student --列出重复的记录数,并列出他的name属性
group by num
having count(num) >1 --按num分组后找出表中num列重复,即出现次数大于一次
删数据:
delete from student
group by num
having count(num) >1
这样的话就把所有重复的都删除了。
3.用distinct方法 -对于小的表比较有用
create table table_new as select distinct * from table1 minux
truncate table table1;
insert into table1 select * from table_new;
delete select a.* from FLRK1 a inner join FLRK1 b on a.记录号=b.记录号 and
(a.[ID]=b.[ID] and a.入库日期=b.入库日期 and a.操作时间=b.操作时间)
delete from FLRK1 where 记录号 in
(select min(记录号) from FLRK1 group by 记录号 having count(记录号)>1)
A表结构:
ID RQ SJ C
--------------------------------------------
1 2005-07-14 14:20:50 A1
2 2005-02-15 05:12:23 A1
3 2005-07-14 14:20:50 A1
4 2005-06-16 16:16:16 A2
5 2005-06-16 16:16:16 A2
6 2005-05-18 05:10:35 A3
7 2005-02-15 05:12:23 A1
--------------------------------------------
求SQL语句一条,把表A中 RQ,SJ,C 三个字段有相同的重复记录删除.
得到的结果:
ID RQ SJ C
--------------------------------------------
1 2005-07-14 14:20:50 A1
2 2005-02-15 05:12:23 A1
4 2005-06-16 16:16:16 A2
6 2005-05-18 05:10:35 A3
--------------------------------------------
Delete from A Where ID Not In (Select Min(ID) from A Group By RQ,SJ,C )
Delete a from tb a inner join tb as b on a.fid <b.fid and a.c=b.c and a.rq=b.rq and a.sj=b.sj
delete from A t
where exists(select 1 from A where ID <A.ID and SJ=t.SJ and RQ=t.RQ and C=t.c)
存储过程使用游标实现:
declare @max integer,@id integer
declare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 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