+ Start a Discussion
Stuart WernerStuart Werner 

can I use Apex Batch to copy data from one object to another?

We have a need to copy the data from the LoginHistory object to a custon loginHistory object on a regular basis. This is a large organization with a lot of activity. I know we can do this manually with the dataloader. 

Can an Apex Batch job support this type of activity?

Can anyone point us to some sampple apex code that copies data from one object to another?

James LoghryJames Loghry

You sure can.  You will want 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: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_scheduler.htm

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) {}

prabhat jhaprabhat jha
@james can you please tell me ,if i have to map multiple fields ,how to incorporate that,after line number 14 in the above code,i am getting errors for various fields ,one another field in your code will suffice my requirement