[green]-- Create dummy data to test functionality[/green]
Declare @Dups Table(Id Int Identity(1,1), EyeColor VarChar(20))
Insert Into @Dups(EyeColor) Values('Blue')
Insert Into @Dups(EyeColor) Values('Blue')
Insert Into @Dups(EyeColor) Values('Blue')
Insert Into @Dups(EyeColor) Values('Blue')
Insert Into @Dups(EyeColor) Values('Blue')
Insert Into @Dups(EyeColor) Values('Brown')
Insert Into @Dups(EyeColor) Values('Brown')
Insert Into @Dups(EyeColor) Values('Brown')
Insert Into @Dups(EyeColor) Values('Brown')
Insert Into @Dups(EyeColor) Values('Brown')
Insert Into @Dups(EyeColor) Values('Brown')
[green]-- See what's in the table to begin with[/green]
Select * From @Dups
[green]-- Suppose you want to KEEP 4 of the 'Blue' rows
-- Calculate the number of rows to delete.[/green]
Declare @CountToDelete Int
Select @CountToDelete = Count(*) -4 From @Dups Where EyeColor = 'Blue'
If @CountToDelete > 0
Begin
[green]-- Only delete if at least one row should be deleted[/green]
Set RowCount @CountToDelete
Delete From @Dups Where EyeColor = 'Blue'
End
Set RowCount 0
-- See what's in the table now.
Select * From @Dups