30

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'

4 Answers 4

25

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];
2
  • 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. Commented Dec 5, 2014 at 4:31
  • 5
    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 :) Commented Dec 5, 2014 at 5:55
14

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.

0

You can directly query it like:

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

No need to declare variable and its value first,

You must log in to answer this question.

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