I have an SQL query as below.
Select * from table
where name like '%' + search_criteria + '%'
If search_criteria = 'abc', it will return data containing xxxabcxxxx
which is fine.
But if my search_criteria = 'abc%', it will still return data containing xxxabcxxx
, which should not be the case.
How do I handle this situation?
To escape a character in sql you can use
!
:EXAMPLE - USING ESCAPE CHARACTERS
It is important to understand how to "Escape Characters" when pattern matching. These examples deal specifically with escaping characters in Oracle.
Let's say you wanted to search for a % or a _ character in the SQL LIKE condition. You can do this using an Escape character.
Please note that you can only define an escape character as a single character (length of 1).
For example:
This SQL LIKE condition example identifies the ! character as an escape character. This statement will return all suppliers whose name is %.
Here is another more complicated example using escape characters in the SQL LIKE condition.
This SQL LIKE condition example returns all suppliers whose name starts with H and ends in %. For example, it would return a value such as 'Hello%'.
You can also use the escape character with the _ character in the SQL LIKE condition.
For example:
This SQL LIKE condition example returns all suppliers whose name starts with H and ends in _ . For example, it would return a value such as 'Hello_'.
Reference: sql/like
If you want a
%
symbol insearch_criteria
to be treated as a literal character rather than as a wildcard, escape it to[%]
Escape the percent sign
\%
to make it part of your comparison value.The easiest solution is to dispense with "like" altogether:
I prefer charindex over like. Historically, it had better performance, but I'm not sure if it makes much of difference now.
May be this one help :)
Use an escape clause:
Result
You can set your escape character to whatever you want. In this case, the default '\'. The escaped '\%' becomes a literal, the second '%' is not escaped, so again wild card.
See List of special characters for SQL LIKE clause