Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have an array of strings i'd like to use in the IN clause of a dynamic soql query.

if i wasn't building the string at runtime i could simply use (from the SF docs):

String[] ss = new String[]{'a', 'b'}; Account[] aa = [SELECT Id FROM Account WHERE AccountNumber IN :ss];

however, as i'm building at runtime, i use the following (where operators is my array):

soqlString += ' and Operator__c in' + operators;

This errors because the string values in operators are not in quotes. Is there an easy way to replicate the first example in dynamic soql?

share|improve this question

3 Answers 3

up vote 5 down vote accepted

This post by @ca_peterson explains you can directly use bind variables in dynamic soql

Alternatively, you can use this utility method to convert a Set into a String, which can be used in Dynamic SOQL.

 //convert a Set<String> into a quoted, comma separated String literal for inclusion in a dynamic SOQL Query
    private String quoteKeySet(Set<String> mapKeySet)
    {
        String newSetStr = '' ;
        for(String str : mapKeySet)
            newSetStr += '\'' + str + '\',';

        newSetStr = newSetStr.lastIndexOf(',') > 0 ? '(' + newSetStr.substring(0,newSetStr.lastIndexOf(',')) + ')' : newSetStr ;
System.debug('quoteKeySet() :  newSetStr ============ ' + newSetStr);   

        return newSetStr;

    }
share|improve this answer
1  
+1 for bind variables in dynamic soql (I knew it but it's a nice trick nonetheless). But shame on you ;) with Winter'13 we finally got String.join(), no more loops like that! –  eyescream Nov 21 '12 at 23:33

The easiest way is to use the array is as given below.

List<String> operators = new List<String> {'AND','OR'};
soqlString = 'SELECT Name FROM ACCOUNT WHERE Name != null';
soqlString += ' AND Operator__c in :operators';

Apex #automagically converts the reference to collection variables in string query to the corresponding sequence of strings inside the SOQL query.

Just another magic!

share|improve this answer

to compare the values in arrays you will have to use the following syntax see at this link Syntax: SELECT 'value' IN (array)

share|improve this answer
    
The question's author has demonstrated he already knows the IN syntax... –  eyescream Dec 4 '12 at 23:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.