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
fiona gentryfiona gentry 

Need Help to change existing Batch Apex code to Database.insert() to insert records, iterate over the results, and persist information about any failures to the database

Hi,

I need to to change below code and use Database.insert() to insert records, iterate over the results, and persist information about any failures to the database ...reason to do above is I want to report Records in Batchable Salesforce apex code such that it should report where the Level2 or Level3 are NULL..Can some one edit the below Batch apex code to use Database.insert() to insert records, iterate over the results, and persist information about any failures to the database

here is current code
global class ertcopybatch3pm implements Database.Batchable<sObject> {
              
                global Database.QueryLocator start(Database.BatchableContext BC) {
                    // collect the batches of records or objects to be passed to execute
                    
                    String query = 'select Case__c, Level_1__c, Level_2__c,Level_3__c  FROM ERT_Case_Type__c';
                    System.debug('ERT Case No is =====>' +query);
                    return Database.getQueryLocator(query);
                }
                
                global void execute(Database.BatchableContext BC, List<ERT_Case_Type__c> exeList) {
                   
                    // process each batch of records
            List<Case_Type__c> listCTD = new List<Case_Type__c>();
                    System.debug('ERT Case No is =====>' +exeList);
                    for(ERT_Case_Type__c exe : exeList)
                    {        
                         listCTD.add(new Case_Type__c(Case__c=exe.Case__c,Level_1__c=exe.Level_1__c,Level_2__c=exe.Level_2__c,Level_3__c=exe.Level_3__c));
                       // System.debug('ERT Case No is =====>' +Case__c);
                    }
                    try {
                      System.debug('ERT Case No is =====>' +listCTD);
                        insert listCTD;
                    
                    } catch(Exception e) {
                        System.debug(e);
                    }
                    
                }   
                
                global void finish(Database.BatchableContext BC) {
                  // execute any post-processing operations
              }
            }

Your help is highly appreciated

Regards.
Fiona
Best Answer chosen by fiona gentry
Abdul KhatriAbdul Khatri
Hi Fiona,

Is this what you are looking for
 
global class ertcopybatch3pm implements Database.Batchable<sObject> {
              
    global Database.QueryLocator start(Database.BatchableContext BC) {
        // collect the batches of records or objects to be passed to execute
        
        String query = 'select Case__c, Level_1__c, Level_2__c,Level_3__c  FROM ERT_Case_Type__c';
        System.debug('ERT Case No is =====>' +query);
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<ERT_Case_Type__c> exeList) {
        
        // process each batch of records
        List<Case_Type__c> listCTD = new List<Case_Type__c>();
        System.debug('ERT Case No is =====>' +exeList);
        for(ERT_Case_Type__c exe : exeList)
        {        
            listCTD.add(new Case_Type__c(Case__c=exe.Case__c,Level_1__c=exe.Level_1__c,Level_2__c=exe.Level_2__c,Level_3__c=exe.Level_3__c));
            // System.debug('ERT Case No is =====>' +Case__c);
        }

        System.debug('ERT Case No is =====>' +listCTD);
        insert listCTD;
        
        
        Database.SaveResult[] srList = Database.insert(listCTD, false);
        
        // Iterate through each returned result
        for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                System.debug('Successfully inserted Case_Type__c: ' + sr.getId());
            }
            else {
                // Operation failed, so get all errors                
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Case_Type__c fields that affected this error: ' + err.getFields());
                }
            }
        }            
        
    }   
    
    global void finish(Database.BatchableContext BC) {
        // execute any post-processing operations
    }
}

 

All Answers

RituSharmaRituSharma
You may use similar logic to handle success and errors based on your requirement:

    Database.UpsertResult[] insertResult = Database.upsert(listCTD,false);            
    for(Integer i = 0; i < insertResult.size(); i++) {
        if(insertResult[i].isSuccess()) {
            System.debug('Success');
        } else {
            System.debug('Error reasons '+string.join(insertResult[i].getErrors(),','));
        }                
    }
Abdul KhatriAbdul Khatri
Hi Fiona,

Is this what you are looking for
 
global class ertcopybatch3pm implements Database.Batchable<sObject> {
              
    global Database.QueryLocator start(Database.BatchableContext BC) {
        // collect the batches of records or objects to be passed to execute
        
        String query = 'select Case__c, Level_1__c, Level_2__c,Level_3__c  FROM ERT_Case_Type__c';
        System.debug('ERT Case No is =====>' +query);
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<ERT_Case_Type__c> exeList) {
        
        // process each batch of records
        List<Case_Type__c> listCTD = new List<Case_Type__c>();
        System.debug('ERT Case No is =====>' +exeList);
        for(ERT_Case_Type__c exe : exeList)
        {        
            listCTD.add(new Case_Type__c(Case__c=exe.Case__c,Level_1__c=exe.Level_1__c,Level_2__c=exe.Level_2__c,Level_3__c=exe.Level_3__c));
            // System.debug('ERT Case No is =====>' +Case__c);
        }

        System.debug('ERT Case No is =====>' +listCTD);
        insert listCTD;
        
        
        Database.SaveResult[] srList = Database.insert(listCTD, false);
        
        // Iterate through each returned result
        for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                System.debug('Successfully inserted Case_Type__c: ' + sr.getId());
            }
            else {
                // Operation failed, so get all errors                
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Case_Type__c fields that affected this error: ' + err.getFields());
                }
            }
        }            
        
    }   
    
    global void finish(Database.BatchableContext BC) {
        // execute any post-processing operations
    }
}

 
This was selected as the best answer