soql = 'select A__c,EmplId__c, B__c,Date__c from Transaction__c Where Transaction__c.name!=null';

    if (!branch.equals(''))
    system.debug('test br1');
      soql += ' and A__c LIKE \''+String.escapeSingleQuotes(branch)+'%\'';

    if (!ordernum.equals(''))
      soql += ' and B__c LIKE \''+String.escapeSingleQuotes(ordernum)+'%\'';
    if (!emplid.equals(''))
      soql += ' and EmplId__c LIKE \''+String.escapeSingleQuotes(emplid)+'%\'';
    if (!paybillcode.equals(''))
      soql += ' and PB_Code__c  LIKE \''+String.escapeSingleQuotes(paybillcode)+'%\'';  
    if (!wkenddate.equals(''))

    soql += ' and Date__c = wkenddate';  

I am getting an error when binding Date. can someone tell me what is the correct syntax?


If you are referencing an Apex variable in a SOQL statement, remember to prefix the variable name with :.

Try switching

 soql += ' and Date__c = wkenddate';  


 soql += ' and Date__c = :wkenddate';  

Two ways to accomplish this:

Binding Statement

soql += ' and Date__c = :wkenddate'; // Include the ':'

Note: DOES NOT WORK with expressions, such as Map.keySet(), array[index], etc. Only simple primitives. You can use sets and lists, however, provided you mean to use the entire list.


soql += ' and Date__c = '+DateTime.newInstance(wkenddate, Time.newInstance(0, 0, 0, 0)).format('yyyy-dd-MM'); // Make sure it's normal SOQL formatted.
  • 4
    I have to protest that the :var format doesn't work with complex types. It absolutely does, but does not evaluate expressions. See salesforce.stackexchange.com/a/3527/60 – ca_peterson Dec 19 '13 at 20:52
  • 2
    I usually add UTC to the DateTime too: String myStart = dateTimeVar.format('yyyy-MM-dd')+'T00:00:01.000Z'; – Sergej Utko Dec 19 '13 at 21:03
  • @ca_peterson That's really more of what I meant. You can bind to myArray, but not myArray[0], or myMap.keySet(). Anything "complex." I'll clarify with your verbiage, as I like that better anyways. We are talking about the same thing, though. – sfdcfox Dec 19 '13 at 21:15
  • 1
    @mast0r That's correct for Date/Time fields, but the time part is implied for simple date fields and so not strictly necessary. – sfdcfox Dec 19 '13 at 21:17

Just bind using the regular syntax:

List<Transaction__c> = [select A__c, EmplId__c, B__c, Date__c from Transaction__c
                        where Date__c = :wkenddate];

The only snag with this is that the variable used for the binding must be local to the method's scope, so if wkenddate is a class member you'll want to do something like this:

Date theDate = wkenddate;
List<Transaction__c> = [select A__c, EmplId__c, B__c, Date__c from Transaction__c
                        where Date__c = :theDate];

Your Answer

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