Notes
public class FindAccountAndMerge {
public static void mergeAccountByNameAndPhone(String accountName, String phone) {
try {
// Fetch the list of accounts with the given name and phone
List<Account> accList = [SELECT Id, Name, Phone FROM Account WHERE Name = :accountName AND Phone = :phone ORDER BY CreatedDate ASC];
System.debug('List of Accounts: ' + accList);
if (accList.size() > 1) {
// The first account in the list will be the master account
Account masterAccount = accList[0];
for (Integer i = 1; i < accList.size(); i++) {
Account duplicateAccount = accList[i];
try {
// Merge the duplicate account into the master account
Database.merge(masterAccount, duplicateAccount);
} catch (Exception e) {
System.debug('Failed to merge Account: ' + duplicateAccount.Id + ' due to: ' + e.getMessage());
}
}
} else {
System.debug('No duplicates found or only one account exists.');
}
} catch (Exception e) {
System.debug('Error in merging accounts: ' + e.getMessage());
}
}
}
Key Points
- Query Criteria: The query now filters accounts based on both
Name
and Phone
.
- Enhanced Debugging: Logs are added to track the list of accounts and any issues that occur during the merge process.
This code should now handle merging Account
records based on the Name
and Phone
fields effectively.