Thursday, August 2, 2012

Variable binding in Apex for dynamic SOQL/SOSL

There are two related topics in the Apex Developer's Guide: Dynamic SOQL, and Using Apex Variables in SOQL and SOSL Queries, but neither provides an example of combining the two.  Well they do combine and work fine, so here's a simple example if anyone is interested:

Id [] ids=new Id []{'500e0000000gev6','500e0000000gevB'};

string q='select id, subject from case where id in ';

case [] cs=database.query(q+' :ids');

This is of course pretty useless, but sometimes you need truly dynamic query with a collection of parameters, the combination would be very handy.  A recent code example I had:

    public static void create_recurrences(List<Id> templates){
          ... ...
        Map<String, Schema.SObjectField> M = Schema.SObjectType.Case.fields.getMap();
        string q='SELECT Id ';
        for (Schema.Sobjectfield f : M.values()){
            if (f.getDescribe().isUpdateable()){
                q+=', '+f.getDescribe().getName();
        q+=' FROM Case WHERE Id in ';
        for (Case c : Database.query(q+' :templates ')){
               ... ...

I'd imagine if you're doing any kind of partner apps, this type of thing could get used a lot.

No comments:

Post a Comment