日期:2013-12-23  浏览次数:20921 次

  运行环境:IIS脚本语言:VBScript数据库:Access/SQL Server数据库语言:SQL 1.概要:
不论是在论坛,还是新闻系统,或是下载系统等动态网站中,大家经常会看到搜索功能:搜索帖子,搜索用户,搜索软件(总之搜索关键字)等,本文则是介绍如何建立一个高效实用的,基于ASP的站内多值搜索。

本文面对的是“多条件模糊匹配搜索”,理解了多条件的,单一条件搜索也不过小菜一碟了。一般来讲,有两种方法进行多条件搜索:枚举法递进法。搜索条件不太多时(n<=3),可使用枚举法,其语句频度为2的n次方,成指数增长,n为条件数。很明显,当条件增多以后,无论从程序的效率还是可实现性考虑都应采用递进法,其语句频度为n,成线性增长。需要指出的是,枚举法思路非常简单,一一判断条件是否为空,再按非空条件搜索,同时可以利用真值表技术来对付条件极多的情况(相信没人去干这种事,4条件时就已经要写16组语句了);递进法的思想方法较为巧妙,重在理解,其巧就巧在一是使用了标志位(flag),二是妙用SQL中字符串连接符&。下面以实例来讲解引擎的建立。

2.实例:
我们建立一通讯录查询引擎,数据库名为addressbook.mdb,表名为address,字段如下:

IDNameTelSchool1张 三33333333电子科技大学计算机系2李 四44444444四川大学生物系3王 二22222222西南交通大学建筑系…………
Web搜索界面如下:

姓名:电话:学校:搜索按钮
采用枚举法的源程序如下:<%@ CODEPAGE = "936" %>'连接数据库<%dim conn  dim DBOathdim rsdim sql  Set conn=Server.CreateObject("ADODB.Connection")  DBPath = Server.MapPath("addressbook.mdb")  conn.Open "driver={Microsoft Access Driver (*.mdb)};dbq=" & DBPathSet rs=Server.CreateObject("ADODB.Recordset")'从Web页获取姓名、电话、学校的值dim Namedim Teldim SchoolName=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 ifrs.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   loopend if'断开数据库set rs=nothing           conn.close        set conn=nothing%>

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

NameTelSchool空空空空空非空空非空空空非空非空非空空空非空空