How to maintain variable value inside the Salesforce Batch Apex class?

How to maintain variable value inside the Salesforce Batch Apex class?

To maintain variable value inside the Salesforce Batch class, Database.Stateful can be used.

Sample Class:

global class Class_Name implements Database.Batchable<sobject>, Database.Stateful {
    
    Integer i = 0;
    
    global Database.QueryLocator start( Database.BatchableContext bc ) {
        
        return Database.getQueryLocator(
            'SELECT Id, Name FROM Account'
        );
        
    }
    
    global void execute( 
        Database.BatchableContext bc, 
        List < Account > listAccounts 
    ) {
        
        for ( Account objAccount : listAccounts ) {
            
            i += 1;
            
        }
        
    }
    
    global void finish( Database.BatchableContext bc ){
    }
    
}

here i value will be maintained even though execute method is called several times.

Maintain variable value inside the ...
Maintain variable value inside the Salesforce Batch Apex class

Leave a Reply