get ids or names of...
 
Notifications
Clear all

[Solved] get ids or names of a list of failed DML insert records

2 Posts
1 Users
0 Likes
366 Views
Posts: 205
 CWL
Admin
Issue starter
(@cwl)
Member
Joined: 11 years ago

How to get a list of ids or any other field for those failed records in a bulk dml operation?

Issue Tags
dml
1 Reply
Posts: 205
 CWL
Admin
Issue starter
(@cwl)
Member
Joined: 11 years ago
// This is one way. This won't give you id's or any other fields, but just the field that caused the exception:

List srList = Database.insert(recsToInsert, false);
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, get the ID of the record that was processed
        System.debug('Successfully inserted. ID: ' + sr.getId());
    } else {
        // Operation failed, get all errors
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Fields that affected this error: ' + err.getFields());
        }
    }
}

// Another method. This will give you the id's or any other field you need:

List srList = Database.insert(recsToInsert, false);
for(Integer i=0;i<srList.size();i++){
    if (srList.get(i).isSuccess()){
        srList.get(i).getId();

    }else if (!srList.get(i).isSuccess()){
        // DML operation failed
        Database.Error error = srList.get(i).getErrors().get(0);
        String failedDML = error.getMessage();
        recsToInsert.get(i);//failed record from the list
        system.debug('Failed Id: '+recsToInsert.get(i).Your_field__c);
    }
}

// Also check out - handle errors in salesforce batch apex:  https://www.forcetalks.com/salesforce-topic/how-to-handle-error-records-in-salesforce-batch-apex/ 
Reply
Share: