1

I was going through the new feature from Spring 23 release regarding Dynamically Pass Bind Variables to a SOQL Query With queryWithBinds Method. It seems like it is working when there is only one value in the map. I might be wrong and that is why I am asking this question here to understand it clearly. Below are some code snippet I wrote to try this out.

Fetching all accounts and store it in map

Map<String, Account> m = new Map<String, Account>([SELECT Id FROM Account ]);

Can I use m.keySet() with queryWithBinds to find out all contacts associated with these accounts?

List<Contact> contacts = 
    Database.queryWithBinds('SELECT Id FROM Contact WHERE AccountId in :m.keySet()',
                            m, AccessLevel.USER_MODE);

Also when I was trying to execute the below code and it is not working with the error that with :in I have to use some sort of iterable, but other than keySet() what I can use here.

Map<String, Object> acctBinds = new Map<String, Object>();
acctBinds.put('acctName', 'GenePoint');
acctBinds.put('acctName', 'sForce');
acctBinds.put('acctName', 'Dickenson plc');
        
List<Account> accts = 
   Database.queryWithBinds('SELECT Id FROM Account WHERE Name in :acctBinds.keySet()',
                            acctBinds, 
                            AccessLevel.USER_MODE);
        
System.Debug('accts: ' + accts.size());
2
  • In your example, you want map values rather than keys
    – identigral
    Feb 28, 2023 at 5:29
  • Can I use map values here? Feb 28, 2023 at 6:55

1 Answer 1

3

Dynamic SOQL does not support dotted expressions as bind values. And the point of queryWithBinds is to be able to use the key name string from the map and obtain the object value whatever type that is.

So this is likely to work for your case:

Map<String, Object> m = new Map<String, Object>();
m.put('names', new Set<String>{'GenePoint', 'sForce', 'Dickenson plc'}); 

... ['SELECT Id FROM Account WHERE Name in :names'], m, ...

And you can have multiple different key names as needed to bind values into expressions.

0

You must log in to answer this question.

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