首页数据库类 mssql → 一题多解教你SQL语句删除重复记录

一题多解教你SQL语句删除重复记录

日期:2007-4-29 09:07:02 出处:其他转载 作者:不详 人气:
上一页 [1] [2] 下一页

此文章用了四种方法教你如何用SQL语句删除重复记录。

问题:怎样把具有相同字段的纪录删除,只留下一条。

例如:表test里有id,name字段,如果有name相同的记录只留下一条,其余的删除。name的内容不定,相同的记录数不定。

方案1:

1、将重复的记录记入temp1表:

select [标志字段id],count(*) into temp1 from [表名]
group by [标志字段id]
having count(*)>1

2、将不重复的记录记入temp1表:

insert temp1
select [标志字段id],count(*) from [表名]
group by [标志字段id]
having count(*)=1

3、作一个包含所有不重复记录的表:

select * into temp2 from [表名]
where 标志字段id in(select 标志字段id from temp1)

4、删除重复表:delete [表名]

5、恢复表:

insert [表名]
select * from temp2

6、删除临时表:

drop table temp1
drop table temp2

方案2:

declare @max integer,@id integer
declare cur_rows cursor local for 
select id,count(*) from 表名 group by id 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 = @id
fetch cur_rows into @id,@max
end
close cur_rows
set rowcount 0

注:set rowcount @max - 1 表示当前缓冲区只容纳@max-1条记录﹐如果有十条重复的﹐就刪除

10条,一定会留一条的。也可以写成delete from 表名。

上一页 [1] [2] 下一页

关于本站 | 帮 助 | 广告服务 | 版权声明 | 业务合作 | 捐助本站 | 软件发布 | 联系我们
77资源下载 www.77zy.com ©2007-2008 版权所有
备案编号:赣ICP备07002641号  QQ:674648476