程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> 用SQL語句刪除重復記錄的四種方法

用SQL語句刪除重復記錄的四種方法

編輯:關於SqlServer

方案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 表名。

方案3:

create table a_dist(id int,name varchar(20))insert into a_dist values(1,''abc'')insert into a_dist values(1,''abc'')insert into a_dist values(1,''abc'')insert into a_dist values(1,''abc'')exec up_distinct ''a_dist'',''id''select * from a_distcreate procedure up_distinct(@t_name varchar(30),@f_key varchar(30))--f_key表示是分組字段﹐即主鍵字段asbegindeclare @max integer,@id varchar(30) ,@sql varchar(7999) ,@type integerselect @sql = ''declare cur_rows cursor for select ''+@f_key+'' ,count(*) from '' +@t_name +'' group by '' +@f_key +'' having count(*) > 1''exec(@sql)open cur_rows fetch cur_rows into @id,@max while @@fetch_status=0 begin select @max = @max -1 set rowcount @max select @type = xtype from syscolumns where id=object_id(@t_name) and name=@f_keyif @type=56select @sql = ''delete from ''+@t_name+'' where '' + @f_key+'' = ''+ @id if @type=167select @sql = ''delete from ''+@t_name+'' where '' + @f_key+'' = ''+''''''''+ @id +'''''''' exec(@sql)fetch cur_rows into @id,@max end close cur_rows deallocate cur_rowsset rowcount 0endselect * from systypesselect 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved