[SalesForce] SOQL Dynamic Query building using Map.get(List)

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!

Best Answer

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.

Related Topic