今天在刷新数据库数据时发现,因为自己表中主键字段不能包含了相同的记录,而从外来表抛转数据的过程中,外来数据表在该字段中包含相同的一行数据,导致执行存储过程中出现异常。

   如何处理掉重复数据并且保留其中的一条数据呢?其中一个方法如下:
   重新建立一个临时表,把源表数据转入这个临时表中,其中临时表字段与目标表字段一至只是关键字段不需要设置为主键,然后对这个临时表进行重复数据删除,并且保留唯一数据,再把该临时表数据转入目标表中,执行完后清空临时表。 

 临时表中重复数据如何删除呢?

1.如果是重复行数据都一致:select distinct(*) from 临时表 ,得到唯一数据在转入至目标表中,

如下:
     select distinct(*)into #temp from 源表
     select * into 目标表 from #temp
     drop table #temp
2.如果只是某一字段重复:
通过创建临时表#temp1 获得一个带有自动递增字段及源表的其他字段
select  identity(int,1,1)  as tempID ,*  into #temp1 from 源表
创建临时表#temp2  获得 最小的 一个重复列的ID
select min(tempID) into #temp2 from #temp1 group by 重复字段
select * from #temp where tempID in(select tempIDfrom #tmp2)得到没重复的结果集。
3.
declare @max integer,@id integer
declare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 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
fetch cur_rows into @id,@max
end
close cur_rows
set rowcount 0