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!

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.

  • 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 Aug 26 '15 at 8:55
  • Will all filters be on IDs only ? – San Aug 26 '15 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 Aug 26 '15 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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