How do I build a string for database query Salesforce?

695    Asked by arun_3288 in Salesforce , Asked on Sep 23, 2022

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 l=Database.query(query);

But the query doesn't work. How Can I solve this problem?

Answered by Amelia Arnold

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.



Your Answer

Interviews

Parent Categories