3

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 ??

1 Answer 1

5

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.

4
  • Can I be sure about the list order? The operations result list has always the same order than object list? Commented Sep 5, 2013 at 13:50
  • Yes, the order is guaranteed in the documentation.
    – sfdcfox
    Commented Sep 5, 2013 at 13:58
  • I've updated the answer with the relevant information from the documentation.
    – sfdcfox
    Commented Sep 5, 2013 at 14:01
  • goes like a charm :) Commented Sep 5, 2013 at 14:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .