0

I am newbie & trying to create a dynamic querystring on the basis of some conditions, & even when it does not satisfies any condition, the query should be able to run properly with where clause like (where 1 as in other database engines). However, I found that (where 1) is not supported by Apex. So, just wondering If i can use anything else for this situation.

    queryString = 'WHERE 1 ';

    if(string.isNotEmpty(gravicID)) {

        queryString += ' AND (Parameter__c = \'' + 'Test' + '\' AND value__c Like \''+String.escapeSingleQuotes(TestID)+'%\')';
    }

if(string.isNotEmpty(AA)) {

        queryString += ' AND (Parameter__c = \'' + 'TestName' + '\' AND value__c Like \''+String.escapeSingleQuotes(TestName)+'%\')';
    }

And running the SOQL as below,

searchRecordsMap = new Map<String, Container__c>([SELECT Parameter__c, Value__c FROM Container__c queryString ]);

1 Answer 1

1

As far as I get the question, there are no such structure as WHERE 1 in apex. Based on your question, next structure may be used:

List<String> and_conditions = new List<String>();
//add some condition like/
//  and_conditions.add( ' test__c = true AND test_data__c != null ');
//  and_conditions.add(' test__c = false AND test_data__c = \'Data\' ');
String where_clause = ' ';
if (!and_conditions.isEmpty()){
    for(Integer i = 0; i < and_conditions.size(); i++){
         if(i == 0){
             where_clause = ' WHERE (' + and_conditions.get(i) + ') ';
         }else{
             where_clause +=' AND (' + and_conditions.get(i) + ') ';
         }
    }    
}

That would support only AND clause as a root clause, but that is simple enough to understand pattern, and improve it on demand.

P.S. there are some statements which are always true. Like WHERE Id != null

P.S.S. With 1.5 year more experience, code written above can be improved

List<String> and_conditions = new List<String>();
//add some condition like/
//  and_conditions.add( ' test__c = true AND test_data__c != null ');
//  and_conditions.add(' test__c = false AND test_data__c = \'Data\' ');
String where_clause = ' ';
if (!and_conditions.isEmpty()){
    where_clause = 'WHERE (' + String.join(and_conditions, ' ) AND ( ') + ')';
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .