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?
The SQL LIKE Operator The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.
%s is a placeholder used in functions like sprintf. Check the manual for other possible placeholders. $sql = sprintf($sql, "Test"); This would replace %s with the string "Test".
Using the LIKE operator, you can specify single or multiple conditions. This allows you to perform an action such as select, delete, and updating any columns or records that match the specified conditions. It is mainly paired with a where clause to set the conditions.
If you want a %
symbol in search_criteria
to be treated as a literal character rather than as a wildcard, escape it to [%]
... where name like '%' + replace(search_criteria, '%', '[%]') + '%'
Use an escape clause:
select *
from (select '123abc456' AS result from dual
union all
select '123abc%456' AS result from dual
)
WHERE result LIKE '%abc\%%' escape '\'
Result
123abc%456
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
The easiest solution is to dispense with "like" altogether:
Select *
from table
where charindex(search_criteria, name) > 0
I prefer charindex over like. Historically, it had better performance, but I'm not sure if it makes much of difference now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With