+ Start a Discussion
SFDC@ErrorSFDC@Error 

Insert Multiple object value in one object

Hi All

How can i copy/insert record form multiple object to one custom object uisng batch process.I have created batch class but its bring data from one object to another object ..
global class CopyContact implements Database.Batchable<Contact> {

    global CopyContact (){}

    global List<Contact> start(Database.BatchableContext BC) {
        return [Select Name,Email,Phone,MobilePhone From Contact];
    }
    
    

    global void execute(Database.BatchableContext BC, List<Contact> scope) {
       List<Master_Data__c> lhList = new List<Master_Data__c>();
       for(Contact lh : scope){
           lhList.add(
               new Master_Data__c(
                  Name=lh.Name,Email__c=lh.Email,Phone__c=lh.Phone,Mobile__c=lh.MobilePhone
               )
           );
       }
       insert lhList;
    }

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

 
sravan velamasravan velama
Hi,
Try to use generic type like List<sObject> sVal = new List<sObject>();

For example: 

List<Account> accountList = new List<Account>();
List<Contact> contactList = new List<Contact>();
for (Integer i = 0; i < 10; i++) {
accountList.add(new Account(Name = 'Boards Test Accout ' + i));
contactList.add(new Contact( FirstName = 'Boards ' + i, LastName = 'Test Contact' ));
}
List<sObject> objects = new List<sObject>();
objects.addAll((List<sObject>)(accountList));
objects.addAll((List<sObject>)(contactList));
insert objects;

You just have to typecast the list into a list of generic sObjects before adding them

Thanks,
Sravan Velama
Harshit Garg 6Harshit Garg 6
Hi,
 
global class CopyContact implements Database.Batchable<sObject> {

    global CopyContact (){}

    global Database.QueryLocator start(Database.BatchableContext BC) {
    
   Contact c= 'Select Name,Email,Phone,MobilePhone From Contact';
        return databse.getQueryLocater(c);
    }
    
    

    global void execute(Database.BatchableContext BC, List<Contact> scope) {
       List<Master_Data__c> lhList = new List<Master_Data__c>();
       for(Contact lh : scope){
           lhList.add(
               new Master_Data__c(
                  Name=lh.Name,Email__c=lh.Email,Phone__c=lh.Phone,Mobile__c=lh.MobilePhone
               )
           );
       }
       insert lhList;
    }

    global void finish(Database.BatchableContext BC) {}
}
Please use that above code.Through sobject you can do the same.

if that helps you.Please choose my answer as the best answer.

Thanks,
Harshit garg