新聞中心
使用SQL語句有多種刪除重復(fù)記錄的方法,下文為您介紹四種方法,教你如何用SQL語句刪除重復(fù)記錄,供您參考,希望對(duì)您有所幫助。

問題:怎樣把具有相同字段的紀(jì)錄刪除,只留下一條。
例如:表test里有id,name字段,如果有name相同的記錄只留下一條,其余的刪除。name的內(nèi)容不定,相同的記錄數(shù)不定。
方案1:
1、將重復(fù)的記錄記入temp1表:
select [標(biāo)志字段id],count(*) into temp1 from [表名]
group by [標(biāo)志字段id]
having count(*)>1
2、將不重復(fù)的記錄記入temp1表:
insert temp1
select [標(biāo)志字段id],count(*) from [表名]
group by [標(biāo)志字段id]
having count(*)=1
3、作一個(gè)包含所有不重復(fù)記錄的表:
select * into temp2 from [表名]
where 標(biāo)志字段id in(select 標(biāo)志字段id from temp1)
4、刪除重復(fù)表:delete [表名]
5、恢復(fù)表:#p#
insert [表名]
select * from temp2
6、刪除臨時(shí)表:
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 表示當(dāng)前緩沖區(qū)只容納@max-1條記錄﹐如果有十條重復(fù)的﹐就刪除
10條,一定會(huì)留一條的。也可以寫成delete from 表名。
分享文章:四種SQL語句刪除重復(fù)記錄的方法
URL分享:http://www.dlmjj.cn/article/dpcpjdd.html


咨詢
建站咨詢
