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
rohan patel 30rohan patel 30 

Batch Apex- Owner Change

i need a batch apex code or something to update contact onwer as same as account owner. there is more than 50,000 records.
Best Answer chosen by rohan patel 30
AnkaiahAnkaiah (Salesforce Developers) 
Hi Rohan,

try with below code.
global class updateContactOwner implements Database.Batchable<Contact>{

   global Database.QueryLocator start(Database.BatchableContext BC){
     String query = 'Select id, ownerId,Account.OwnerId from Contact'; 
     return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<Contact> scope){
     List<Contact> conList = new List<Contact>();
     for(Contact con : scope){
       con.ownerID = con.Account.OwnerId;
       conList.add(con);
     }
     update conList;
    }

   global void finish(Database.BatchableContext BC){
   }
}

open annoumus window and run the below code.
updateContactOwner  batch = new updateContactOwner ();

Database.executebatch(batch,200);


If this helps, Please mark it as best answer.

Thanks!!

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi Rohan,

try with below code.
global class updateContactOwner implements Database.Batchable<Contact>{

   global Database.QueryLocator start(Database.BatchableContext BC){
     String query = 'Select id, ownerId,Account.OwnerId from Contact'; 
     return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<Contact> scope){
     List<Contact> conList = new List<Contact>();
     for(Contact con : scope){
       con.ownerID = con.Account.OwnerId;
       conList.add(con);
     }
     update conList;
    }

   global void finish(Database.BatchableContext BC){
   }
}

open annoumus window and run the below code.
updateContactOwner  batch = new updateContactOwner ();

Database.executebatch(batch,200);


If this helps, Please mark it as best answer.

Thanks!!
This was selected as the best answer
rohan patel 30rohan patel 30
hey Ankaiah, thanks a lot
it worked !!
rohan patel 30rohan patel 30

hey @ankaiah !!

can you help me with its test class??