Dynamic SOQL based on Sobject Name and Where Clause

 public class DynamicSOQLUtil {

    // Returns a dynamic SOQL statement for the whole object, based on object name and where clause as a dynamic

    public static string getCreatableDynamicFieldsSOQL(String objectName, String whereClause){

        

        String selects = '';

        // Check whereclause if null then return null

        if (whereClause == null || whereClause == ''){ return null; }

        

        // Get a map of field name and sobject field

        Map<String, Schema.SObjectField> objFieldMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();

        list<string> selectFields = new list<string>();

        

        if (objFieldMap != null){

            for (Schema.SObjectField objFt : objFieldMap.values()){ // loop through all field tokens

                Schema.DescribeFieldResult fd = objFt.getDescribe(); //field describe  for each field

               //if (fd.isCreateable()){ // if needed only add isCreateable field then check it is creatable

                    selectFields.add(fd.getName());

               

              //}

            }

        }

        

        if (!selectFields.isEmpty()){

            for (string s:selectFields){

                selects += s + ',';

            }

            if (selects.endsWith(',')){selects = selects.substring(0,selects.lastIndexOf(','));}

            

        }

        

        return 'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause;

        

    }

    

}



// OutPut

string SQOL = DynamicSOQLUtil.getCreatableDynamicFieldsSOQL('Bank__C','DOB__c!=null');

system.debug('SQOL@@@'+SQOL);


Comments

Popular posts from this blog

Salesforce Spring 16 Release Exam (Maintenance Exam Q&A) for Developer 201 Admin

Show Hyper Link On Add Error in Salesforce Trigger

Show the Success Message before Redirecting the Detail page on Visualforce Page