Requirement:
Write a batch to merge and remove the duplication records.
For ex: 2 existing Accounts(Organizations) having same EIN and same Email, then merge and delete one record .
- If Acc1 is having Name=Acc1,EIN = 01-000040 and email [email protected], Phone = null
- If Acc2 is having Name=Acc2,EIN = 01-000040 and email [email protected], Phone = 0471-2465046
- then copy the phone number of Acc2 to Acc1 and copy the Name = Acc2 to Acc1 and then delete the Acc1 record
Code I have tried:
Global class deDuplicateRecords implements Database.Batchable<sObject>,Database.Stateful{
global Set<String> ein;
global Set<String> n;
global Set<String>u;
global Set<String>p;
global Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocator([Select Name, EIN_c, Website, Phone from Account WHERE EIN_c != Null]);
}
global void execute(Database.BatchableContext bc, List<Account>acc){
List<Account> accToBeDeleted = new List<Account>();
Map<String, Account> accountMap = new Map<String,Account>();
for(Account a:acc){
if(!Accountmap.containsKey(a.EIN__c)){
accoutMap.put(a.EIN__c, a);
}else{
Account existingAcc = accoutMap.get(a.EIN__c);
existingAcc.Website = a.Website;
existingAcc.Phone = a.Phone;
existingAcc.Name = a.Name;
accoutMap.put(a.EIN__c, existingAcc);
accToBeDeleted.add(a);
}
}
update accoutMap.values();
delete accToBeDeleted;
}
global void finish(Database.BatchableContext bc){
}
}
After running the batch using the anonymous code, the duplicate records are not getting deleted. As according to my requirement, if two records have same EIN and same website then and different EIN then the one with the phone number should exist and other should get deleted.
But After runninng the batch, the names of the records with same EIN are becoming the same but the duplicate isn't deleted. Also the phone numbers are becoming blank.
How do I fix this?
FindDuplicates
class to match new records against existing.