Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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'
share|improve this question

3 Answers 3

up vote 8 down vote accepted

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];
share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.