Skip to main content
Soubhagya Ranjan ha fatto una domanda in #Apex
Hi 

I have a requirement . in this i have to insert and update account records . 

If account filed failed to insert then status field value will be IF .

If account field failed to update then status field value will be UF .

After batch apex execute there are records which will be failed to insert and failed to update .

I want to send mail to the owner that these records are failed due to duplicate value .

How to send this mail to owner in the finish method of batch apex .

 
3 risposte
  1. 4 gen 2017, 14:40
    Hi,

    Use Database Class methods to do partial update. With Database.SaveResult[], you will get the status of DML operation.

    Sample example here:

    // Create the list of sObjects to insert

    List<Account> acctList = new List<Account>();

    acctList.add(new Account(Name='Acme1'));

    acctList.add(new Account(Name='Acme2'));

    // DML statement

    Database.SaveResult[] srList = Database.insert(acctList, 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 account. Account ID: ' + 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('Account fields that affected this error: ' + err.getFields());

    }

    }

    }

    Once you got the output,  you just have to send an email from the error block by using Messaging.SinglEmailMessage.

     

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    String[] toAddresses = new String[] {email1, emaiol2};

    mail.setToAddresses(toAddresses);

    mail.setSubject('Batch Subject ' + a.Status);

    mail.setPlainTextBody('records processed ' + a.TotalJobItems +

    'with '+ a.NumberOfErrors + ' failures.');

    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    Thanks

    Brahma