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 

Using batch apex want to delete the prefix of all account names i.e 'Mr.'

Hi all,
Help me out from this,
Here i came with a situation that i have created a batch apex to give 'Mr.' as a  prefix of every account name(the code was copyed bellow), and i executed this batch class using execute anonymous window using bellow 2 lines

batchAccountUpdate b1 = new batchAccountUpdate();
database.executeBatch(b1);

By mistake i have executed 3 times that anonymous block, so that the name of account  prefix 'Mr.' was updated 3 times for all accounts(like:   'Mr.Mr.Mr.Balu'), so now
I want to delete two Prefixes that 'Mr.'(Final Result wants to be like:   'Mr.Balu')

And the batch class is::
global class batchAccountUpdate implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id,Name FROM Account';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<Account> scope) {
         for(Account a : scope)
         {
             a.Name = 'Mr.'+ a.Name;            
         }
         update scope;
    }   
    
    global void finish(Database.BatchableContext BC) {
    }
}

Thanks in advance.
ManojjenaManojjena
HI Venky ,

try beow code in execute method . .
 
global void execute(Database.BatchableContext BC, List<Account> scope) {
         for(Account a : scope){
             a.Name =  a.Name.removeStart('Mr.');            
         }
         update scope;
    }

Let me know if it helps.

Thanks 
Manoj
venkyyyvenkyyy
Thanks Manoj,

I achived that what i expect, but for this acutally i have executed 2 times.
Before this the account name seems like:  Mr.Mr.Mr.Venky.
As per your suggestion i want to be run the job twise to get the result as : Mr.Venky.

Can we achive these output by using any if condition or anything else inseted of running two times the job???
ManojjenaManojjena
Hi Venky ,

You can modify the code as belwo to get Mr.Venky and execute once .
 
a.Name =  a.Name.removeStart('Mr.Mr.');

Let me know if it helps .

Thanks 
Manoj
venkyyyvenkyyy
Yes Manoj, 
Done.

Thanq once again.