-
--Setup a table and add some data for rhe example to work with
-
create table tblDulicateDates([Num1] [tinyint],[Num2] [tinyint],[dte] [datetime])
-
-
delete from tblDulicateDates
-
insert into tblDulicateDates select 1,1,'2026-01-01'
-
insert into tblDulicateDates select 1,1,'2026-01-02'
-
insert into tblDulicateDates select 1,1,'2026-01-03'
-
insert into tblDulicateDates select 1,2,'2026-01-01'
-
insert into tblDulicateDates select 1,2,'2026-01-02'
-
insert into tblDulicateDates select 1,2,'2026-01-03'
-
insert into tblDulicateDates select 1,3,'2026-01-01'
-
-
-
-
--show the table contents with the duplicate records except for date
-
select * from tblDulicateDates
-
-
--Declare the necessary variables
-
Declare @ThereAreDuplicates int,@Num1 int,@Num2 int, @Dte datetime
-
-
-
--see if there are any duplicate records
-
set @ThereAreDuplicates=(select count(a.num1) from
-
(select num1,num2,min(Dte) as Dte from tblDulicateDates group by num1,num2)a
-
join
-
(select num1,num2,max(Dte) as Dte from tblDulicateDates group by num1,num2)b on a.num1=b.num1 and a.num2=b.num2
-
where a.dte<>b.dte)
-
-
-
--if there are duplicates then enter the loop
-
while @ThereAreDuplicates > 0
-
BEGIN
-
--select the duplicates that need to be deleted into a cursor
-
DECLARE DuplicatesCursor CURSOR FOR
-
select a.num1,a.num2,a.dte from
-
(select num1,num2,min(Dte) as Dte from tblDulicateDates group by num1,num2)a
-
join
-
(select num1,num2,max(Dte) as Dte from tblDulicateDates group by num1,num2)b on a.num1=b.num1 and a.num2=b.num2
-
where a.dte<>b.dte
-
-
-
OPEN DuplicatesCursor
-
FETCH NEXT FROM DuplicatesCursor
-
INTO @Num1,@Num2,@Dte
-
-
-
--enter a loop that deletes each of the records in the cursor
-
WHILE @@FETCH_STATUS = 0
-
BEGIN
-
DELETE FROM tblDulicateDates where Num1=@Num1 and Num2=@Num2 and Dte=@Dte
-
-
FETCH NEXT FROM DuplicatesCursor
-
INTO @Num1,@Num2,@Dte
-
END
-
CLOSE DuplicatesCursor
-
DEALLOCATE DuplicatesCursor
-
-
--Check to see if there are any more duplicates still in the table
-
--This is to handle the case where there are 3 or more duplicate records
-
set @ThereAreDuplicates=(select count(a.num1) from
-
(select num1,num2,min(Dte) as Dte from tblDulicateDates group by num1,num2)a
-
join
-
(select num1,num2,max(Dte) as Dte from tblDulicateDates group by num1,num2)b on a.num1=b.num1 and a.num2=b.num2
-
where a.dte<>b.dte)
-
-
END
-
-
--now show the table contents
-
-- no duplicates and only the ones that had the max date are left
-
select * from tblDulicateDates