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

标题: SQL模糊查询 [打印本页]

作者: qc1125    时间: 2006-4-25 09:17
标题: SQL模糊查询
<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>
作者: 废话大仙    时间: 2006-5-10 20:03
8错,呵呵,楼主描述的是标准sql嘛,是否通用于所有数据库?




欢迎光临 信息系统项目管理师_2024年软考学习应考交流_信息系统项目管理师考试 (http://bbs.tuandui.org.cn/) Powered by Discuz! X3.2