根据字段值有条件地过滤 SQL 查询

Conditionally filter on SQL query based on the field value

我想根据选项列表的字段值有条件地过滤 SQL 查询。我该怎么做呢?如果选项列表字段值为 'Any Type' 那么我不想过滤查询。

if (picklistValue == 'Any Type') //dont filter     

SELECT Object__c.Name
FROM Object__c
WHERE Object__c.Type__c = :picklistValue

在这些情况下,您需要根据您的条件动态构建 SOQL。在您的情况下,动态 SOQL 可能是这样的:

List<Object__c > objList = new List<Object__c>();
String query = 'SELECT Object__c.Name FROM Object__c ';

if(picklistValue == 'Any Type') {// don't filter
    // your code..
} else {
    // apply filter
    query = query + ' WHERE Object__c.Type__c = \'' + picklistValue + '\';

}

objList = Database.query(query);

详情请参考dynamic SOQL documentation