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 example: WC[R]S123456
.
If I do a LIKE 'WC[R]S123456'
it will not return anything.
I found some information on using the ESCAPE
keyword with LIKE
but I do not understand how to use it to treat the square brackets as a regular string.
or
Should work.
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[[]
.According to documentation:
You need to escape these three characters
%_[
: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 "[".
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.
To search start with string
To search end with string
To search contain with string
and so on for other pattern matching. But direct user input needs to format as mentioned above.
Here is what I actually used:
I needed to exclude names that started with an underscore from a query, so I ended up with this: