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
WilmerWilmer 

How to build dynamic queries using ApexCode?

Hi, I need to build dynamic queries by passing variables values to the statement from the choice an user has done from a selection list.
 
For example: I got a list with these values (representing field names from a SObject): 'Field1__c', 'Field2__c', 'Field3__c', ..., 'FieldX__c'. So I got the selected value and I want to build a query according to the user choice like this:
 
Code:
String strSelectedField = Myobject.RequestedField__c; // This passes the selected FieldName from the combobox.
Map<String, Account> FoundValuesMap = new Map<String, Account>();
for(Account QueryResult : [Select strSelectedField from Account]){
  FoundValuesMap.put(QueryResult.strSelectedField, QueryResult);
}

 Obviously, if I try this code an error comes up saying that the FieldName "strSelectedField" doesn't exist on Account object. I tried to put before the variable name the caracter ":" but another error appears saying there is an unexpected token (:). I can not define those fieldnames because the list of fields could change without notice.
 
How could I pass the variable to query to make SOQL understand the value as a fieldname?
 
Thanks for any given help.
 
Regards,
 
WILMER
Ron HessRon Hess
This is not possible with Apex Code today, please vote for this idea on the Force.com Idea Exchange
WilmerWilmer

ok, Ron.

It is good to know a least, that it's not possible yet.

Anyway, if in the future this would be possible, please let us know.

Thanks,

Wilmer

 

kpitkpit

I got "Save error: Expression of type Schema.DescribeSObjectResult has no member named fields" with the following code in Sandbox. Please help.

Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;

 
WilmerWilmer
Hi, in summer '08 dynamic queries  in Apex Code will be available but not as a commercial solution, it need to be activated in your org after a special request. Check this page [click on the 'Link' word]: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm 


Message Edited by Wilmer on 06-17-2008 09:30 AM