假如我想模糊查询一个字段中带有百分号“%”
模糊查询我们一般都这么写
select * from student where address like '%待查询的字符串%'
如果 待查询的字符串==% 那么
select * from student where address like '%%%'
结果导致把表中的所有的行就查询出来了,没有达到预期效果后来考虑到使用函数charindex(),也是可以解决的,但是如果这样一来like岂不是要被抛弃掉了?
请高手们赐教?

解决方案 »

  1.   

    可以将通配符模式匹配字符串用作文字字符串,方法是将通配符放在括号中。下表显示了使用 LIKE 关键字和 [ ] 通配符的示例。符号 含义 
    LIKE '5[%]' 5% 
    LIKE '[_]n' _n 
    LIKE '[a-cdf]' a、b、c、d 或 f 
    LIKE '[-acdf]' -、a、c、d 或 f 
    LIKE '[ [ ]' [ 
    LIKE ']' ] 
    LIKE 'abc[_]d%' abc_d 和 abc_de 
    LIKE 'abc[def]' abcd、abce 和 abcf 
      

  2.   

    使用 ESCAPE 子句的模式匹配
    可搜索包含一个或多个特殊通配符的字符串。例如,customers 数据库中的 discounts 表可能存储含百分号 (%) 的折扣值。若要搜索作为字符而不是通配符的百分号,必须提供 ESCAPE 关键字和转义符。例如,一个样本数据库包含名为 comment 的列,该列含文本 30%。若要搜索在 comment 列中的任何位置包含字符串 30% 的任何行,请指定由 WHERE comment LIKE '%30!%%' ESCAPE '!' 组成的 WHERE 子句。如果不指定 ESCAPE 和转义符,SQL Server 将返回所有含字符串 30 的行。下例说明如何在 pubs 数据库 titles 表的 notes 列中搜索字符串"50% off when 100 or more copies are purchased":USE pubs
    GO
    SELECT notes
    FROM titles
    WHERE notes LIKE '50%% off when 100 or more copies are purchased' 
       ESCAPE '%'
    GO
      

  3.   

    declare @s table (address varchar(18))
    Insert into @s
    select 'dfdfdf'
    union select 'dfd%888888'
    union select 'ooooooooo'select * from @s where address like '%[%]%' --[]引起来
      

  4.   

    declare @t table(id int identity(1,1),name varchar(20))
    insert @t(name)
    select '123%456' union all
    select '123%%456' union all
    select '123456' select * from @t where name like '%[%]%'             /*使用界定符*/
    select * from @t where name like '%!%%' escape '!'   /*使用转义符*//*
    id    name
    1     123%456
    2     123%%456
    */