I have a table containing products. I need to make a query finding all the matching results to an user-input value. I am using SqlParameter for the insertion of
You have two options:
enclose them in [ and ]. So:
where pattern like '[%]'
Looks for the percentage character.
Full list of characters to escape - '_', '%', '[', ']' with corresponding replacements '[_]', '[%]', '[[]', '[]]'. Sample code can be found in Escaping the escape character does not work – SQL LIKE Operator
use an escape character that is unlikely to be in the string, such as a backtick:
where pattern like '`%' escape '`'
(See the syntax on MSDN - LIKE (Transact-SQL).)
In both cases, I would suggest that you make the substitution in the application layer, but you can also do it in SQL if you really want:
where pattern like replace(@pattern, '%', '[%]')
And, giving the end-user access to wildcards may be a good thing in terms of the user interface.
Note: there are couple more special characters '-' and '^' in the LIKE query, but they don't need to be escaped if you are already escaping '[' and ']'.