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

sql, sql-like, sql-server

Solution

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

Problem

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?

Original source

Related problems