You need to sign in to do that
Don't have an account?
Using Apex variables with LIKE in SOQL queries
I thought I'd share since figuring this out was kind of crappy. Since you can't (or I couldn't find how) concatenate a string in an SOQL query to combine wildcards like % and _ to make a query, you need to do so with the variable you want to pass in.
So if you want to do an SOQL query using LIKE, wild cards, and an Apex variable, this will work.
//create a string
String s = 'mystring';
//add wildcards around it to be more flexible in the search
s = '%' + s + '%';
//create an SOBject list with the results from our query
SObject[] obj = [select id from SObjectName where Name LIKE :s];
and this will return any row from the SObjectName where the "Name" field has "mystring" in it.
You could use Dynamic Apex to dynamically build the SOQL string during runtime.
All Answers
You could use Dynamic Apex to dynamically build the SOQL string during runtime.
so something like this?
//create a string
String s = 'mystring';
//create an SOBject list with the results from our query
SObject[] obj = Database.query('SELECT Id FROM SObjectName WHERE Name LIKE' + '%' + s + '%');
Yes, correct. Here is a little extra to cast the SObject to an Account (for example)
//create a string String s = 'mystring'; //create an SOBject list with the results from our query List<SObject> obj= Database.query('SELECT Id FROM SObjectName WHERE Name LIKE' + '%' + s + '%'); for(SObject o : obj){ Account a = (Account)o; //do more here.....
}
i was using SObject so as to be generic for this question. realistically, i don't think i'd personally need to make the code that generic, rather than just calling the proper SOBject type when creating "obj" in the first place.
thanks much for explaining this.
thanks ... ur solution really helped me . :)
Thanks Paul. Your soution helped me
Again Stuck with the concatenation :
private final String SOQL_RECENT_REC = 'SELECT LastViewedDate,Type,UserRoleId FROM RecentlyViewed';
private final String CONDITION_USER_SORT = ' Order By LastViewedDate DESC LIMIT 20';
List<RecentlyViewed> recentViewed= new List<RecentlyViewed>();
recentViewed = Database.query(SOQL_RECENT_REC +' WHERE Type = \'Account \' ' + CONDITION_USER_SORT);
Should run a query like the following :
recentViewed = [SELECT LastViewedDate,Type,UserRoleId FROM RecentlyViewed Where Type='Account' Order By LastViewedDate DESC LIMIT 20];
Many Thanks !!