I am newbie in Apex, but I am trying to write some code. The purpose was simple: I have PricebookEntry object on Salesforce, and 2 lookup fields:

  • Pricebook2Id
  • Price_Book_2__c I want to fill Price_Book_2__c with the same value as Pricebook2Id on each record.

When I opened and run batch in Anonymouse Window I get error: Line: 3, Column: 25 Variable does not exist: Pricebook2Id

Here is the Apex class:

global class UpdatePriceBookCustomField implements Database.batchable<sObject>{
    global final String query;
    global Database.QueryLocator start (Database.BatchableContext BC) {
        return Database.getQueryLocator(query);}
    global void execute(Database.BatchableContext BC,List<sObject> scope){
        List<PricebookEntry>pbeToUpdate = new List<PricebookEntry>();
    for (sObject s : scope){PricebookEntry a = (PricebookEntry)s;
    update pbeToUpdate;
    global void finish(Database.BatchableContext BC) {

Here is the batch:

UpdatePriceBookCustomField PBE = new UpdatePriceBookCustomField();
PBE.query='Select Id, Pricebook2Id, Price_Book_2__c from PricebookEntry';
ID batchprocessid = Database.executeBatch(PBE);

Anyone has any idea why it don't want to run? I don't know why Apex is not seeing the Pricebook2Id...

1 Answer 1


Fails because there aren't any such properties in your class. Further the final modifier will prevent you from assigning the query value. global is not advised for most cases, you should use public instead. You don't need the dynamic query, you're querying too many fields, you are needlessly checking for null values (you can filter those out by way of the query), and you don't need to copy values from one list to another to update records. Taking all this into account, your code can simply read as:

public class UpdatePriceBookCustomField implements Database.batchable<sObject>{
    public Database.QueryLocator start (Database.BatchableContext BC) {
        return Database.getQueryLocator([
            SELECT Pricebook2Id FROM PricebookEntry WHERE Price_Book_2__c = null
    public void execute(Database.BatchableContext BC, PricebookEntry[] scope){
        for(PricebookEntry entry: scope) {
            entry.Price_Book_2__c = entry.PriceBook2Id;
        update scope;
    public void finish(Database.BatchableContext BC) {

Which you can then just call normally:

Database.executeBatch(new UpdatePriceBookCustomField());
  • Hi! :) Thank you so much for your help and tips! It resolve my problem! I saved this post, and analyzed your comment, and now I know what mistakes I made. Based on that I will write more examples to learn :)
    – ApexNewbie
    Jun 22 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.