I am trying to run the following query locator:

 Database.getQueryLocator('select ' + TrackingNumberString + ',Carrier_Status__c from ' 
                         + MainObjectString + ' where ECS__Shipped_Time__c = LAST_N_DAYS:' 
                         + DaysBackString + ' and Carrier_Status__c != ' + exclusion1);


TrackingNumberString = Tracking_Number_Field__c

MainObjectString = Main_Object__c

DaysBackString = 1

and exclusion1 = Delivered

The fields are correct, and I cannot simply insert 'Main_Object__c' into the query string because it is located from another query using a custom setting. Also it isn't really related to my question.

I am getting the following error:

12:20:07:059 FATAL_ERROR System.QueryException: Variable does not exist: Delivered

So my question is: How can I write the code so that 'and Carrier_Status__c' does not equal the string: Delivered?

Should I do something where I extract the string information from Carrier_Status__c then run it through a series of if statements to see if it equals exclusion1? Or is there some way to type it in a query so that Carrier_Status__c does not equal the string value of exclusion1?

Any help is appreciated. If you need more code to help, just ask please.

  • 1
    exclusion1 needs to be quoted in the dynamic soql; i.e. it must be generated as 'Delivered'
    – cropredy
    Dec 31, 2015 at 17:33

1 Answer 1


You need to wrap your value in single quotes. Replace exclusion1 with '\'' + String.escapeSingleQuotes(exclusion1) + '\''.

Not the answer you're looking for? Browse other questions tagged .