时间: 2021-08-13 作者:daque
数据库的运用进程中因为步调上面的题目有功夫会碰到反复数据,反复数据引导了数据库局部树立不许精确树立…… 本领一 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 本领二 有两个意旨上的反复记载,一是实足反复的记载,也即一切字段均反复的记载,二是局部要害字段反复的记载,比方name字段反复,而其余字段不确定反复或都反复不妨忽视。 1、对于第一种反复,比拟简单处置,运用 select distinct * from tablename 就不妨获得无反复记载的截止集。 即使该表须要简略反复的记载(反复记载保持1条),不妨按以次本领简略 select distinct * into #tmp from tablename drop table tablename select * into tablename from #tmp drop table #tmp 爆发这种反复的因为是表安排不周爆发的,减少独一索引列即可处置。 2、这类反复题目常常诉求保持反复记载中的第一条记载,操纵本领如次 假如有反复的字段为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子句中省去此列)