[SalesForce] Get Error record on bulk upsert

I'm upserting a list of SObjects using Database.upsert and I need to know which records are not inserted.

This is an example:

  Account[] accts = new List<Account>{
        new Account(Name='Account1'),
        new Account(Name='Accoun2')};
    Database.upsertResult[] srList = Database.insert(accts, false);

    // Iterate through each returned result
    for (Database.upsertResult 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());
            }
        }
    }

Is there any way to get the record that caused the error from Database.upsertResult ??

Best Answer

Change your loop from for-each to indexed:

for(Integer idx = 0; idx < srList.size(); idx++) {
    if(srList[idx].isSuccess()) {
        ...
    } else {
        ...
    }
}

srList[idx] will correspond to accts[idx].

This is guaranteed in the documentation:

An array of Database.UpsertResult objects is returned with the upsert database method. Each element in the UpsertResult array corresponds to the sObject array passed as the sObject[] parameter in the upsert Database method; that is, the first element in the UpsertResult array matches the first element passed in the sObject array, the second element corresponds with the second element, and so on. If only one sObject is passed in, the UpsertResults array contains a single element.

Related Topic