How to escape a string for use with the LIKE operator in SQL Server?

后端 未结 7 1380
半阙折子戏
半阙折子戏 2020-12-15 07:59

I am looking for something that works in SQL Server similar to the @ symbol in c# which causes a string to be taken as it\'s literal. Eg:

strin         


        
相关标签:
7条回答
  • 2020-12-15 08:25

    I'd sanitize the string in the front-end application rather than try and do hokey stuff in SQL to work around this.

    0 讨论(0)
  • 2020-12-15 08:31

    To search for "%" as a literal not wildcard in a string, it needs escaped as [%].

    Now, SQL Server only need 3 characters escaping: % _ [

    So, create a scalar udf to wrap this:

    REPLACE(REPLACE(REPLACE(@myString, '[', '[[]'), '_', '[_]'), '%', '[%]')
    

    Because of the simplicity (aka: very limited) pattern matching in SQL, nothing more complex is needed...

    0 讨论(0)
  • 2020-12-15 08:33

    From the docs:

    Syntax

    match_expression [ NOT ] LIKE pattern [ ESCAPE escape_character ]

    Use the ESCAPE option like so:

    SELECT [Name] 
      FROM [Test] 
     WHERE [Name] LIKE (REPLACE(@searchText, '%', '%%') + '%') ESCAPE '%'
    
    0 讨论(0)
  • 2020-12-15 08:34

    In TSQL, you can wrap the % and _ characters in brackets like so [%] [_] this tells SQL to treat them as literals.

    I have tested and verified this works in SQL Server 7.0, 2000, and 2005.

    http://msdn.microsoft.com/en-us/library/aa933232(SQL.80).aspx

    0 讨论(0)
  • 2020-12-15 08:42

    Each character to be treated literally should be enclosed in square brackets. A right bracket is taken literally directly so don't enclose that one.

    0 讨论(0)
  • 2020-12-15 08:45

    If you parameterize your query you don't need to worry about it.

    UPDATE

    As recursive stated in the comments, % still needs to be escaped even in parameterized queries, I didn't realize linq to sql was doing it automagically when I tested.

    You can use ESCAPE 'x' where x is the character you wish to be the escape character. Linq to SQL does it like this

    WHERE [Name] LIKE @searchText ESCAPE '~'

    where @searchText = [some text with a~% character%]

    or as others have stated it can be escaped with [%]

    view the documentation

    0 讨论(0)
提交回复
热议问题