I am trying to syc data email from contact to account for 20 million records.Here is the batch i have written to do that.when i run this batch i am getting an error "First error: Aggregate query has too many rows for direct assignment, use FOR loop".Moreover, I am not sure whether this code can handle 20 Million records.Your review and help is much appreciated.
global class EmailSycBatch implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(SELECT Name,Id,Primary_Email__c,(SELECT Email,Id,Primary_Indicator__c FROM Contacts where Primary_Indicator__c=true) FROM Account );
}
global void execute(Database.BatchableContext BC, List<SObject> scope) {
for(Account a : scope){
List<Contact> cc = a.getSObjects('Contacts'); //grab all the related contact records
if (cc != null) { //if there are related contact records
for (Contact con: cc) {
if(a.Primary_Email__c != con.Email)
a.Primary_Email__c = con.Email;
}
}
}
try
{
update scope;
}
catch(Exception ex)
{
throw new TriggerException('Error in batch UpdateAccountBatch on method Batchable execute with the following error message'+ex.getMessage() + 'Stack Trace = ' +ex.getStackTraceString() );
}
}
global void finish(Database.BatchableContext info) {
AsyncApexJob a = [SELECT CreatedBy.Email, CreatedBy.Name, CreatedDate, CompletedDate, Id, JobItemsProcessed, NumberOfErrors, Status, TotalJobItems FROM AsyncApexJob WHERE Id =: info.getJobId()];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'XXXXXXXX'};
mail.setToAddresses(toAddresses); //to
mail.setSubject('Apex batch_field_aggregation:'+a.Status);
mail.setPlainTextBody('The batch Apex job created by '+a.CreatedBy.Name+' ('+a.CreatedBy.Email+') processed '+a.TotalJobItems+' batches with '+a.NumberOfErrors+' failures. The process began at '+a.CreatedDate+' and finished at '+a.CompletedDate+'.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); //send
}
}