A typical SOQL Query return a list of Opportunity records(with conditions) may be in the following pattern,
Database.getQueryLocator([SELECT Name,Id,StageName from Opportunity StageName='Closed Won']).
The above case may work only if our returned records meeting Query conditions are fixed, as StageName='Closed Won' above.
Database.getQueryLocator([SELECT Name,Id,StageName from Opportunity StageName='Closed Won']).
The above case may work only if our returned records meeting Query conditions are fixed, as StageName='Closed Won' above.
Hence specifying SOQL directly between square brackets may not work in all conditions, as above.
Implying that it works only at compile time costing to run the query again and again.
Quite simple solution for this is, to assign the SOQL Query to string variable and then by appending query/filter conditions to the assigned string variable at run time as below.
string strQuery='SELECT Name, Id, closedate, StageName from Opportunity WHERE StageName=\'Closed Won\'';
Suppose if we want to classify/filter the records based on a VF page field value (in this case Name LIKE %Univ%),then
strQuery+=' AND Name LIKE \'%Unive%\'';
Finally run the Query as below,
Database.getQueryLocator(strQuery);
Makes sense, isn't it?
Implying that it works only at compile time costing to run the query again and again.
Quite simple solution for this is, to assign the SOQL Query to string variable and then by appending query/filter conditions to the assigned string variable at run time as below.
string strQuery='SELECT Name, Id, closedate, StageName from Opportunity WHERE StageName=\'Closed Won\'';
Suppose if we want to classify/filter the records based on a VF page field value (in this case Name LIKE %Univ%),then
strQuery+=' AND Name LIKE \'%Unive%\'';
Finally run the Query as below,
Database.getQueryLocator(strQuery);
Makes sense, isn't it?
Note: In this case, use the field value between \' and \' as we try to specify a string inside another string in a SOQL Query.
No comments:
Post a Comment