Dynamic SOSL refers to the creation of a SOSL string at runtime with an Apex script. Dynamic SOSL enables you to create more flexible applications. For example, you can create a search based on input from an end user, or update records with varying field names.
To create a dynamic SOSL query at runtime, use the search query method. For example:
List<List <sObject>> myQuery = search.query(SOSL_search_string);
The following example exercises a simple SOSL query string.
String searchquery='FIND\'Edge*\'IN ALL FIELDS RETURNING Account(id,name),Contact, Lead';
List<List<SObject>>searchList=search.query(searchquery);
Dynamic SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the dynamic SOSL query. From the example above, the results from Account are first, then Contact, then Lead.
The search query method can be used wherever an inline SOSL query can be used, such as in regular assignment statements and for loops. The results are processed in much the same way as static SOSL queries are processed.
SOSL queries are only supported in Apex classes and anonymous blocks. You cannot use a SOSL query in a trigger.
Dynamic SOSL queries have the same governor limits as static queries. For more information on governor limits, see Understanding Execution Governors and Limits.
For a full description of SOSL query syntax, see www.salesforce.com/us/developer/docs/api/index_CSH.htm#sforce_api_calls_sosl.htm in the Force.com Web Services API Guide.
SOSL injection is a technique by which a user causes your application to execute database methods you did not intend by passing SOSL statements into your script. This can occur in an Apex script whenever your application relies on end user input to construct a dynamic SOSL statement and you do not handle the input properly.
To prevent SOSL injection, use the escapeSingleQuotes method. This method adds the escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands.