Using SOQL apex bind variables for date literals (e.g. LAST_N_DAYS, TODAY, THIS_QUARTER)

Is there anyway I can use a variable value for LAST_N_DAYS. For example, I am trying to do something like:

Integer lastDays = 7;
//... 
//...
List<Opportunity> opportunities = [SELECT OwnerId, Amount, Probability FROM OPPORTUNITY 
where Amount > 0 and LastModifiedDate < LAST_N_DAYS:lastDays];

But I get:

expecting a number, found 'lastDays'

Answer

Wow, that’s an interesting one! I doubt it’s allowed though (at least without having to use Dynamic SOQL).

You can always do this instead:

Date d = System.today() - 7;
List<Opportunity> opportunities = [SELECT OwnerId, Amount, Probability FROM OPPORTUNITY 
where Amount > 0 and LastModifiedDate < :d];

Attribution
Source : Link , Question Author : dublintech , Answer Author : eyescream

Leave a Comment