use EnVisage DECLARE @dupTable TABLE (Id UNIQUEIDENTIFIER, ParentId UNIQUEIDENTIFIER, WeekEndingDate DateTime, ExpCatId UNIQUEIDENTIFIER) insert into @dupTable(Id, ParentId, WeekEndingDate, ExpCatId) select newId(), d.ParentID, d.WeekEndingDate, d.ExpenditureCategoryId from ScenarioDetail d left join scenario s on s.id = d.ParentID left join project p on p.id = s.ParentId left join ScenarioDetail md on md.ParentID = d.ParentID and md.ExpenditureCategoryId = d.ExpenditureCategoryId and md.WeekEndingDate = d.WeekEndingDate where s.type <> 1 and s.type <>13 group by d.ParentID, d.ExpenditureCategoryId, d.WeekEndingDate, s.name, s.type, p.name having count(md.Id) > 1 order by ParentID, ExpenditureCategoryId, WeekEndingDate declare @parentId uniqueidentifier declare @weekDate DateTime declare @expCatId uniqueidentifier declare @Id uniqueidentifier declare dupcursor cursor for select Id from @dupTable open dupcursor fetch next from dupcursor into @Id while @@FETCH_STATUS = 0 begin select @parentId = ParentId, @weekDate = WeekEndingDate, @expCatId = ExpCatId from @dupTable where Id = @Id DELETE FROM ScenarioDetail WHERE ParentId = @parentId and WeekEndingDate = @weekDate and ExpenditureCategoryId = @expCatId and Id <> ( SELECT Top(1) d.Id FROM ScenarioDetail d left join History h on d.Id = h.EntityId where d.ParentId = @parentId and d.WeekEndingDate = @weekDate and d.ExpenditureCategoryId = @expCatId order by h.TimeStamp desc ) fetch next from dupcursor into @Id end close dupcursor; deallocate dupcursor; DELETE FROM @dupTable declare @check as bit select @check = 1 --d.ParentID, d.ExpenditureCategoryId , d.WeekEndingDate, s.type, count(d.Id) as ctr from ScenarioDetail d left join scenario s on s.id = d.ParentID left join project p on p.id = s.ParentId left join ExpenditureCategory ec on ec.id = d.ExpenditureCategoryId where s.type <> 1 and s.type <> 13 --and d.ParentID = 'B58FD530-817C-475D-AD15-1065F3670063' group by d.ParentID,d.ExpenditureCategoryId , d.WeekEndingDate, s.type, p.name having count(d.Id) > 1 order by d.ParentID, d.ExpenditureCategoryId , WeekEndingDate Print iif(@check is null, 'Script ran successfully', 'Script ran incorrectly')