function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
scottj2scottj2 

LAST_N_DAYS with apex variable

Hi All,

 

I'd like to do something like this with APEX/SOQL:

 

Integer numDays = x;

List<Account> accs = [select id from account where createddate = LAST_N_DAYS::var];

 

 

Essentially, I want to pass the variable to the LAST_N_DAYS feature in SOQL.  Any ideas?

Best Answer chosen by Admin (Salesforce Developers) 
colemabcolemab

You can pass date literals in - just not by bind variable.  What you need to do instead is *build* your SOQL string using your variable and the execute that string against the database using database.query(INSERT_SOQL_STRING_HERE)

 

This is called dynamic SOQL and can be found here

All Answers

colemabcolemab

You can pass date literals in - just not by bind variable.  What you need to do instead is *build* your SOQL string using your variable and the execute that string against the database using database.query(INSERT_SOQL_STRING_HERE)

 

This is called dynamic SOQL and can be found here

This was selected as the best answer
scottj2scottj2

I sort of found a solution, which I think is equivalent

 


Date startDate = Date.today().addDays(-Integer.valueOf(numDays));
List<Account> accs = [select id from account where createddate >= :startDate];

 

I guess dynamic SQL would work as well.