Notifications
Clear all
Nov 17, 2021 10:28 am
How to merge two records into one in apex?
1 Reply
Nov 17, 2021 10:31 am
The merge statement merges up to three records of the same sObject type into one of the records, deleting the others, and re-parenting any related records. The first parameter represents the master record into which the other records are to be merged. The second parameter represents the one or two other records that should be merged and then deleted. You can pass these other records into the merge statement as a single sObject record or ID, or as a list of two sObject records or IDs.
The following example merges two accounts named 'Acme Inc.' and 'Acme' into a single record:
List ls = new List{new Account(name='Acme Inc.'),new Account(name='Acme')}; insert ls; Account masterAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme Inc.' LIMIT 1]; Account mergeAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1]; try { merge masterAcct mergeAcct; } catch (DmlException e) { // Process exception here }