2

Here's the requirement:

Rolls up the number of cases created within the last 30 days to the Account.

global class ZW_BatchCaseNumberRollup implements      Database.Batchable<sObject>,Database.Stateful{
 //Rolls up the number of cases created within the last 30 days to the Account
//Account field: Number_of_Cases__c

//Query: select Account.Id from Case where createddate=Last_n_days:30;
global final String query;
public Map<String,integer> CaseCount=new Map<String,integer>();
global ZW_BatchCaseNumberRollup(String q){
    query=q;
}

global Database.QueryLocator start(Database.BatchableContext BC)
{        
    return Database.getQueryLocator(query);        
}
global void execute(Database.BatchableContext BC, List<Case> scope)
{ 

    Integer num=0;
    For(Case c : scope)
    {
        String key=c.Account.Id;
        if(CaseCount.containsKey(key))
        {
            num=CaseCount.get(key)+1;
            CaseCount.put(key, num);
        }
        else
        {
            CaseCount.put(key, 1);
        }
    }
}
global void finish(Database.BatchableContext BC)
{
    List<Account> accountsWithCases=[select Id,Number_of_Cases__c from Account where Id in:CaseCount.keySet()];
    For(Account acct: accountsWithCases)
    {
        acct.Number_of_Cases__c=CaseCount.get(acct.Id);
    }
    update accountsWithCases;
}

}

My problem:

  1. If I have a million Accounts, this class can not be used.

Question:

  1. Can I change my query to an aggregate query?
  2. How can I resolve my problem?
  • Do you need this value as a field on the Account? Why not just link to a report? – Nick Cook Mar 11 '15 at 1:22
  • I was assigned this task. My batch apex can handle millions of cases but I don't think this can be used when these cases are associated with millions of Accounts. – sfdcnoob Mar 11 '15 at 1:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.