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
Soubhagya Ranjan 2Soubhagya Ranjan 2 

batch fail when one record failed

I hav a batch apex in account object . it will update account records . but when one single record failed to update then batch apex failed . please help me on this .. below is my code


global class batchAccount2 implements Database.Batchable<sobject>, Database.stateful {
  
    global Database.QueryLocator start(Database.BatchableContext bc){
      
        String query = 'SELECT Id, Name FROM Account';
        return Database.getQueryLocator(query);
    }
      
    global void execute(Database.BatchableContext bc, List<account> scope) {
      
        for(Account a : scope) {
            a.Name = a.Name + 'Updated';
        }
        // update scope;
        Database.update(scope, false);
    } 
      
    global void finish(Database.BatchableContext bc) {
       // Get the AsyncApexJob that represents the Batch job using the Id from the BatchableContext
 AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
  TotalJobItems, CreatedBy.Email, ExtendedStatus
  from AsyncApexJob where Id = :BC.getJobId()];
  
 // Email the Batch Job's submitter that the Job is finished.
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BatchJob batchAccount2  Status: ' + a.Status);
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
  ' batches with '+ a.NumberOfErrors + ' failures. Please modify the error . ExtendedStatus: ' + a.ExtendedStatus);
   
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}
Best Answer chosen by Soubhagya Ranjan 2
Rohit SharmaGRohit SharmaG
Hi , Try below code in your execute method - 
List<Account> accList = new List<Account>();

for(Account a : scope) {
            a.Name = a.Name + 'Updated';
            accList.add(a);
 }
        // update scope;
        Database.update(accList, false);

All Answers

Rohit SharmaGRohit SharmaG
Hi , Try below code in your execute method - 
List<Account> accList = new List<Account>();

for(Account a : scope) {
            a.Name = a.Name + 'Updated';
            accList.add(a);
 }
        // update scope;
        Database.update(accList, false);
This was selected as the best answer
Soubhagya Ranjan 2Soubhagya Ranjan 2
Thanks Rohit
Paula MenendezPaula Menendez

Hello Rohit SharmaG
I was wondering why your code would work and not the code that 
Soubhagya Ranjan 2 suggested? As far as i understand the only thing your code does is transfer the updated records to another list 'accList' and updating this List instead of updating (scope' list, which is the list that has the original records that need to be updated? 

Thanks!