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
Miranda L 2Miranda L 2 

System DmlException Update failed

Hello there,
my batch class failed to update some records please do help me. Here is the error message
Failed to process batch for class 'BatchFirstInvoiceasProductClient' for job id '7070X0000CQtt7h' caused by: System.DmlException: Update failed. First exception on row 0 with id 0010X00004LVOpyQAH; first error: UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record or 200 records:


Thank you
Miranda L 2Miranda L 2
here is my batch class
global class BatchFirstInvoiceasProductClient implements Database.Batchable<sObject>,Schedulable {
        
    String query = 'SELECT Id,(SELECT id, Date_Invoice__c From Invoices__r WHERE Contract_Service_Provided__c != null and Category_Invoice__c !=\'Monthly\' And Contract_Service_Provided__c != \'CURRENCY ACCOUNTS;\' ORDER BY Date_Invoice__c ASC LIMIT 1) FROM Account';
    
    global BatchFirstInvoiceasProductClient() {
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope) {    
        List<Account> toUpdate = New List <Account> ();
        for(Account A: (List<Account>) scope) {
            Account oneAccount;
            if(!A.Invoices__r.isEmpty()){
                oneAccount = new Account();
                oneAccount.Id = A.Id;
                oneAccount.First_Invoice_as_Product_Client__c = A.Invoices__r[0].Date_Invoice__c;
                system.debug('first invoice as product client'+oneAccount.First_Invoice_as_Product_Client__c);
                toUpdate.add(oneAccount);
            }
            if(A.Invoices__r.isEmpty()){
                oneAccount = new Account();
                oneAccount.Id = A.Id;
                oneAccount.First_Invoice_as_Product_Client__c=null;
                toUpdate.add(oneAccount);
            }
        }
        
        update toUpdate;
    }
    
    global void finish(Database.BatchableContext bc){
        
    }
    
    global void execute(SchedulableContext sc) {
        BatchFirstInvoiceasProductClient batchable = new BatchFirstInvoiceasProductClient();
        Database.executeBatch(batchable, 300);
    }
}