I am setting a string qryDate = 'Last_N_Months:' + x - so it could be Last__Months:3.

I create a string qryString = 'SELECT field1 FROM Case WHERE CreatedDate=: qryDate' and then do: result = Database.query(qryString); I get this error: Invalid bind expression type of String for column of type Datetime

I know CreatedDate = Last_N_Months:3 works so why doesn't mine work?

1 Answer 1


It's a Date Literal. You need to merge it in as such. Rather than using a bind variable, you need to actually include the string so it results in your dynamic SOQL containing a Date Literal.

String soql = '... WHERE CreatedDate = LAST_N_MONTS:' + x;

Effectively, what you had would output:

SELECT ... FROM ... WHERE CreatedDate = 'LAST_N_MONTHS:42'

But what you really want (and the above provides) is:

SELECT ... FROM ... WHERE CreatedDate = LAST_N_MONTHS:42

You must log in to answer this question.

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