Escaping special characters in a SQL LIKE statement using sql parameters

后端 未结 4 1124
小鲜肉
小鲜肉 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:00

    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 ']'.

提交回复
热议问题