+ Start a Discussion
Hari nadh babu EluruHari nadh babu Eluru 

Update the records by using batch apex

Hi all,
By using batch apex, write an apex class to update the records of custom sobject as like gender is male then we can add Mr infront of the name and gender is female then we can add Miss infront of the name.
Please provide code to me. Thank you !
Best Answer chosen by Hari nadh babu Eluru
AnkaiahAnkaiah (Salesforce Developers) 
Hi Harinadh,

Please try with below code.
global class batchAccountNameUpdate implements Database.Batchable<sObject> {
 
    global Database.QueryLocator start( Database.BatchableContext BC ) {

//Replace the query as per your requirement
 
        String query = 'SELECT Id,Name,Gender__c FROM Account';
        return Database.getQueryLocator( query );
 
    }
   
    global void execute( Database.BatchableContext BC, List< Account > scope ) {
 
         for ( Account a : scope )
         {
             if(a.Gender__c=='Male'){
                 
                 a.Name = 'Mr'+ a.Name; 
                 
             }else if(a.Gender__c=='Female'){
                 
              a.Name = 'Mrs'+ a.Name;                  
             }
                       
         }
         update scope;
 
    }   
    
    global void finish( Database.BatchableContext BC ) {
        
    }
 
}

If this helps, please mark it as best answer.

Regards,
Ankaiah bandi

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi Harinadh,

Please try with below code.
global class batchAccountNameUpdate implements Database.Batchable<sObject> {
 
    global Database.QueryLocator start( Database.BatchableContext BC ) {

//Replace the query as per your requirement
 
        String query = 'SELECT Id,Name,Gender__c FROM Account';
        return Database.getQueryLocator( query );
 
    }
   
    global void execute( Database.BatchableContext BC, List< Account > scope ) {
 
         for ( Account a : scope )
         {
             if(a.Gender__c=='Male'){
                 
                 a.Name = 'Mr'+ a.Name; 
                 
             }else if(a.Gender__c=='Female'){
                 
              a.Name = 'Mrs'+ a.Name;                  
             }
                       
         }
         update scope;
 
    }   
    
    global void finish( Database.BatchableContext BC ) {
        
    }
 
}

If this helps, please mark it as best answer.

Regards,
Ankaiah bandi
This was selected as the best answer
Hari nadh babu EluruHari nadh babu Eluru
@Ankaiah Thank you ! for your Support.