Batch Class to rename Opportunity Name



global class batchNameChange implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc){
        Id recId = Schema.SObjectType.Opportunity.getRecordTypeInfosByDeveloperName().get('RecordTypeA').getRecordTypeId();
        system.debug('!!!!!recId!!!!!'+recId);
        return Database.getquerylocator([SELECT Id,Name,Account.Name
                                         FROM Opportunity WHERE RecordTypeId =: recId AND AccountId != NULL ]);
    }
    global void execute(Database.BatchableContext bc, List<Opportunity> records){
        system.debug('!!!!!Entered Execute!!!!!');
        List<Opportunity> finalOpp = new List<Opportunity>();
        for(Opportunity opp : records ) {
            //if(opp.Name.startsWith(opp.Account.Name))
            //*change criteria as per need*/
            if(opp.Name.contains('TEST')){
                finalOpp.add(opp);
            }
        }
        for(Opportunity opty: finalOpp) {
            system.debug('!!!!!opty!!!!!'+opty);
            system.debug('!!!!!optyName!!!!!'+opty.Name);
            system.debug('!!!!!accName!!!!!'+opty.Account.Name);
            opty.Name = opty.Account.Name + ':'+ opty.Name;
            system.debug('!!!!!opty.Name!!!!!'+opty.Name);
            //opty.Name = opty.Account.Name + ':'+ opty.Name.remove(opty.Account.Name);
            //op.Customer_Type__c = 'End User';
        }
        update finalOpp;
    }
    global void finish(Database.BatchableContext bc){
        
    }
}


Execute -

Open the Developer Console
Click Debug | Open Execute Anonymous Window
Execute the following code-

Database.executeBatch(new batchNameChange(), 200);
200 is batch size here


Output:
https://www.youtube.com/watch?v=sqVoSH-yMz0





Comments