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
Michael MMichael M 

Workaround error when merging person accounts: "name" is not writeable

I'm trying to merge 2 person accounts. However I am getting an error, stating that the "name" field is not writeable. I know that I have permissions, but it seems that on person accounts this field is not writeable when merging. How can I edit my code to work around that issue?  

List<AggregateResult> MyMergeList = [SELECT Count(ID) , name, patient_dob__c
FROM Account 
WHERE IsPersonAccount=TRUE
and name like '%James Dean%'
GROUP BY Name, Patient_DOB__c
HAVING Count(ID) > 1 
ORDER BY Count(ID) desc
LIMIT 2000];


For (AggregateResult Agm : MyMergeList){
   //** Tweak the string parameters to match your preference (confidence)....
   //String accName = '%'+ string.valueOf(agm.get('Name')) + '%';
   String accName = string.valueOf(agm.get('Name'));
   Account ToAccount = [Select id, name from account where name like :accName limit 1];
   Account FromAccount = [Select id, name from account where Id != :ToAccount.Id and name like :accName Limit 1];

   system.debug(LoggingLevel.Info,'*** FromAccount: ' + FromAccount.Name+' ('+FromAccount.Id+')');
   system.debug(LoggingLevel.Info,'*** ToAccount  : ' + ToAccount.Name+' ('+ToAccount.Id+')');
   database.merge(ToAccount , FromAccount, false );
}
 
Best Answer chosen by Michael M
Michael MMichael M
I was able to make it work but using firstname instead of name in the 2 account queries:

 //** Tweak your account selection ... aka where clause ..
List<AggregateResult> MyMergeList = [SELECT Count(ID) , name, patient_dob__c
FROM Account 
WHERE IsPersonAccount=TRUE
and name like '%James Dean%'
GROUP BY Name, Patient_DOB__c
HAVING Count(ID) > 1 
ORDER BY Count(ID) desc
LIMIT 2000];


For (AggregateResult Agm : MyMergeList){
   //** Tweak the string parameters to match your preference (confidence)....
   //String accName = '%'+ string.valueOf(agm.get('Name')) + '%';
   String accName = string.valueOf(agm.get('Name'));
   Account ToAccount = [Select id, firstname, lastname from account where name like :accName limit 1];
   Account FromAccount = [Select id, firstname, lastname from account where Id != :ToAccount.Id and name like :accName Limit 1];

   system.debug(LoggingLevel.Info,'*** FromAccount: ' + FromAccount.firstname+' ('+FromAccount.Id+')');
   system.debug(LoggingLevel.Info,'*** ToAccount  : ' + ToAccount.firstname+' ('+ToAccount.Id+')');
   database.merge(ToAccount , FromAccount );
}