Sunday, October 2, 2016

Dynamic Apex - Build Dynamic SOQL and SOSL

This post is the continuation of my previous two posts on Dynamic Apex. You can find the posts here
In this post, I will explain another very powerful feature of Dynamic Apex i.e. Dynamic SOQL and SOSL.

Dynamic SOQL:
Dynamic SOQL refers to the ability of creating SOQL statement in runtime with Apex code i.e. you can select which fields you want to query based on situation or user input and then prepare the SOQL statement and finally perform the query to fetch the data from the organisation.

You can execute the below statement to perform the query:

Dynamic SOQL can return concrete sObjects i.e. Account, Lead or MyCustomObject__c or the generic sObject data type. At runtime, system will match the return type with the variable's declared type. If the types are not matching, then runtime will be thrown. So it is the responsibility of the developer to cast from generic sObject data type to a concrete sObject.

In terms of governor limits, Dynamic SOQL queries have the same governor limits as static queries.

Below example is going to fetch the fields from Account sObject, prepare the SOQL statement and then finally query Account sObject to fetch the data.

Dynamic SOQL Consideration:
In Dynamic SOQL, you cannot use bind variable strings in a query string. For example, the below section of code will not work and will throw an error that Variable doesn't exist.

To solve that you need to resolve the variable into a String variable and then use in Dynamic SOQL. Below is the code which will work.

Dynamic SOSL:
With Dynamic SOSL, developer can create SOSL statement in runtime thus allowing to build more flexible applications.

You can execute the below statement for dynamic SOSL:

Dynamic SOSL statement returns a list of lists of sObjects, where each list contains the search result for a particular sObject type. Results will be stored in the same order as the sObjects are specified in the dynamic SOSL query. Dynamic SOSL can't be used where an inline SOSL can be used, such as in regular assignments and for loops.

Dynamic SOSL is also having the same governor limits as static SOSL statements.
Below code will search for the keyword in the object - Account, Lead, Contact and sudipta__Book__c.

Please provide your feedback. Thanks.


Post a Comment