Database.query(soql);
String strName = 'Test';
String soql = 'Select Id, Name From SObject';
if(Name != null){
soql += 'And Name LIKE \'%' + strName.trim() + '%\'';
}
eg:
public void runQuery() {
try {
productList = Database.query(soql);
//If there is empty,give a hint
if(productList.isEmpty()){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'There is no such product in our ORG.'));
return;
}
} catch (Exception e) {
//Catch exceptions for abnormal hints
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
return;
}
}
public PageReference searchAction(){
soql = 'Select ProductCode, Name, IsActive, Id, Family, Material_Cost__c, Description From Product2 Where Name != null';
if (proName.trim() != null && !proName.trim().equals('')){
soql += ' and Name LIKE \'%'+ String.escapeSingleQuotes(proName.trim()) + '%\'';
}
if (proCode.trim() != null && !proCode.trim().equals('')){
soql += ' and ProductCode LIKE \'%' + String.escapeSingleQuotes(proCode.trim()) + '%\'';
}
runQuery();
return null;
}
**http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm
转载于:https://blog.51cto.com/919637235/1543744