《SQLServer刪除重複數據的方法》

方法一:ide

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 

 

方法二:fetch

有兩個意義上的重複記錄,一是徹底重複的記錄,也即全部字段均重複的記錄,二是部分關鍵字段重複的記錄,好比Name字段重複,而其餘字段不必定重複或都重複能夠忽略。spa

一、對於第一種重複,比較容易解決,使用 設計

 

select distinct * from tableName 

 

就能夠獲得無重複記錄的結果集。 
若是該表須要刪除重複的記錄(重複記錄保留1條),能夠按如下方法刪除code

select distinct * into #Tmp from tableName 
drop table tableName 
select * into tableName from #Tmp 
drop table #Tmp 

發生這種重複的緣由是表設計不周產生的,增長惟一索引列便可解決。 blog


二、這類重複問題一般要求保留重複記錄中的第一條記錄,操做方法以下 
假設有重複的字段爲Name,Address,要求獲得這兩個字段惟一的結果集索引

select identity(int,1,1) as autoID, * into #Tmp from tableName 
select min(autoID) as autoID into #Tmp2 from #Tmp group by Name,autoID 
select * from #Tmp where autoID in(select autoID from #tmp2) 

最後一個select即獲得了Name,Address不重複的結果集(但多了一個autoID字段,實際寫時能夠寫在select子句中省去此列)it

delete from 表名 where 重複字段名 in (select 重複字段名 from 表名 group by 重複字段名 having count(重複字段名) > 1) and id not in (select min(id) from 表名 group by 重複字段名 having count(重複字段名 )>1) 
相關文章
相關標籤/搜索