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

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?

Answer

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
Source : Link , Question Author : metadaddy , Answer Author : metadaddy

Leave a Comment