6
Map<Id, Account> maps = new Map<Id, Account>();
for(Account acc : [Select Id from Account])
{  
    maps.put(acc.Id, acc);
}

String s = 'Select Id from Account Where Id IN : maps.keySet()' ;

List<Account> acc =   Database.query(s);
System.debug('@@' + acc);

Line: 9, Column: 1 System.QueryException: unexpected token: '('

1
  • Map<Id, Account> maps = new Map<Id, Account>(); for(Account acc : [Select Id from Account]) { maps.put(acc.Id, acc); } String s = 'Select Id from Account Where Id IN : ' ; s = s+ maps.keySet(); List<Account> acc = Database.query(s); System.debug('@@' + acc); Its also not working Apr 13, 2016 at 6:49

3 Answers 3

2

Yes, We have to store map.KeySet() or map.values() in either list/set and then use that set and list over there. Because , we can use variable and collection in dynamic SOQL and map.keySet() / map.values() are the method of collection type(map).

2
  • i flagged this answer for moderation. Because there is best answer given by @sfdcweb which is perfect.
    – Bforce
    Apr 22, 2016 at 14:49
  • 1
    @BaskaranS this isn't something moderators can change. Apr 25, 2016 at 7:15
11

Use an extra set variable

set<Id> setAccountIds = new set<Id>();

Map<Id, Account> maps = new Map<Id, Account>([Select Id from Account]);
setAccountIds.addAll(maps.keySet());
String s = 'Select Id from Account Where Id IN :setAccountIds ';

List<Account> acc =   Database.query(s);
System.debug('@@' + acc);
3
  • Thanks, but is it possible using map only ? Apr 13, 2016 at 7:03
  • @YogeshGupta what I think looks we can't use directly map's keyset.. We need to store somewhere and then use in dynamic soql
    – Ratan Paul
    Apr 13, 2016 at 7:05
  • @YogeshGupta is my ans different than Neha's Answer ?
    – Ratan Paul
    Apr 14, 2016 at 7:07
3

from the Apex Developer guide

"You can use simple bind variables in dynamic SOQL query strings:

for more info about the binding

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm

You must log in to answer this question.

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