SOQL でアンダースコアなどの予約文字を含む検索用語と一致させるために LIKE を使用する場合、Apex コードで、期待する結果を得るには、追加の手順を実行する必要があります。
@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
}
このテストはアンダースコア文字をエスケープしています。これが成功して、1 つの行「name_a」と一致することを期待しますが、一致しません。
アンダースコア文字があるために、通常のエスケープ方法の使用が機能しない場合、検索用語を変数に代入して、SOQL クエリで変数を使用することで、LIKE ステートメントが正しい値に一致するようになります。
@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
}000382866

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.