Friday, June 1, 2012

Dynamic SOQL and SOSL


Dynamic SOQL and SOSL:
Dynamic SOQL/SOSL is nothing but the creation of a SOQL/ SOSL string at runtime with an Apex script. Dynamic SOQL enables you to create more flexible applications means developer can pass parameters dynamically. For example, you can create a search based on input from an end user, or update records with varying field names on different objects.
Following are the steps to create a dynamic SOQL query at runtime, use the database query method, in one of the following ways:
1. Return a single salesforce Object when the query returns a single record:
Code: sObject S = Database.query (string_limit_1);
Database query methode return number of sObjects.
2. Return a list of sObjects when the query returns more than a single record of the object:
Code: List ListofObject= Database.query(string);
The database query method can be used wherever an inline SOQL query can be used, such as in regular assignment statements and for loops. Results are processed in much the same way as static SOQL queries are processed.
Live example Dynamic SOQL Code:
public String getSearchQuery(){
companyName = inputFieldValue.Company+'%';
cityName = '%'+inputFieldValue.City__c+'%';
countryName = inputFieldValue.Address_Country__c;
String Operator='='
dist = 'Distributor';
partnerStatus ='Active';
locationType = 'Headquarters';
String Query;
if(countryName !=null && countryName !=''){
Query='Select Id,Name,City__c,Country_list__c , State_LIst__c, Location_Type__c, BP_Link_Id__c from Account where Name like: distributorName and Partner_Type_New__c = :dist and Location_Type__c = :locationType and Status__c = :partnerStatus and Country_list__c= :countryName'
}else{
Query='Select Id,Name,City__c,Country_list__c , State_LIst__c, Location_Type__c, BP_Link_Id__c from Account where Name like: distributorName and Partner_Type_New__c = :dist and Location_Type__c = :locationType and Status__c = :partnerStatus'
}
return Query;
}
Description:
Above code snippet method return Dynamic SOQL where we are passing some fields value at run time and also written some condition on if Country name is blank.

No comments:

Post a Comment