General Query Utility - using Dynamic SOQL

10:14 PM

This sample code covers a general query utility which can be used to query any object.

This is the general class which runs the query. Comments are embedded inline for understanding the functionality.

Copy and paste this class

Public class QueryUtility
{
    // Function to run the query
    Public List<sObject> runQuery(String objname,String[] fieldnames,String condition)
    {
        List<sObject> queryresult;
        String fieldslist = '';
        // Generate the fieldslist from the string array
        if (fieldnames != NULL)
        {
            if(fieldnames.size() > 0)
            {
                for (Integer i=0; i < fieldnames.size(); i++)
                {
                    if( i <= (fieldnames.size() - 2))
                        fieldslist = fieldslist+fieldnames[i]+',';
                    else
                        fieldslist = fieldslist+fieldnames[i];    
                }
            }
        } 
        // Construct the query string
        String soqlquery = 'Select '+fieldslist+' from '+objname+' '+condition;
        // Run the query
        queryresult = Database.query(soqlquery);
        return queryresult;               
    }
}    

To Call this class:

You can call this class from any other class. Below is a sample code which you can embed into any class or you can execute this from the system log.


// Construct the list of fields
     String[] flist  = new List<String>{'Name','Id'};
// Initialte a new variable of the general utility class
     QueryUtility test = new QueryUtility();
// Call the runquery method to execute the query. Note that the condition has to be passed as an empty string if you do not have any condition
     Account[] qresult = test.runQuery('Account',flist,'');
     system.debug('The query result is'+qresult); 

1 comments

  1. subject :- Salesforce administrator

    Salesforce Consultant & Salesforce administrator can help you with salesforce projects and salesforce certification, salesforce helpdesk, salesforce training, salesforce automation helps in salesforce
    http://www.plug2salesforce.com

    ReplyDelete

AD