经常在论坛上碰到一些新学ASP开发的朋友咨询如何通过查询按类别输出数据,而通常用的方法是先查询出各类别,然后通过循环一个一个的再查询出该类别的数据输出。这个办法是最简单的,但是也是比较耗费资源和效率比较低的。下面我介绍两个方法,都是只查询一次就可以输出的,希望对大家有所帮助。
- <%@Language=VBScript CodePage=936%>
- <%
- Option Explicit
- dim conn,rs,currentClassname
- Set Conn=Server.CreateObject("ADODB.Connection")
- conn.Open "Driver={Microsoft Access Driver (*.mdb)};Dbq= test.mdb;"
- set rs=conn.execute("select id,classname,title from test order by classname,title")
- currentClassname=""
- do while not rs.eof
- if currentClassname<>rs("classname") then
- if currentClassname="" then
- response.write "<table>" & vbcrlf
- else
- response.write "</table><br /><table>" & vbcrlf
- end if
- currentClassname=rs("classname")
- response.write "<tr><td align='center' style='font-weight:bold;'>"¤tClassname&"</td></tr>"& vbcrlf
- end if
- response.write "<tr><td><a href='test.asp?id="&rs("id")&"'>"&rs("title")&"</a></td></tr>"& vbcrlf
- rs.movenext
- loop
- response.write "</table>"& vbcrlf
- %>
- rs.close
- set rs=nothing
- conn.close
- set conn=nothing
Shape 命令可以包含子句,指定针对基本数据提供者并将返回 Recordset 对象的查询命令。查询的语法取决于对基本数据提供者的要求。虽然 ADO 并不要求使用任何指定的查询语言,但通常是使用结构化查询语言 (SQL)。
然后我们可以写出如下代码:
- <%@Language=VBScript CodePage=936%>
- <%
- Option Explicit
- dim conn,rs,rschapClassname
- Set Conn=Server.CreateObject("ADODB.Connection")
- conn.Open "Provider=MSDataShape;Data Provider=MSDASQL;Driver={Microsoft Access Driver (*.mdb)};Dbq=D:/projects/homepage/test/sample1/test.mdb;"
- set rs=conn.execute( "SHAPE {select DISTINCT classname from test order by classname }" & vbcrlf & _
- "APPEND ({select id,title,classname from test} " & vbcrlf & _
- "RELATE classname TO classname) AS chapClassname")
- do while not rs.eof
- response.write "<table>" & vbcrlf & _
- "<tr><td align='center' style='font-weight:bold;'>"&rs("classname")&"</td></tr>"& vbcrlf
- set rschapClassname=rs("chapClassname").value
- do while not rschapClassname.eof
- response.write "<tr><td><a href='test.asp?id="&rschapClassname("id")&"'>"&rschapClassname("title")&"</a></td></tr>"& vbcrlf
- rschapClassname.movenext
- loop
- response.write "</table>" & vbcrlf
- rs.movenext
- loop
- rschapClassname.close
- set rschapClassname=nothing
- rs.close
- set rs=nothing
- conn.close
- set conn=nothing
在以上代码中我们要注意的有点: