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

后端 未结 8 1929
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 02:29

I have an SQL query as below.

Select * from table 
where name like \'%\' + search_criteria + \'%\' 

If search_criteria = \'abc\', it will r

相关标签:
8条回答
  • 2020-12-03 02:59

    You need to escape it: on many databases this is done by preceding it with backslash, \%.

    So abc becomes abc\%.

    Your programming language will have a database-specific function to do this for you. For example, PHP has mysql_escape_string() for the MySQL database.

    0 讨论(0)
  • 2020-12-03 02:59

    May be this one help :)

    DECLARE @SearchCriteria VARCHAR(25)
    SET  @SearchCriteria = 'employee'
    IF CHARINDEX('%', @SearchCriteria) = 0
    BEGIN
    SET @SearchCriteria = '%' + @SearchCriteria + '%'
    END
    SELECT * 
    FROM Employee
    WHERE Name LIKE @SearchCriteria
    
    0 讨论(0)
  • 2020-12-03 03:08

    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, '%', '[%]') + '%'
    
    0 讨论(0)
  • 2020-12-03 03:09

    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

    0 讨论(0)
  • 2020-12-03 03:09

    Escape the percent sign \% to make it part of your comparison value.

    0 讨论(0)
  • 2020-12-03 03:18

    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.

    0 讨论(0)
提交回复
热议问题