What are Dynamic Queries in SALESFORCE?
A dynamic query is a SOQL or SOSL query which can be constructed and executed at runtime. It is the process of constructing the query string consisting of the fields to be retrieved and the WHERE clauses, based upon certain conditions.
SOQL – Salesforce Object Query Language
SOSL – Salesforce Object Search Language
Here is an example of Dynamic SOQL:
General class which runs the query
Public class DynamicQueryUtility { // Function to run the query Public List runQuery(String objname, String[] fieldnames, String condition) { List queryresult; String fieldslist = ''; // Generate the fieldslist from the string array if (fieldnames != NULL) { if(fieldnames.size() > 0) { for (Integer i=0; i < fieldnames.size(); i++) { if( i <= (fieldnames.size() - 2)) fieldslist = fieldslist+fieldnames[i]+','; else fieldslist = fieldslist+fieldnames[i]; } } } // Construct the query string String soqlquery = 'Select '+fieldslist+' from '+objname+' '+condition; // Run the query queryresult = Database.query(soqlquery); return queryresult; } }
To Call the Above Class:
// Construct the list of fields String[] fieldList = new List<String>{'FirstName','LastName','Id'}; // Initialte a new variable of the general utility class DynamicQueryUtility conRes = new DynamicQueryUtility(); // Call the runquery method to execute the query. Note that the condition has to be passed as an empty string if you do not have any condition Contact[] contactResult = conRes.runQuery('Contact', fieldList, ''); system.debug('The query result is::'+contactResult);
Salesforce Notes about Dynamic Query: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm