Method One:
Declare @max integer,@id integer DeclareCur_rowscursorLocal for SelectMain field,Count(*) fromTable nameGroup byMain field having Count(*)> 1 Opencur_rowsFetchCur_rows into @id,@max while @ @fetch_status=0 begin Select @max = @max -1 Set RowCount @max Delete fromTable namewhereMain field= @id FetchCur_rows into @id,@max End Closecur_rowsSet RowCount 0
Method Two:
There are two meanings of duplicate records, one is a completely duplicate record, that is, all fields are duplicated records, and the second is some key field duplicate records, such as the Name field repeats, and other fields may not be repeated or can be ignored.
1, for the first kind of repetition, easier to solve, using
Select distinct * from
You can get a result set with no duplicate records.
If the table needs to delete duplicate records (duplicate records retain 1), you can delete them as follows
Select distinct * into from droptable select * into from droptable
This duplication occurs because the table is poorly designed and the unique index columns are added to resolve.
2, this kind of repetition problem usually requires to keep the first record in the duplicate record, the operation method is as follows
Suppose there is a duplicate field name,address, which requires the result set to be unique for both fields
Select Identity(int,1,1) asAutoid,* into#Tmp fromTableNameSelect min(autoid) asAutoid into#Tmp2 from#TmpGroup byname,autoidSelect * from#TmpwhereAutoidinch(SelectAutoid from#tmp2)
The last select is the result set that name,address not duplicate (but one more autoid field, which can be written in the SELECT clause without this column in the actual write)
Delete fromTable namewhererepeating field namesinch(Selectrepeating field names fromTable nameGroup byrepeating field names having Count(repeating field name)> 1) andId not inch(Select min(ID) fromTable nameGroup byrepeating field names having Count(repeating field name)>1)
How SQL Server removes duplicate data