四種SQL語句刪除重復記錄的方法
使用SQL語句有多種刪除重復記錄的方法,下文為您介紹四種方法,教你如何用SQL語句刪除重復記錄,供您參考,希望對您有所幫助。
問題:怎樣把具有相同字段的紀錄刪除,只留下一條。
例如:表test里有id,name字段,如果有name相同的記錄只留下一條,其余的刪除。name的內容不定,相同的記錄數(shù)不定。
方案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、恢復表:#p#
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 表示當前緩沖區(qū)只容納@max-1條記錄﹐如果有十條重復的﹐就刪除
10條,一定會留一條的。也可以寫成delete from 表名。