+ Start a Discussion
Lee_CampbellLee_Campbell 

Dynamic SOQL query

Hi folks,

 

I was wondering if it's possible to produce dynamic SOQL queries. I'll elaborate:

 

I have a class whose input is a string, let's call it str. I then use str to manipulate a double on an object record (rec), like so:

 

(double)rec.get(str)

 

I'd like to query just for this double, specified by the above code, as, at the moment, I'm running something like

 

for(Custom_Object__c rec: [select **loads of different doubles** from Custom_Object__c where **condition**]){

 

which is hitting the SOQL query limit. Is there a way of, in the for loop above, just using "selecting" the double specified by (double)rec.get(str)? i.e. if str was something like "Number_of_Days__c", the loop:

 

for(Custom_Object__c rec: [select (double)str from Custom_Object__c where **condition**]){

 

would yield the same value as:

 

for(Custom_Object__r rec: [select Number_of_Days__c from Custom Object__c where **condition**]){

 

Any help you can give would be massively appreciated.

 

Thanks,

Lee

logontokartiklogontokartik

I am not sure if I understand it right.

 

Looks like you are using only one query, and iterating over the records, Can you please paste the code you are having issues with or maybe elaborate more where exactly you are getting SOQL limit.?

Noam.dganiNoam.dgani

Hi Lee

 

i dont think hitting the limit is caused by the query in the for statement, but probably something inside the for statement.

 

regardless, you can do:

 

String q = 'Select ' + str + ' from Custom_Object__c where SOME CONDITION'; // this is your dynamic query definition

List<Custom_Object__c> objs = database.query(q);

for(Custom_Object__c obj : objs)

{

        Double d = Double.valueOf(obj.get(str));

        //do you stuff

}

Lee_CampbellLee_Campbell

That answers my question, thank you.

 

However, when trying to use this method to query for a related object, I'm presented with this kind of error:

 

Invalid field Related__r.Custom_Field__c, if str = 'Related__r.Custom_Field__c', in spite of the fact that the field most certainly does exist (because I was accessing it using static SOQL previously).

 

Any clues as to why that might be?

 

Thanks,

Lee