Sunday 19 May 2024

Dynamically Pass Bind Variables to a SOQL Query

With the new Database.queryWithBinds, Database.getQueryLocatorWithBinds, and Database.countQueryWithBinds methods, the bind variables in the query are resolved from a Map parameter directly with a key rather than from Apex code variables.

Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.

How: In this example, the SOQL query uses a bind variable for an Account name. Its value (Acme Inc.) is passed in to the method using the nameBind Map. The accountName variable isn't (and doesn’t have to be) in scope when the query is executed within the method.


  
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
public static List<Account> simpleBindingSoqlQuery(Map<String, Object> bindParams) {
    String queryString =
        'SELECT Id, Name ' +
        'FROM Account ' +
        'WHERE name = :name';
    return Database.queryWithBinds(
        queryString,
        bindParams,
        AccessLevel.USER_MODE
    );
}
 
String accountName = 'Acme Inc.';
Map<String, Object> nameBind = new Map<String, Object>{'name' => accountName};
List<Account> accounts = simpleBindingSoqlQuery(nameBind);
System.debug(accounts);
 

  

No comments:

Post a Comment