How can I escape square brackets in a LIKE clause?

后端 未结 10 1904
被撕碎了的回忆
被撕碎了的回忆 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:57

    There is a problem in that whilst:

    LIKE 'WC[[]R]S123456' 
    

    and:

    LIKE 'WC\[R]S123456' ESCAPE '\'
    

    Both work for SQL Server but neither work for Oracle.

    It seems that there is no ISO/IEC 9075 way to recognize a pattern involving a left brace.

    0 讨论(0)
  • 2020-11-22 15:02

    According to documentation:

    You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets.

    You need to escape these three characters %_[:

    '5%'      LIKE '5[%]'      -- true
    '5$'      LIKE '5[%]'      -- false
    'foo_bar' LIKE 'foo[_]bar' -- true
    'foo$bar' LIKE 'foo[_]bar' -- false
    'foo[bar' LIKE 'foo[[]bar' -- true
    'foo]bar' LIKE 'foo]bar'   -- true
    
    0 讨论(0)
  • 2020-11-22 15:05

    If you would need to escape special characters like '_' (underscore), as it was in my case, and you are not willing/not able to define an ESCAPE clause, you may wish to enclose the special character with square brackets '[' and ']'.

    This explains the meaning of the "weird" string '[[]' - it just embraces the '[' character with square brackets, effectively escaping it.

    My use case was to specify the name of a stored procedure with underscores in it as a filter criteria for the Profiler. So I've put string '%name[_]of[_]a[_]stored[_]procedure%' in a TextData LIKE field and it gave me trace results I wanted to achieve.

    Here is a good example from the documentation: LIKE (Transact-SQL) - Using Wildcard Characters As Literals

    0 讨论(0)
  • 2020-11-22 15:06
    LIKE 'WC[[]R]S123456' 
    

    or

    LIKE 'WC\[R]S123456' ESCAPE '\'
    

    Should work.

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