0

Im learning more about Batch Apex class and I find it pretty cool and helpful. When I remove the Where BillingSate='TX' everything works as expected. Yet when I use the Where condition I get the following error: First error: unexpected token: BillingState What does this error mean?

Things I considered: I have made sure the query works by using the Query Editor. The Contacts don't have any values in their MailingState fields. I have access to all fields as a system admin. I get the same error even after using variable binding.

/*String state = 'TX';
        return Database.getQueryLocator(
        'Select id,BillingStreet,BillingCity,BillingState,'+
        'BillingPostalCode,(Select id,MailingStreet,MailingCity,'+
        'MailingState,MailingPostalCode from Contacts) From Account'+
        'where BillingState=:'+state
        );  This doesn't work either */
global class UpdateContactAddInfo implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        return Database.getQueryLocator(
        'Select id,BillingStreet,BillingCity,BillingState,'+
        'BillingPostalCode,(Select id,MailingStreet,MailingCity,'+
        'MailingState,MailingPostalCode from Contacts) From Account'+
        'where BillingState=\'TX\''
        );
    }
    global void execute(Database.BatchableContext bc, List<Account> scope)
    {
        List<Contact> contacts=new List<Contact>();
        for(Account a:scope)
        {
            for(Contact c:a.contacts)
            {
                c.MailingStreet = a.BillingStreet;
                c.MailingCity = a.BillingCity;
                c.MailingState = a.BillingState;
                c.MailingPostalCode = a.BillingPostalCode;
                contacts.add(c);
                  
            }
        }
      update contacts;
    } 
    global void finish(database.BatchableContext bc)
    {
        
    }

}   

1 Answer 1

1

You're missing a space after FROM Account, which is a constant pitfall when building queries through string concatenation.

This would be easier to see if you did not use Dynamic SOQL here, since you do not need it. Just write a static SOQL query:

return Database.getQueryLocator([
    SELECT Id, BillingStreet, BillingCity, BillingState,
           BillingPostalCode,
           (SELECT Id, MailingStreet, MailingCity, MailingState, MailingPostalCode 
            FROM Contacts)
    FROM Account
    WHERE BillingState='TX'
]);
1
  • Thank you! that solved it. I will definitely remember this.
    – Nameishi
    Nov 18, 2020 at 23:40

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.