User Story
As a Salesforce Administrator, I want to use a Batch Apex class to calculate the total number of accounts and store the result in a new account record.
The organization requires a solution to count the total number of Account
records in Salesforce and store this aggregate value in a newly created Account
record. The solution should process records efficiently, handling large datasets using Batch Apex, and ensure the total is accurately calculated and stored.
Code
Apex Class:
global class BatchAccountStateFul implements Database.Batchable<Sobject>, Database.Stateful {
public Decimal AR = 0;
global Database.QueryLocator start(Database.BatchableContext bc) {
String query = 'Select Id from Account';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc, List<SObject> scope) {
for(sobject s :scope) {
AR+=1;
}
}
global void finish(Database.BatchableContext bc) {
Account ac = new Account(Name='Batch Apex Stateful');
ac.AnnualRevenue = AR;
insert ac;
}
}
Apex Code (Execution):
BatchAccountStateFul objA = new BatchAccountStateFul();
Database.executeBatch(objA,10);