function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
venkyyyvenkyyy 

Want to give account name prefix as Mr if Gender is Male(M) or Ms if Gender is Female Using batch apex

Hi, 
The code was not working that i have created to update account name.

If the account Gender is 'M' then i want to update account name with the prefix of 'Mr.'
If the account Gender is 'F' then i want to update account name with the prefix of 'Ms'.

Following code i did, but it does'nt works.
-----------------------------------------------------
global class AcPrefixMaleFemale implements database.batchable<sObject>{
    
    global database.querylocator start(database.batchablecontext bc){
        string sql = 'select id,name,Gender__c from account';
        return database.getquerylocator(sql);
    }
    
    global void execute(database.batchablecontext bc, list<account> scope){
        list<account> lst = new list<account>();
        for(account a:lst){
            if(a.Gender__c == 'M'){
                a.Name = 'Mr.'+a.Name;
                lst.add(a);
            }
            if(a.Gender__c == 'F'){
                a.Name = 'Ms.'+a.Name;
                lst.add(a);
            }
        }
        update lst;
    }
    
    global void finish(database.batchablecontext bc){}
    
}
 
Best Answer chosen by venkyyy
ManojjenaManojjena
Hi venkat,

You need to change the below line 
 for(account a:scope )

Instead of lst you need to scope .As your lst is blank list you may not get any out put .

Try and let me know if it helps .




 

All Answers

sandeep sankhlasandeep sankhla
Hi,

You should iterate over scope instead of new blank list...
 
global class AcPrefixMaleFemale implements database.batchable<sObject>{
    
    global database.querylocator start(database.batchablecontext bc){
        string sql = 'select id,name,Gender__c from account';
        return database.getquerylocator(sql);
    }
    
    global void execute(database.batchablecontext bc, list<account> scope){
        list<account> lst = new list<account>();
        for(account a:scope){
            if(a.Gender__c == 'M'){
                a.Name = 'Mr.'+a.Name;
                lst.add(a);
            }
            if(a.Gender__c == 'F'){
                a.Name = 'Ms.'+a.Name;
                lst.add(a);
            }
        }
        update lst;
    }

thanks,
Sandeep
ManojjenaManojjena
Hi venkat,

You need to change the below line 
 for(account a:scope )

Instead of lst you need to scope .As your lst is blank list you may not get any out put .

Try and let me know if it helps .




 
This was selected as the best answer
venkyyyvenkyyy
Yes sandeep and manoj, 
it is working fine. 

Thank you guys.