Escaping special characters in a SQL LIKE statement using sql parameters

后端 未结 4 1113
小鲜肉
小鲜肉 2020-12-11 21:25

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

4条回答
  •  囚心锁ツ
    2020-12-11 22:23

    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.

提交回复
热议问题