Why does using an Underscore character in a LIKE filter give me all the results?

后端 未结 6 1693
我在风中等你
我在风中等你 2020-11-29 00:52

I wrote the below SQL query with a LIKE condition:

SELECT * FROM Manager
WHERE managerid LIKE \'_%\'
AND managername LIKE \'%_%\'
6条回答
  •  野性不改
    2020-11-29 01:22

    As you want to specifically search for a wildcard character you need to escape that

    This is done by adding the ESCAPE clause to your LIKE expression. The character that is specified with the ESCAPE clause will "invalidate" the following wildcard character.

    You can use any character you like (just not a wildcard character). Most people use a \ because that is what many programming languages also use

    So your query would result in:

    select * 
    from Manager
    where managerid LIKE '\_%' escape '\'
    and managername like '%\_%' escape '\';
    

    But you can just as well use any other character:

    select * 
    from Manager
    where managerid LIKE '#_%' escape '#'
    and managername like '%#_%' escape '#';
    

    Here is an SQLFiddle example: http://sqlfiddle.com/#!6/63e88/4

提交回复
热议问题