ESCAPE statement in the LIKE-query

suggest change

If you implement a text-search as LIKE-query, you usually do it like this:

SELECT * 
FROM T_Whatever 
WHERE SomeField LIKE CONCAT('%', @in_SearchText, '%')

However, apart from the fact that you should not necessarily use LIKE when you can use full-text search, this creates a problem when somebody inputs text like “50%” or “a_b”.

So (instead of switching to fulltext-search), you can solve that problem using the LIKE-escape statement:

SELECT * 
FROM T_Whatever 
WHERE SomeField LIKE CONCAT('%', @in_SearchText, '%') ESCAPE '\'

That makes \ the escape character. Escape only %, _, and \ itself in the search text. Escaping every character is wrong: in SQL Server, an escape character that is not followed by a wildcard or by itself is an error. In standard SQL a backslash inside quotes is an ordinary character, so ESCAPE '\' is a one-character escape. MySQL’s default string escapes can treat \' as an escaped quote and make this literal invalid.

e.g.

string stringToSearch = "abc_def 50%";
string newString = stringToSearch.Replace(@"\", @"\\").Replace("%", @"\%").Replace("_", @"\_");

sqlCmd.Parameters.Add("@in_SearchText", newString);
// instead of sqlCmd.Parameters.Add("@in_SearchText", stringToSearch);

Replace \ first so the escapes added for % and _ are not themselves escaped again.

See also https://stackoverflow.com/questions/1009689/reversestring-a-c-sharp-interview-question/36312251#36312251

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents