此文章用了四種方法教你如何用SQL語句重複資料刪除記錄。
問題:怎樣把具有相同欄位的紀錄刪除,只留下一條。
例如:表test裡有id,name欄位,如果有name相同的記錄只留下一條,其餘的刪除。name的內容不定,相同的記錄數不定。
方案1:
1、將重複的記錄記入temp1表:
select [標誌欄位id],count(*) into temp1 from [表名]group by [標誌欄位id]having count(*)>1 |
2、將不重複的記錄記入temp1表:
insert temp1select [標誌欄位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 temp1drop table temp2 |
方案2:
declare @max integer,@id integerdeclare cur_rows cursor local for select id,count(*) from 表名 group by id having count(*) > 1open cur_rowsfetch cur_rows into @id,@maxwhile @@fetch_status=0beginselect @max = @max -1set rowcount @maxdelete from 表名 where id = @idfetch cur_rows into @id,@maxendclose cur_rowsset rowcount 0 |
注:set rowcount @max - 1 表示當前緩衝區只容納@max-1條記錄﹐如果有十條重複的﹐就刪除
10條,一定會留一條的。也可以寫成delete from 表名。
【內容導航】 |
第1頁:一題多解教你SQL語句重複資料刪除記錄 |
第2頁:方案3: |
第3頁:方案4 |
|