ASP多条件查询功能实现代码(多关键词查询)(3)


Name=request("Name")
Tel=request("Tel")
School=request("School")
'枚举法的搜索核心,因为有3个条件所以要写8组If判断语句
if trim(Name)="" and trim(Tel)="" and trim(School)="" then
sql="select * from address order by ID asc"
end if
if trim(Name)="" and trim(Tel)="" and trim(School)<>"" then
sql="select * from address where School like '%"&trim(School)&"%' order by ID asc"
end if
if trim(Name)="" and trim(Tel)<>"" and trim(School)="" then
sql="select * from address where Tel like '%"&trim(Tel)&"%' order by ID asc"
end if
if trim(Name)="" and trim(Tel)<>"" and trim(School)<>"" then
sql="select * from address where Tel like '%"&trim(Tel)&"%' and School like '%"&trim(School)&"%' order by ID asc"
end if
if trim(Name)<>"" and trim(Tel)="" and trim(School)="" then
sql="select * from address where Name like '%"&trim(Name)&"%' order by ID asc"
end if
if trim(Name)<>"" and trim(Tel)="" and trim(School)<>"" then
sql="select * from address where Name like '%"&trim(Name)&"%' and School like '%"&trim(School)&"%' order by ID asc"
end if
if trim(Name)<>"" and trim(Tel)<>"" and trim(School)="" then
sql="select * from address where Name like '%"&trim(Name)&"%' and Tel like '%"&trim(Tel)&"%' order by ID asc"
end if
if trim(Name)<>"" and trim(Tel)<>"" and trim(School)<>"" then
sql="select * from address where Name like '%"&trim(Name)&"%' and Tel like '%"&trim(Tel)&"%' and School like '%"&trim(School)&"%' order by ID asc"
end if
rs.open sql,conn,1,1
'显示搜索结果
if rs.eof and rs.bof then
response.write "目前通讯录中没有记录"
else
do while not rs.eof
response.write "姓名:"&rs("Name")&"电话:"&rs("Tel")&"学校:"&rs("School")&"<br>"
rs.movenext
loop
end if
'断开数据库
set rs=nothing
conn.close
set conn=nothing
%>

理解上述程序时,着重琢磨核心部分,8组语句一一对应了3个搜索框中的8种状态

Name Tel School
空 空 空
空 空 非空
空 非空 空
空 非空 非空
非空 空 空
非空 空 非空
非空 非空 空
非空 非空 非空

另外trim()是VB的函数,将输入的字符串前后的空格去掉;%是SQL语言中的多字符通配符(_是单字符通配符),由此可见%"&trim()&"%对搜索框中输入的关键字是分别向左向右匹配的;SQL语言中用and连接说明非空条件之间是“与”关系。

再来看看递进法,与枚举法相比它们只有核心部分不同:
'递进法的搜索核心,依次判断条件为空否,非空则将其加入搜索条件

复制代码 代码如下:

sql="select * from address where"
if Name<>"" then
sql=sql&" Name like '%"&Name&"%' "
flag=1
end if
if Tel<>"" and flag=1 then
sql=sql&" and Tel like '%"&Tel&"%'"

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/2008.html