+ Start a Discussion
Soubhagya Ranjan 2Soubhagya Ranjan 2 

batch apex to insert one object record to other object record


I am having 2 custom objects as student and studentcopy .

how to move records of student into student copy through batch apex . 

please provide me the code .

NagendraNagendra (Salesforce Developers) 
Hi Soubhagya,

Please check with below example which copies data from login history object to custom login history object.

You have to create a batch job with a scope of records from LoginHistory in the start method of your batch job.  The trick here potentially is checking for duplicate records, e.g. LoginHistory records that may or may not already exist in the LoginHistory custom object.  

Next, your execute method would create a new list of custom LoginHistory records and then insert them.  Note that the max batch size is 200 records, so that means your batch job will run in "chunks" of 200 records at a time, but for simply copying from one object to another, you should have no problem with that.

To run the batch job on a regular basis, you'll want to call it from a Schedulable class.  See here for more info on that: Below is an example of what your batch job may look like:
global class CopyLoginHistory implements Database.Batchable<LoginHistory> {

    global CopyLoginHistory(){}

    global List<LoginHistory> start(Database.BatchableContext BC) {
    	return [Select <fields> From LoginHistory Where //condition to prevent dupe records.. may be by time frame?];

    global void execute(Database.BatchableContext BC, List<LoginHistory> scope) {
       List<LoginHistory__c> lhList = new List<LoginHistory__c>();
       for(LoginHistory lh : scope){
               new LoginHistory__c(
       insert lhList;

    global void finish(Database.BatchableContext BC) {}
For more information check with below link. Please mark this as solved if the information helps.

Best Regards,