My anonymous de-dupe Account apex code runs successfully until it hits a DML limit on the merge execution. I do not want to reduce the size of my query. How do I implement this in batch apex so that it is aware of governor limits?
In particular, I want it to run in batches of appropriate size so that it can complete without giving me "too many DML statements".
// Assumption is accounts exist with dupe DunsNumber
List<Account> allMasters = [SELECT Id, DunsNumber FROM Account WHERE CreatedBy.LastName!='Smith' AND DunsNumber!=null];
List<Account> allPotentialDupes = [SELECT Id, DunsNumber FROM Account WHERE CreatedBy.LastName='Smith' AND DunsNumber!=null];
Map<Account, List<Account>> mastersDupes = new Map<Account, List<Account>>();
for (Account master : allMasters){
List<Account> mSDupes = new List<Account>();
for (Account dupe : allPotentialDupes){
if(master.DunsNumber == dupe.DunsNumber){ //dupe account identified so add it to the mastersDupes list
mSDupes.add(dupe);
}
}
mastersDupes.put(master, mSDupes);
}
for (Account masterAcct : mastersDupes.keySet()) { //for every key in mastersDupes
List<Account> keysDupeList = new List<Account>();
keysDupeList.addAll(mastersDupes.values()[0]);
for (Account mergeAcct : keysDupeList) //mergeAcct with the masterAcct
{
try {
merge masterAcct mergeAcct;
} catch (DmlException e) {
// Process exception
System.debug('An unexpected error has occurred: ' + e.getMessage());
}
}
}