Can you provide an example of adding multiple arguments to a dynamic soql query?

222    Asked by DavidEDWARDS in Salesforce , Asked on May 9, 2023

 I'm trying to build a dynamic query but I think I may have the wrong syntax.

String query = 'SELECT ProjectId__c from Project__c'
projectList = Database.query(query + ' WHERE Name__c equals 'pp2');

No error is thrown, only there are no retrieved records. Also, can someone provide an example of adding multiple arguments to a dynamic query?

You should not use a dynamic soql query unless you must. In this case, since you are doing nothing fancy, just use a static query:


projectList = [SELECT ProjectId__c FROM Project__c WHERE Name = 'pp2'];
There are two problems you have, the first of which is much easier to solve.
The equality operator for SOQL is =, not equals.
If you want to merge in a literal string, you must escape the single quote characters:
projectList = Database.query(baseQuery + 'WHERE Name__c = 'pp2'');
As an alternative to 2, you can use merge syntax. You can merge in any variable that is in scope, but you cannot reference any names or properties.
projectList = Database.query('SELECT ProjectId__c FROM Project__c WHERE Name = p2');

Your Answer

Interviews

Parent Categories