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
pooja chauchanpooja chauchan 

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 pooja chauchan
Gaurav NirwalGaurav Nirwal

1. If you need to dynamically pick fields from a SOQL query you have to options: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
}