Salesforce

Before going to code we learn about  Dynamic Soql Query .
Dynamic Soql:

Dynamic SOQL refers to the creation of a SOQL string at run time with Apex code. Sometimes we need to query data on the based of input from end users or update records with varying field names. Here to achieve  this requirement we use  dynamic  Soql queries.

To create a Dynamic Soql Query at run time,  we use  database query method.

To create a dyanmic soql  you need to keeps

  1. query as a string
  2.  Execute  query string using Database.query method.

Here is the Duanmic soql query example  in this example we are getting  soql fields from a fieldset.

// here first we  take query as a string 
String query = 'SELECT ';

// now get fields from fieldset iterate over fieldset and concate the field to query string
for(Schema.FieldSetMember f : SObjectType.opportunity.FieldSets.Yourfieldset_name.getFields())
{
query += f.getFieldPath() + ', ';
}
query += 'id FROM Opportunity where id in:oppids';

// execute query string using Database.query
list<opportunity> oppor = Database.Query(query);

 

Hits: 1771

Share Post

By Himanshu Rana

My Name is Himanshu Rana, 23 Years young, born and grow up in Ghaziabad, India. A High Spirited Salesforce Admin, Developer and a Blogger. I currently work at Wakencode Technologies,

2 thoughts on “How to write Dynamic Soql Query .”

Leave a Reply

Your email address will not be published. Required fields are marked *