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
kiran punurukiran punuru 

How to get the failed to update record ids

Hi ,
I Have list of 10 accounts which i need to update out of that 10 records 5 records get updated and 5 records get failed to update due to validation rules ,Is there a way to get the failed record ids .any ideas ??

Thanks 
Kiran
Nayana KNayana K
// replace lstAccountToUpdate with list of accounts to be updated.
Database.SaveResult[] srList = Database.update(lstAccountToUpdate, false);

// Iterate through each returned result

for(Integer i=0; i<srList.size(); i++) 
{
	sr = srList[i];
    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 was unsuccessful, so get the ID of the record that was processed
        System.debug('Error Account ID: ' + lstAccountToUpdate[i].Id);
        // 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());
        }
    }
}

 
Abu HashimAbu Hashim
As Nayana said, u should Database.Update and use the return type Database.SaveResult and iterate through failed records...!!
Tad Aalgaard 3Tad Aalgaard 3

One edit to the code provided by Nayana.

Add Database.SaveResult to beginning of the followng line.

sr = srList[i];
 
Database.SaveResult sr = srList[i];
 

 

Ashish BandewarAshish Bandewar
Hello ,
Please check the reference solution:


public virtual class MyClass{
public static void myMethod(){    

    List<Opportunity> oppList = new List<Opportunity>();
    
    Opportunity opp1 = new Opportunity();
    opp1.Name = 'Mithun';
    opp1.Id = '0065g00000UtO5bAAF';
    opp1.StageName = 'Prospecting';
    opp1.CloseDate = date.today();
       oppList.add(opp1);
    
    Opportunity opp2 = new Opportunity();
    opp2.Name = null;
    opp2.Id = '0065g00000UtO5cAAF';
    opp2.StageName = 'Qualification';
    opp2.CloseDate = date.today();
    oppList.add(opp2);
    
   List<Database.SaveResult> srList = Database.update(oppList,false);
   
    for(Database.SaveResult sr : srList){
        if(sr.isSuccess()){
            system.debug('Successfully updated id is :'+sr.getId());
        }else{
            system.debug('Failed to update id is :'+sr.getId());
        }
    }
    }
  }