While troubleshooting a programming problem today I noticed that you can’t use a LIKE search for string columns containing special characters like % or _ without using a special syntax. Figuring out the problem took only a few minutes, but remembering syntax is always easier if you write about it.
So yes, this post is solely for my benefit. Hopefully it will help somebody else too.
Let’s say you want to find any fields that contain the text “100%”, so you put together this query:
SELECT * FROM tablename WHERE fieldname LIKE ‘%100%%’
Instead of what you wanted, you’ll get all the rows that contain “100″ as well as the rows that contain “100%”.
The problem here is that SQL Server uses the percent sign, underscore, and square brackets as special characters. You simply can’t use them as a plain character in a LIKE query without escaping them.
Square Bracket Escape
You can surround the % or _ with square brackets to tell SQL Server that the character inside is a regular character.
SELECT * FROM tablename WHERE fieldname LIKE ‘%100[%]%’
T-SQL ESCAPE Syntax
Alternatively, you can append the ESCAPE operator onto your query, and add a \ character before the value you want to escape.
SELECT * FROM tablename WHERE fieldname LIKE ‘%100\%%’ ESCAPE ‘\’
The ESCAPE ‘\’ part of the query tells the SQL engine to interpret the character after the \ as a literal character instead of as a wildcard.
Personally I find the second method easier to deal with, and you can use it to escape a square bracket as well.