I am trying to find duplicate accounts in the system and trying to merge them based on our filter criteria using apex. The issue is I am hitting the governor limit of 150 DML statements while doing this.
We will have to put the merge statement inside the loop as we need the parent and child as the parameters in the merge statement. I don't think we can bulkify Merge like other DML statements due to the above reason. I am not sure if there is any better way to do it and avoid hitting governor limits.
Any help in this regard would be greatly appreciated.
Code that I have tried is included below
global class LoyaltyAccountBatch implements Database.batchable<sObject>{
global Database.QueryLocator start(Database.batchableContext info){
String query;
query = ('SELECT Id FROM LoginHistory LIMIT 1');
return Database.getQueryLocator(query);
}
global void execute(Database.batchableContext info, List<LoginHistory> scope){
// Get those records based on the IDs
List<Account> templst1 = [SELECT Id,UniqID from account where createddate = LAST_N_DAYS:4 and UniqID <> ''];
system.debug('templist is '+templst1);
Set<String> insertedRecords = new Set<String>() ;
for (Account a : templst1) {
insertedRecords.add(a.UniqID);
}
List<Account> templst = [SELECT Id,UniqID from account where NewUniqID IN : insertedRecords
order by NewUniqID,UniqID asc];
// Process records
for(integer i=0;i+1<templst.size();i++)
{
if(templst[i].UniqID < templst[i+1].UniqID)
{
system.debug('ids are '+templst[i].UniqID+'-->'+templst[i+1].UniqID);
String str = '1'+templst[i].UniqID.substring(1,templst[i].UniqID.length());
String str1 = '1'+templst[i+1].UniqID.substring(1,templst[i+1].UniqID.length());
system.debug('str is'+str);
system.debug('str1 is'+str1);
if(str.equals(str1))
{
Merge templst[i+1] templst[i];
system.debug('value of i is'+i);
}
}
}
}
global void finish(Database.batchableContext info){
}
}
UniqueId__c
?