Dynamic SOQL with conditions

Standard

Very often, salesforce developers work on requirements where they have to generate SOQL queries on the fly/dynamically. And everyone has there own style of coding, hence they attempt this topic in their own unique ways.

Here is the code snippet I generally use when working with dynamic SOQL. Hope thats helpful 🙂

private String strSOQL = '';

private void prepareSOQL(){
 strSOQL = 'Select Name, Ticker_symbol__c, Headquarters__c, Company_Type__c, Ownership__c from CustomObject__c';
 List<string> conditions = new List<string>();

if(acct.Name!=''){
 conditions.add('Name LIKE \'%' + acct.Name + '%\' ');
 }

if(acct.Ticker_symbol__c!=''){
 conditions.add('Ticker_symbol__c LIKE \'%' + acct.Ticker_symbol__c + '%\' ');
 }

if(acct.Industry__c!=''){
 conditions.add('Industry__c = \'' + acct.Industry__c + '\' ');
 }

if(acct.Company_type__c!=''){
 conditions.add('Company_type__c = \'' + acct.Company_type__c + '\' ');
 }

if(acct.Company_status__c!=''){
 conditions.add('Company_status__c = \'' + acct.Company_status__c + '\' ');
 }

if (conditions.size() > 0) {
 strSOQL += ' WHERE ' + conditions[0];
 for (Integer i = 1; i < conditions.size(); i++)
 strSOQL += 'AND ' + conditions[i];
 }
 }

Advertisements