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
Kevin DesaiKevin Desai 

ID after getting inserted via a List

Hello,

Is there any way to get the ID of all the records that are getting inserted or updated via a list?
For example, To get the ID of a single record, you would write :

Account a = new Account();
a.Name = 'Test Account';
insert a;
system.debug('----Inserted Account ID ----'+a.Id);

I want the same while using list. 
Nilesh Jagtap (NJ)Nilesh Jagtap (NJ)
Hi Kevin you can use database.insert method to insert your lists as :
Account[] accts = new List<Account>{
    new Account(Name='Account1'),
    new Account()};
Database.SaveResult[] srList = Database.insert(accts, 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());
        }
    }
}


If this helps, mark this as best answer

Thanks,
N.J
Ramu_SFDCRamu_SFDC
You might have to use database classes and saveresult class. see if the below article helps

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_database_saveresult.htm
Kevin DesaiKevin Desai
Thanks much!