Bind it Up: Dynamic SOQL with Variables

       1. Utilize the Like operator in a dynamic SOQL query as shown below.

   

                 String accName = 'Ac';

         String searchText = '%' + accName + '%';


         String query = 'Select Id, Name, Industry From Account ';

         query = query + 'Where Name Like :searchText';

         System.debug('Dynamic SOQL Query: ' + query);


         List<Account> accountList = database.Query(query);


        System.debug('Account List Size: ' + accountList.size());

           



        2. Utilizing a String in a dynamic SOQL query is as shown below.


                String accName = 'Acme';


        String query = 'Select Id, Name, Industry From Account ';

        query = query + 'Where Name = :accName AND Industry = \'Manufacturing\' ';

        List<Account> accountList = database.Query(query);


        System.debug('Account List: ' + accountList);


        3. Variable binding in a dynamic SOQL query is demonstrated below:

       /*

       If you define values in Custom Label, then we can use the syntax below

      Set<String> AccName = System.Label.LabelValues.split(',');

     */

      Set<String> AccName = new Set<String>{'Acme', 'Kyle C. Korbal', 'Matthew Lukes'};


     String query = 'Select Id, Name From Account ';

     query = query + 'Where Name IN :AccName AND Industry <> NULL';


     List<Account> accountList = database.Query(query);


    System.debug('Account List: ' + accountList);