Well how many times you have tried to use a list variable in a Dynamic SOQL?
We generally use Database.query() , which takes a query in string format and returns a List of sObject . The problem comes when want to use "IN" statement or want to use "date/date time" in a Dynamic query . I really tried a lot of combination, formatting the data,escapes etc.But finally was surprised to see if you just include the variable inside the query String, it just works !!!
Wasn't clear enough??
See the below example which shows how to query all the accounts that are created today:
Please Note : that the variable "now" is included in the string itself.
We generally use Database.query() , which takes a query in string format and returns a List of sObject . The problem comes when want to use "IN" statement or want to use "date/date time" in a Dynamic query . I really tried a lot of combination, formatting the data,escapes etc.But finally was surprised to see if you just include the variable inside the query String, it just works !!!
Wasn't clear enough??
See the below example which shows how to query all the accounts that are created today:
//initialize the Datetime with current time
DateTime now = System.now();
//query accounts by merging the variable name inside the query string
List<Account> accountList = Database.query('SELECT Id FROM Account WHERE CreatedDate =:now');
Please Note : that the variable "now" is included in the string itself.
Is there a way to select the system date time in a SOQL query? For example: SELECT Id, system.now FROM Account
ReplyDeleteWell you can't pick System datetime in a query. You can simply do "Datetime dt = System.now()" and use the variable "dt" wherever needed.
DeleteThanks. I was just hoping there would be something, like in MS SQL : SELECT GETDATE(), ....... that I could include in my query.
DeleteKaren I am not much aware about MS SQL, but APEX has lot of similarities with JAVA. If you are aware about Java you can easily code @force.com
Delete