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: '('

  • 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 – Yogesh Gupta Apr 13 '16 at 6:49
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).

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

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);
  • Thanks, but is it possible using map only ? – Yogesh Gupta Apr 13 '16 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 '16 at 7:05
  • @YogeshGupta is my ans different than Neha's Answer ? – Ratan Paul Apr 14 '16 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

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.