2

I am using below query in a batch class

Query='Select Id FROM Contact WHERE SyncToMarketo__c  = true ' 
            + ' AND LastModifiedDate >= :date.today().addDays(-1) ';

and get an error in logs unexpected token: ( but the same works good in the anonymous window. Can anyone please suggest?

5

In dynamic SOQL (where the SOQL is a string) dotted expressions are not supported for bind variables (that follow the :).

Best approach is to use static SOQL instead and that way you also get more syntax checking done for you. So:

Contact[] contacts = [
        SELECT Id
        FROM Contact
        WHERE SyncToMarketo__c = true
        AND LastModifiedDate >= :Date.today().addDays(-1)
        ];

If you have a reason to use dynamic SOQL, then this should work providing the query is executed where d is still in scope:

Date d = Date.today().addDays(-1)
String q = ''
        + ' SELECT Id'
        + ' FROM Contact'
        + ' WHERE SyncToMarketo__c = true' 
        + ' AND LastModifiedDate >= :d';
...
Contact[] contacts = (Contact[]) Database.query(q);
  • Thank you so much for responding but is there any other way to write the same in a dynamic query? – gs650x Jan 7 at 12:27
  • @gs650x See last bit of code I just added. – Keith C Jan 7 at 12:29
2

Posted query will not work in anonymous block as well. You could try something like

Date dt = date.today().addDays(-1);
string Query='Select Id FROM Contact WHERE SyncToMarketo__c = true ' 
            + ' AND LastModifiedDate >= :dt';
Database.query(Query);

For efficiency you can try with YESTERDAY

string Query = 'SELECT Id FROM Contact WHERE SyncToMarketo__c = true AND LastModifiedDate >= YESTERDAY';

More on Date Literals here.

  • 1
    Yeah Date Literal makes way more sense for this use case. – Adrian Larson Jan 7 at 18:36

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.