Simple Batch Apex example in Salesforce

Apex Code:

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 = a.Name + 'Updated';            
         }
         update scope;
    }   
    
    global void finish(Database.BatchableContext BC) {
    }
}

Run the batch apex for testing it in Developer Console.


Output:


Cheers!!!

10 comments:

  1. Hi
    Could you please suggest if want to revert the name as previous.then what I do?
    regards
    Sumit Shukla

    ReplyDelete
    Replies
    1. Create another batch with below code

      for(Account a : scope)
      {
      a.Name = a.Name.remove('Updated');
      }
      update scope;

      Cheers!!!

      Delete
  2. Thank you very much. Its working fine.

    ReplyDelete
  3. Thank you so much for your example on batch apex.....
    i am fresher, i need to know more about batch apex can pls give me some more links like this

    ReplyDelete
  4. global class AccountBatch_AC implements Database.Batchable{
    global Database.QueryLocator start(Database.BatchableContext bc){
    String strQuery='SELECT id,name FROM Account';
    return Database.getQueryLocator(strQuery);
    }
    global void execute(Database.BatchableContext bc,List lstAccObj){
    for(Account accObj:lstAccObj){
    accObj.name='Mr'+accObj.name;
    lstAccObj.add(accObj);
    }
    update lstAccObj;
    }
    global void finish(Database.BatchableContext bc){}

    ReplyDelete
    Replies
    1. [11/6/2015, 1:17 PM] +91 81973 15768: error idi vastundiCannot modify a collection while it is being iterated.

      Delete
  5. can i call metadata in batchclass,i had used metadata to create customfields in custom object based on Standard object.I created a Apex class to create custom fields.

    ReplyDelete
    Replies
    1. Yes. You can do this. But check Salesforce documents for Apex Class version supported.

      Delete
  6. Hi Mahesh,


    try this




    global class AccountBatch_AC implements Database.Batchable{
    global Database.QueryLocator start(Database.BatchableContext bc){
    String strQuery='SELECT id,name FROM Account';
    return Database.getQueryLocator(strQuery);
    }
    global void execute(Database.BatchableContext bc,List lstAccObj){
    for(Account accObj:lstAccObj){
    accObj.name='Mr'+accObj.name;
    lstAccObj.add(accObj);
    }
    update lstAccObj;
    }
    global void finish(Database.BatchableContext bc){}

    ReplyDelete