SQL 'LIKE' query using '%' where the search criteria contains '%'

pratik picture pratik · May 29, 2012 · Viewed 375.4k times · Source

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?

Answer

Alex K. picture Alex K. · May 29, 2012

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, '%', '[%]') + '%'