function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
EmplEmpl 

Trigger changes are rolled back for whole batch if there is an error in some records.

I've written a trigger on Account object. When I upload records using Dataloader, or update them using Batch apex(200 batch size), this trigger executes on all records if there is no error. But, it misses the complete batch if there is an error while updating/inserting at-least one record.

 

Can someone give some direction on this?

Please note that accounts having no errors in the batch get updated/inserted, but trigger code is rolled-back on whole batch

 

Please find below the two versions of the trigger(before and after), both dont work:

 

VERSION -1

trigger accountScorerTrigger on Account (before insert, before update) {
  
    if(Trigger.isUpdate || Trigger.isInsert) {
       if(Utility.isFutureUpdate){
          List<Account> accList = new List<Account>();
           // Iterate through all records
          for (Account newAccount:Trigger.new) {
              Account tempAcc = new Account(id = newAccount.id);
              tempAcc.Account_Score_History__c = 'TESTING RECORDS 3';
              accList.add(tempAcc);
          }
          Utility.isFutureUpdate = false;
          if(accList.size()>0){
               //update accList;
               Database.DMLOptions dml = new Database.DMLOptions();
               dml.optAllOrNone = true;
               database.update(accList,dml);
          }
      }
   }

}


VERSION -2

trigger accountScorerTrigger on Account (before insert, before update) {

    if(Trigger.isUpdate || Trigger.isInsert) {
        for (Account newAccount:Trigger.new) {
              newAccount.Account_Score_History__c = 'TESTING RECORDS 5';
        }
}

 

Thanks,

Vishal

yvk431yvk431

its how it works, Every batch will fall under a separate context and so when the context encounters any error the changes made to the batch will get  reverted. one workaround is to have some flag and set it when a batch runs on it . Later you can run the batch for the missed ones with batch size 1. Or if the total records are few thousands you can directly  limit batch size to 1 and execute, only the problematic records will get effected .

 

 

--yvk

Prafull G.Prafull G.

Hi Vishal,

 

Did you get any updates or any workaround for this issue?

 

Thanks,

-P

EmplEmpl

I didnt find a solution because as said earlier in this thread this is actually how it works. So, the workaround I have found is that I stored a flag for the set of records which failed in custom object and reduce the batch size by doing update using batch class with smaller batches.