How do I build a string for database query Salesforce?
for an extension controller of a VF page, I need to build a query to retrieve all the leads with a Company name similar to a variable. My variable name is compagnia: Now I'm trying to build the query like this:
String query='select Id,Company from Lead where Company like'+ '%'+compagnia'%'
List
But the query doesn't work. How Can I solve this problem?
I'd recommend building such dynamic queries using a library such as Query.apex. Using this library, your statement becomes:
List leads = new Query('Lead')
.selectFields('Company')
.addConditionLike('Company', '%compagnia%')
.run();
This would also solve injection automatically. Moreover, you would end up having less semantic and syntax errors when building the dynamic query string, since your database query Salesforce is more structural.