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
WminWmin 

Is it possible to call Database.executeBatch from a For loop

I am processing hundreds of thousands of call records that must be assigned to their respective telephone lines based on the phone number. I wanted to retrieve a list of Phone Line records and then create multiple batch jobs to find all related telephone call records. 

public void GetLines(){

        List<Lines__c> lines = [Select id, phone_number__c from lines__c ORDER BY Line_Status__c ASC];
        
        for(Lines__c l: lines){
                   ExecuteBatchUpdate(l.id, l.phone_number__c );         
        }  
    }

public void ExecuteBatchUpdate(Id lineid, String phone){
..
If(Test.isRunningTest()){
            Id batchInstanceId = Database.executeBatch(new BatchUpdateCallRecordsAssingLine(q, Lineid), 20); 
            System.abortJob(batchInstanceId);
        }else{
                Database.executeBatch(new BatchUpdateCallRecordsAssingLine(q, Lineid));
        }
..
}

Unfortunately, I get System.LimitException: Too many DML statements: 151

Is it possible to call Database.executeBatch from a loop?  If not, what is the right way do deal with this scenario?

Your advice would be much appreciated.

Many thanks in advance.
 
Deepali KulshresthaDeepali Kulshrestha
Hi Wmin,

I've gone through your requirement and you can refer below code for the solution:

(Note--> I am passing the index and list of (lines__c) to pass the id and phone number to next batch)
Apex Code:--->

List<Lines__c> lines = [Select id, phone_number__c from lines__c ORDER BY Line_Status__c ASC];
        
Integer i=0;

        
ExecuteBatchUpdate(lines[i].id, lines[i].phone_number__c ,i++,lines);      //executing batch   
       

global class batchNotesInsert implements Database.Batchable<sObject>, Database.Stateful {

    Integer i=0;
    List<Lines__c> newLines=new List<Lines__c>();

    public batchNotesInsert(String strParam) {
        strParameter = strParam;
    }

global database.querylocator start(Database.BatchableContext BC)
{
  //start method logic here
}

global void execute(Database.BatchableContext BC, List<sObject> scope)
 {
    //start method logic here
}

global void finish(Database.BatchableContext BC)
 {
       //call next batch
       ContactBatch newBatchCLass= new ContactBatch();
      Id batchProcessId = Database.executeBatch(newBatchCLass,newLines[i].id,newLines[i].phone_number__c,i++,newLines);
    
     //finish method logic here
}

}


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com