function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mikebr59mikebr59 

Problem with variable bind in SOQL query

I've spent the past hour trying to figure out what's wrong with this WHERE clause and am totally stuck:

 

WHERE employee__c = :UserInfo.getUserId()
and activity_date__c >= :xlStartDate
and activity_date__c <= :xlEndDate
and (invoiced__c = false or :includeInvoiced = true)

 

includeInvoiced is a public Boolean variable, and invoiced__c is a checkbox field on the object being queried. I keep getting this error: "Compile Error: unexpected token: ':' at line 53 column 44 ".

 

The token in question is the colon before includeInvoiced. What's going on? If I remove "or :includeInvoiced = true" then it compiles. What am I doing wrong?!?!?

Best Answer chosen by Admin (Salesforce Developers) 
James LoghryJames Loghry

Mike, you can only bind values to columns associated with the SOQL query.

 

I'd recommend using dynamic SOQL for this use case.

 

Something like String query = 'Select fields from Object Where .... ' + (!includeInvoiced ? ' and invoiced__c = false' : '');

List<sObject> myObjs = Database.execute(query); 

 

Also note that your value bindings for employee__c and activity_date__c will still work in the dynamic query string.

 

Hope that helps some.

All Answers

James LoghryJames Loghry

Mike, you can only bind values to columns associated with the SOQL query.

 

I'd recommend using dynamic SOQL for this use case.

 

Something like String query = 'Select fields from Object Where .... ' + (!includeInvoiced ? ' and invoiced__c = false' : '');

List<sObject> myObjs = Database.execute(query); 

 

Also note that your value bindings for employee__c and activity_date__c will still work in the dynamic query string.

 

Hope that helps some.

This was selected as the best answer
mikebr59mikebr59

That helps a lot, thanks. I more or less discovered the same thing while I was working on another query and was pondering the best approach.

 

Thanks for the quick reply!