Question
How do I escape the underscore character?
I am writing something like the following where clause and want to be able to find actual entries with _d at the end.
Where Username Like '%_d'
Solution
T-SQL Reference for LIKE for SQL Server 2000:
You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The table shows several examples of using the LIKE keyword and the [ ] wildcard characters.
For your case:
... LIKE '%[_]d'
OTHER TIPS
Obviously @Lasse solution is right, but there's another way to solve your problem: T-SQL operator LIKE
defines the optional ESCAPE clause, that lets you declare a character which will escape the next character into the pattern.
For your case, the following WHERE clauses are equivalent:
WHERE username LIKE '%[_]d'; -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';
These solutions totally make sense. Unfortunately, neither worked for me as expected. Instead of trying to hassle with it, I went with a work around:
select * from information_schema.columns
where replace(table_name,'_','!') not like '%!%'
order by table_name
This worked for me, just use the escape
'%\_%'