July 10, 2012

Like operator in Salesforce

Example:

String sql = 'Select Name From Account WHERE Name LIKE \'%' + searchKeyword + '%\'';

where searchKeyword is an Apex variable.

(or)

List<Contact> listCon = [SELECT Id, FirstName FROM Contact WHERE FirstName LIKE '%test%'];

system.debug('List contacts are ' + listCon);

3 comments:

  1. Thank you its working.

    ReplyDelete
  2. Hi Everyone ,

    I just wrote a simple batch apex which will update account names with some text but its not working , could anyone suggest is there any mistake in SOQL?
    Please note I am just taking accounts which are starting from AccountTest and updating those records and following is my code:
    global class BatchApexExample implements Database.Batchable {


    global Database.QueryLocator start(Database.BatchableContext BC){

    System.debug('inside');
    string accRecords = 'AccountTest';
    String query = 'Select Name From Account WHERE Name LIKE \' '+accRecords+' %\'';
    System.debug('-------query-------'+query);
    return Database.getQueryLocator(query);


    }

    global void execute(Database.BatchableContext BC,List accList){

    for(Account accToUpdate : accList){

    accToUpdate.name = accToUpdate.name + 'BATCHAPEXEXAMPLE';

    }
    try{
    update accList;
    }
    catch(Exception e){

    System.debug('---Error---'+e);
    }
    }

    global void finish(Database.BatchableContext BC){

    //finish

    }


    }



    Thanks in Advance!

    ReplyDelete
    Replies
    1. The issue was with the query.
      String query = 'Select Name From Account WHERE Name LIKE \''+accRecords+'%\''; There shouldn't be any white space(blank space) before and after the escape sequence.

      Delete