SQL Server Escape an Underscore
I had a similar issue using like pattern '%_%'
did not work - as the question indicates :-)
Using '%\_%'
did not work either as this first \
is interpreted "before the like".
Using '%\\_%'
works. The \\
(double backslash) is first converted to single \
(backslash) and then used in the like pattern.
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 '^';
T-SQL Reference for LIKE:
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 following table shows several examples of using the LIKE keyword and the [ ] wildcard characters.
For your case:
... LIKE '%[_]d'