Loading

Use LIKE in SOQL when used in Apex to escape special characters

Publiceringsdatum: Oct 13, 2022
Beskrivning
When using LIKE to match a search term in SOQL that includes a reserved character like an underscore, in Apex code, you will need to take additional steps to get the expected results. 
 
@isTest 
private static void testWithoutAssignment() 
{ 
    insert new account(name='namea'); 
    insert new account(name='name_a'); 
    insert new account(name='name_b');

    List<Account> a = [SELECT Name From Account Where Name like '%\\_a'];
    system.debug(a);
    system.assertEquals(1,a.size());  // fails
}



This test escapes the underscore character. You would expect this to succeed, and match with one row - 'name_a' but it does not. 

 
Lösning
If using the normal escape method does not work, as with the underscore character, assigning the search term to a variable, and then using the variable in the SOQL query will allow the LIKE statement to match the correct values. 
 
@isTest 
private static void testWithAssignment() 
{ 
    insert new account(name='namea'); 
    insert new account(name='name_a'); 
    insert new account(name='name_b'); 

    String searchTerm = '%\\_a';  // assign the search term to a variable

    List<Account> a = [SELECT Name From Account Where Name like :searchTerm]; 
    system.debug(a); 
    system.assertEquals(1,a.size());  // success

}
Knowledge-artikelnummer

000382866

 
Laddar
Salesforce Help | Article