0

I want assign a date value into a WHERE clause of query This is my date

Date myDate = System.Today().AddDays(Integer.valueOf(Deal_Expiration_Batch_Settings__c.getInstance().Expire_Notification_Prior_Days__c));

And this is my WHERE clause

 String strQuery = ' SELECT Id
            + ' FROM bDeal__c WHERE End_Date__c =:' + myDate)'; 

Here myDate is retrun the value as 2018-06-01 00:00:00 But End_Date__c in the query is returning as 2018-06-01

So I am getting an error System.QueryException: unexpected token: '2018-06-01'

How to resolve this. Please anyone help me.

I have tried to format the date using myDate.format() method. But it is returning the values as string. I want a Date type value.

2 Answers 2

3

you don't need ' symbol to enclose myDate variable.

Date myDate = System.Today().AddDays(Integer.valueOf(Deal_Expiration_Batch_Settings__c.getInstance().Expire_Notification_Prior_Days__c));
String strQuery = 'SELECT Id FROM bDeal__c WHERE End_Date__c = :myDate';

and in this case dynamic soql variable binding is used.

0
2

Apex supports the binding of data into static SOQL (via the : character) meaning in general you do not need to concatenate strings to create queries.

So in your case:

Date myDate = ...;

bDeal__c[] deals = [SELECT Id FROM bDeal__c WHERE End_Date__c :myDate];

Static SOQL has the advantage that it is syntax checked by the compiler (including that the objects and fields exist) and is easier to get right as there is less clutter in the code. It also automatically avoids the risk of SOQL Injection.

Dynamic SOQL based on building strings as you are doing is only occasionally necessary where you want to vary the query in away that can't be done through bind variables.

0

You must log in to answer this question.

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