3

I have a doubt. Suppose I want to query on Account object filtering based on a given list of IDs. Below snippet works fine when I have a list of Ids.

List<String> accountIds = new List<String> {'1','2'};
String query = ' Select ID, Name From Account Where ID in :accountIds';
Database.query(query);

But when I use a Map with List as Values, it gives me an exception.

Map<String, List<String>> acntIdMap = new Map<String, List<String>>{'ids' => accountIds};
String key = 'ids';
query = ' Select ID, Name From Account Where ID in :acntIdMap.get(key)';
Database.query(query);

Exception thrown is System.QueryException: unexpected token: '('.

Is there any way to use the list coming from a map in SOQL query.

Any help is highly appreciated!

1 Answer 1

3

Try this

Map<String, List<String>> acntIdMap = new Map<String, List<String>>{'ids' => accountIds};
String key = 'ids';
List<String> keys = acntIdMap.get(key);
query = ' Select ID, Name From Account Where ID in :keys';
Database.query(query);

as dynamic SOQL only supports simple bind variables.

3
  • Thanks! Your answer will work fine if I have one filter. Say I have dynamic no of filters coming as follows. String query = 'select id ,name from account where ' ; Map<String, String> fieldNameToTypeMap and Map<String, List<Object>> fieldToDataMap. I want to iterate the fieldToDataMap and dynamically build query with all filters sent. Somewhat like below for(String field : fieldNameToTypeMap){ query = query + ' in :fieldToDataMap.get(field)'; }
    – Ashu NCS
    Commented Aug 26, 2015 at 8:55
  • Will all filters be on IDs only ?
    – San
    Commented Aug 26, 2015 at 8:57
  • No, It can be on any fields available in Account Object. Suppose the request comes to add Id, Name, Source fields as filters with their lists of values each. I want to iterate across all fields and append their data to the query for each filter field
    – Ashu NCS
    Commented Aug 26, 2015 at 9:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .