How can I escape square brackets in a LIKE clause?

后端 未结 10 1903
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 14:28

I am trying to filter items with a stored procedure using like. The column is a varchar(15). The items I am trying to filter have square brackets in the name.

For ex

相关标签:
10条回答
  • 2020-11-22 14:39

    Instead of '\' or another character on the keyboard, you can also use special characters that aren't on the keyboard. Depending o your use case this might be necessary, if you don't want user input to accidentally be used as an escape character.

    0 讨论(0)
  • 2020-11-22 14:43

    I needed to exclude names that started with an underscore from a query, so I ended up with this:

    WHERE b.[name] not like '\_%' escape '\'  -- use \ as the escape character
    
    0 讨论(0)
  • 2020-11-22 14:43

    Here is what I actually used:

    like 'WC![R]S123456' ESCAPE '!'
    
    0 讨论(0)
  • 2020-11-22 14:43

    The ESCAPE keyword is used if you need to search for special characters like % and _, which are normally wild cards. If you specify ESCAPE, SQL will search literally for the characters % and _.

    Here's a good article with some more examples

    SELECT columns FROM table WHERE 
        column LIKE '%[[]SQL Server Driver]%' 
    
    -- or 
    
    SELECT columns FROM table WHERE 
        column LIKE '%\[SQL Server Driver]%' ESCAPE '\'
    
    0 讨论(0)
  • 2020-11-22 14:44

    Use Following.

    For user input to search as it is, use escape, in that it will require following replacement for all special characters (below covers all of SQL Server).

    Here single quote "'" is not taken as it does not affect like clause as It is a matter of string concatenation.

    "-" & "^" & "]" replace is not required as we are escaping "[".

    String FormattedString = "UserString".Replace("ð","ðð").Replace("_", "ð_").Replace("%", "ð%").Replace("[", "ð[");
    

    Then, in SQL Query it should be as following. (In parameterised query, string can be added with patterns after above replacement).

    To search exact string.

    like 'FormattedString' ESCAPE 'ð'
    

    To search start with string

    like '%FormattedString' ESCAPE 'ð'
    

    To search end with string

    like 'FormattedString%' ESCAPE 'ð'
    

    To search contain with string

    like '%FormattedString%' ESCAPE 'ð'
    

    and so on for other pattern matching. But direct user input needs to format as mentioned above.

    0 讨论(0)
  • 2020-11-22 14:49

    Let's say you want to match the literal its[brac]et.

    You don't need to escape the ] as it has special meaning only when it is paired with [.

    Therefore escaping [ suffices to solve the problem. You can escape [ by replacing it with [[].

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