+ Start a Discussion
srinivas pulipatisrinivas pulipati 

Hi I am write the below code my requirement is when i run batch, account phone number and contact phone number like same but again run the batch contact phone dose't change could u please tell me the mistake?

BatchApex Class:
global class ContactBatchApex implements DataBase.Batchable<Sobject>{
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('select id,phone,account.phone from contact');
    }
    global void execute(Database.BatchableContext bc,list<contact> scope){
        List<contact> con =new List<contact>();
        for(contact c: con){
            c.phone =c.account.phone;
            con.add(c);
        }
        update con;
    }
    global void finish(Database.BatchableContext bc){
        
    }
}

batch:

ContactBatchApex  b=new ContactBatchApex();
database.executebatch(b,1);
AdminBooster.comAdminBooster.com
Probable a mistake in this part of the code :
global void execute(Database.BatchableContext bc,list<contact> scope){
        List<contact> con =new List<contact>();
        for(contact c: con){
            c.phone =c.account.phone;
            con.add(c);
        }
        update con;
    }

Your "con" list is empty. You should remove the line "List<contact> con =new List<contact>();" and change your for() line into 
for(contact c: scope){
then remove the con.add(c) line, and update scope.

You could do this without code in real time through Process Builder too


 
Amit Chaudhary 8Amit Chaudhary 8
Please check below post for batch job. I hope that will help you.
http://blog.shivanathd.com/2013/01/how-to-write-batch-class-in.html
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

Please try below code.
global class ContactBatchApex implements DataBase.Batchable<Sobject>{
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('select id,phone,account.phone from contact');
    }
    global void execute(Database.BatchableContext bc,list<contact> scope){
        List<contact> con =new List<contact>();
        for(contact c: scope){
            c.phone =c.account.phone;
            con.add(c);
        }
        update con;
    }
    global void finish(Database.BatchableContext bc){
        
    }
}
Please let us know if this will help you

Thanks
Amit Chaudhary