+ Start a Discussion
lovetolearnlovetolearn 

Problems with Trigger

Hi,

 

I am trying to remove duplicates records after they have been inserted. Not sure where I went wrong, but the trigger only seems to work about 50% of the time. Here is my code:

 

trigger deleteEventDup on Events__c (after update, after insert) {
    for(Events e : trigger.new){  
       Events[] eDup = [SELECT ID FROM Events__c WHERE Case__c =: e.Case__c 
                        AND CreatedDateAndTime__c =: e.CreatedDateAndTime__c
                        AND Type_of_Events__c =: e.Type_of_Events__c  
                        ORDER BY Name ASC];
           if(eDup.size() >1){
            delete eDup[0];        
         }
    }
}

 Please help. Thank you.

bob_buzzardbob_buzzard

Its highly likely you are retrieving the record that you are currently processing via that SOQL query.  As you are only deleting the first value returned from the query, if there is another one that matches that will be left in place.

 

You should exclude the record that you are processing as follows:

 

Events[] eDup = [SELECT ID FROM Events__c WHERE Case__c =: e.Case__c 
                 AND CreatedDateAndTime__c =: e.CreatedDateAndTime__c
                 AND Type_of_Events__c =: e.Type_of_Events__c  
                 AND id!= e:id
                 ORDER BY Name ASC];

 I'm also duty bound to point out that this trigger isn't bulk-safe, so if it is called with a large number of records you will breach governor limits.

lovetolearnlovetolearn

Thank you for your help. 

 

I tried it, but it does not work 100% of the time, not sure why. Please help. 

bob_buzzardbob_buzzard

Have you tried adding debug to see what matches you are getting?