Find your content:

Search form

You are here

Is there a way to make the insert not fail if one record fails?

 
Share

I am inserting multiple records using Apex DML; e.g.

List<Account> accounts = new List<Account>();

// Populate the accounts list

insert accounts;

If there is any kind of error inserting any of the records, the insert fails for the entire batch. Is there a way to make the insert not fail if one record fails?


Attribution to: metadaddy

Possible Suggestion/Solution #1

Use a DML database method with a value of false for the optional opt_allOrNone parameter - i.e.

Database.SaveResult[] result = Database.Insert(accounts, false);

From the docs,

Use DML database methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the operation. When using this form, you can write code that never throws DML exception errors. Instead, your code can use the appropriate results array to judge success or failure. Note that DML database methods also include a syntax that supports thrown exceptions, similar to DML statements.


Attribution to: metadaddy
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/1730

My Block Status

My Block Content