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
- query as a string
- 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
It was helpful for me.
thank u.
very helpful thanx alot