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 can do it like this: specify an explicit escape character in your SQL string, and then place that escape in front of all %
and _
characters inside the string the user enters:
SqlCommand findProcutsByPattern = new SqlCommand(
@"SELECT *
FROM [Products]
WHERE ProductName LIKE @pattern", connection) ESCAPE '_'"
When you set the parameter, replace all instances of _
and %
with __
and _%
:
var escapedPattern = Regex.Replace(pattern, "[%_]", "_$0");
Demo.