24

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'
19

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];
  • 1
    Good answer. This is a little more complicated when you want to use a variable for N in a date range like LastModifiedDate = LAST_N_DAYS:N. – Alain O'Dea Dec 5 '14 at 4:31
  • 2
    I would use Date.today().addDays(-7) and let the Date object handle all of the inherent terribleness of arithmetic on calendar dates for you :) – Alain O'Dea Dec 5 '14 at 5:55
9

You can use Database.query() with a string like:

Integer lastDays = 7;

List<OPPORTUNITY> opplist = Database.query('SELECT OwnerId, Amount, Probability FROM OPPORTUNITY where Amount > 0 and LastModifiedDate < LAST_N_DAYS:' + lastDays);

System.debug(opplist);

This is referred to as Dynamic SOQL.

1

It would be great if you could, but you can't. At least not in any way I'm aware of. When I need this, I build up dynamic SOQL. The date arithmetic eyescream mentions is another solution, although make sure you do thorough testing as date arithmetic is much more bug-prone than SOQL date literals.

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.