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
Lucky29Lucky29 

dynamic SOQL query????

Hi,

string namevf=name;

            For(Contact objContact:[SELECT  :namevf,id,MailingStreet,MailingCity,MailingCountry,MailingState FROM Contact])
            {
          
          //some code
            
            }

in the above code , I want to replace  ":namevf" with "name"(or any other API name) if I store the API name in another string variable ...
can any one help me on this......
Best Answer chosen by Lucky29
James LoghryJames Loghry
What you are trying to do is actually called variable binding.  Furthermore, you are trying to use variable binding for selecting a field. You cannot do this, you can only use variable binding for filters in a where clause. For instance:

[Select Id From Contact Where Name = :name];

Or..

[Select Id From Contact Where Id in :contactIds];

If you need to dynamically pick fields from a SOQL query you have to options:
  1. Add all the potential fields you'll be selecting to your SOQL query
  2. Use Dynamic SOQL (http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm)
For the latter you would construct your SOQL in a string like so:

String query = 'SELECT  ' + nameVf + ',Id,MailingStreet,MailingCity,MailingCountry,MailingState FROM Contact';
for(Contact objContact : Database.query(query)){
   //some code
}


All Answers

srikanth sfdcsrikanth sfdc
hi ,

I hope we cannot change the query dynamically
James LoghryJames Loghry
What you are trying to do is actually called variable binding.  Furthermore, you are trying to use variable binding for selecting a field. You cannot do this, you can only use variable binding for filters in a where clause. For instance:

[Select Id From Contact Where Name = :name];

Or..

[Select Id From Contact Where Id in :contactIds];

If you need to dynamically pick fields from a SOQL query you have to options:
  1. Add all the potential fields you'll be selecting to your SOQL query
  2. Use Dynamic SOQL (http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm)
For the latter you would construct your SOQL in a string like so:

String query = 'SELECT  ' + nameVf + ',Id,MailingStreet,MailingCity,MailingCountry,MailingState FROM Contact';
for(Contact objContact : Database.query(query)){
   //some code
}


This was selected as the best answer
Lucky29Lucky29
Hi james ,
Thanks for the solution and it's working 

Thanks for this.......