信息系统项目管理师_2024年软考学习应考交流_信息系统项目管理师考试

 找回密码
 马上注册

QQ登录

只需一步,快速开始

查看: 3153|回复: 1
打印 上一主题 下一主题

SQL模糊查询

  [复制链接]

该用户从未签到

跳转到指定楼层
楼主
发表于 2006-4-25 09:17:34 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
<span id="post1" style="FONT-SIZE: 12px; COLOR: #000000;"><span id="post1" style="FONT-SIZE: 12px; COLOR: #000000;">SQL模糊查询<br/><br/><br/>&nbsp; &nbsp;SQL模糊查询的语法为<br/>&nbsp; &nbsp;“SELECT column FROM table WHERE column LIKE 'pattern'”。<br/>&nbsp; &nbsp;<br/>&nbsp; &nbsp;SQL提供了四种匹配模式:<br/>&nbsp; &nbsp;1. % 表示任意0个或多个字符。如下语句:<br/>&nbsp; &nbsp; &nbsp; &nbsp;SELECT * FROM user WHERE name LIKE '%三%'<br/>&nbsp; &nbsp;将会把name为“张三”,“三脚猫”,“唐三藏”等等有“三”的全找出来;<br/>&nbsp; &nbsp;<br/>&nbsp; &nbsp;2. _ 表示任意单个字符。语句:<br/>&nbsp; &nbsp; &nbsp; &nbsp;SELECT * FROM user WHERE name LIKE '_三_'<br/>&nbsp; &nbsp;只找出“唐三藏”这样name为三个字且中间一个字是“三”的;<br/>&nbsp; &nbsp; &nbsp; &nbsp;SELECT * FROM user WHERE name LIKE '三__'<br/>&nbsp; &nbsp;只找出“三脚猫”这样name为三个字且第一个字是“三”的;<br/>&nbsp; &nbsp;<br/>&nbsp; &nbsp;3. [ ] 表示括号内所列字符中的一个(类似与正则表达式)。语句:<br/>&nbsp; &nbsp; &nbsp; &nbsp;SELECT * FROM user WHERE name LIKE '[张李王]三'<br/>&nbsp; &nbsp;将找出“张三”、“李三”、“王三”(而不是“张李王三”);<br/>&nbsp; &nbsp; &nbsp; &nbsp;<br/>&nbsp; &nbsp;如 [ ] 内有一系列字符(01234、abcde之类的)则可略写为“0-4”、“a-e”<br/>&nbsp; &nbsp; &nbsp; &nbsp;SELECT * FROM user WHERE name LIKE '老[1-9]'<br/>&nbsp; &nbsp;将找出“老1”、“老2”、……、“老9”;<br/>&nbsp; &nbsp;如要找“-”字符请将其放在首位:'张三[-1-9]'<br/>&nbsp; &nbsp;<br/>&nbsp; &nbsp;4. [^ ] 表示不在括号所列之内的单个字符。语句:<br/>&nbsp; &nbsp; &nbsp; &nbsp;SELECT * FROM user WHERE name LIKE '[^张李王]三'<br/>&nbsp; &nbsp;将找出不姓“张”、“李”、“王”的“赵三”、“孙三”等;<br/>&nbsp; &nbsp; &nbsp; &nbsp;SELECT * FROM user WHERE name LIKE '老[^1-4]'<br/>&nbsp; &nbsp;将排除“老1”到“老4”寻找“老5”、“老6”、……、“老9”。<br/>&nbsp; &nbsp;<br/>&nbsp; &nbsp;!最后是重点!<br/>&nbsp; &nbsp;由于通配符的缘故,导致我们查询特殊字符“%”、“_”、“[”、“'”的语句无法正常实现,而把特殊字符用“[ ]”括起便可正常查询。据此我们写出以下函数:<br/>&nbsp; &nbsp;<br/>&nbsp; &nbsp;function sqlencode(str)<br/>&nbsp; &nbsp; str=replace(str,"'","''")<br/>&nbsp; &nbsp; str=replace(str,"[","[[]") '此句一定要在最先<br/>&nbsp; &nbsp; str=replace(str,"_","[_]")<br/>&nbsp; &nbsp; str=replace(str,"%","[%]")<br/>&nbsp; &nbsp; sqlencode=str<br/>&nbsp; &nbsp;end function<br/>&nbsp; &nbsp;<br/>&nbsp; &nbsp;在查询前将待查字符串先经该函数处理即可。<br/></span></span>
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 转播转播 分享分享 顶 踩
  • TA的每日心情
    慵懒
    2014-11-5 09:39
  • 签到天数: 281 天

    [LV.8]以坛为家I

    沙发
    发表于 2006-5-10 20:03:32 | 只看该作者
    8错,呵呵,楼主描述的是标准sql嘛,是否通用于所有数据库?
    您需要登录后才可以回帖 登录 | 马上注册

    本版积分规则

    小黑屋|手机版|Archiver|信息系统项目管理师_软考交流平台. ( 鄂ICP备11002878号-1  公安备案号:42011102001150

    GMT+8, 2025-7-7 07:21

    Software by Discuz! X3.2

    © 2001-2013 SKIN BY DSVUE

    快速回复 返回顶部 返回列表