function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MG ConsultingMG Consulting 

No Binding Variables in Dynamic SOQL

Hi,

I just noticed that bind variables are not allowed in Dynamic SOQL. I'd like to be able to pass in a set of Ids, i.e. getLeadIds() and then dynamically vary the subsequent part of the Where clause, i.e. City = 'Boston'.

Code:
Database.query('SELECT Name FROM Lead WHERE Id IN :getLeadIds() AND City = \'Boston\'');

Is there any good way to pass a set of Ids to a Dynamic SOQL statement?

Do I just have to resort to looping through the set of Ids and adding them to the query string in the required format, i.e. ('id1', 'id2')?

Seems a bit cumbersome, so just wondering if anyone had some better ideas on how to handle this.

Thanks a lot,
Mike

JeremyKraybillJeremyKraybill
You can't bind, so you do have to build up a dynamic string. While bindings would be nice, it's not that cumbersome without it.

Code:
String idList = '';
for (Id id : ids) {
 idList = idList + ',\'' + id + '\'';
}
idList = idList.substring(1);

Jeremy Kraybill
Austin, TX
MG ConsultingMG Consulting
Yeah, you're right, it's not so bad, thanks.
sslatersslater
And if you really must use dynamic SOQL, be sure to keep the following in mind:

http://wiki.apexdevnet.com/index.php/Apex_and_Visualforce_Security_Tips#SOQL_Injection


Doug ACFDoug ACF
Per the Spring 09 release notes, bind variables will be available in dynamic SOQL/SOSL with that release next month
MG ConsultingMG Consulting
Nice, thanks for the heads up Doug.