function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
oenoen 

Need help with Merge logic

Hi Everyone,

 

I am trying to Merge contacts in a do while loop base on Contact's FirstName,LastName and AccountID.

 

I got the code to work on Merging Contacts but for some reason the Do While loop is not looping through all the contacts that need to be merge. Below is the Apex code:

 

public class myContactMerger {

public myContactMerger(ApexPages.StandardController controller) {


}

public integer myii;
public integer myi;


public void doAdd() {

List<aggregateResult> results = new List<aggregateResult>();
do {
myii = [Select count() from Contact Where AccountId <>''];
results.clear();
results = [select count(id) mycount,min(id) mymasterid,Max(id) myslaveid,accountid,FirstName,LastName from Contact Where AccountId <> '' group by accountid,FirstName,LastName having count(id)>1 limit 50];
Id mymasterid;
Id myslaveid;
Contact MasterContact;
Contact SlaveContact;
Contact thismastercontact ;
Contact thissalvecontact;

for (AggregateResult ar : results) {

 


mymasterid = (Id)ar.get('mymasterid');
myslaveid = (Id)ar.get('myslaveid');

thismastercontact = new Contact(Id=String.valueOf(ar.get('mymasterid')));
thissalvecontact = new Contact(Id=String.valueOf(ar.get('myslaveid')));

try {
merge thismastercontact thissalvecontact;
} catch (DmlException e) {
// Process exception
System.debug('An unexpected error has occurred: ' + e.getMessage());
}


}
myi = [Select count() from Contact Where AccountId <>''];

} while (myii >myi);

 


}

}

 

Anyone has any suggestion why this is not working? Also appreciates it if someone can tell me if the code i am currently have is most effienct or it can be improve.

 

Thanks