使用 SQL COUNT 方法的一个简单解决方案。这假设您需要行数而不是数据本身。
<%
Set rsscroll = Server.CreateObject("ADODB.Recordset")
Dim strSQLscroll, rsscroll, intRow
strSQLscroll = "SELECT COUNT(*) AS Total FROM tblItems WHERE expiration_date > getdate();"
rsscroll.open strSQLscroll, oConn
response.write rsscroll("Total")
rsscroll.close: set rsscroll = nothing
oConn.close: set oConn = nothing
%>
这会返回一行,其中包含一个名为“Total”的值。 (如果您同时需要行数 和 数据,请继续阅读。)
您的查询代码使用默认的 RecordSet,它以“仅转发”模式返回数据以提高效率。它将逐行执行,但不知道实际计数。 (此模式还将 RecordSet.RecordCount 设置为 -1,因此该字段对您没有用处。)
RecordSet.Open 的“Cursor Type”参数允许您更改为“Keyset”模式(参数值 1),确实将 RecordCount 字段设置为数据行数。 (为了完整起见,“锁定类型”和“命令类型”参数包括在内,但它们并未包含在此答案中。)
RecordsetObject.Open "TableName|SQLStatement", ConnectionObject [,Cursor Type] [,Lock Type] [,Command Type]
将此参数添加到代码的 RecordSet.Open 调用中,然后检查 RecordCount。
<%
Set rsscroll = Server.CreateObject("ADODB.Recordset")
Dim strSQLscroll, rsscroll, intRow
strSQLscroll = "SELECT * FROM tblItems where expiration_date > getdate() order by expiration_date desc;"
rsscroll.open strSQLscroll, oConn, 1
intRow = rsscroll.RecordCount
' ... do something with intRow
rsscroll.close: set rsscroll = nothing
oConn.close: set oConn = nothing
%>
如果数据库性能对您的情况有任何影响,那么 RecordSet.GetRows() 方法的效率要高得多。
<%
Dim rsscroll, intRow, rsArray
Set oConn = CreateObject("ADODB.Connection")
oConn.open "<connection string>"
strSQLscroll = "SELECT * FROM tblItems where expiration_date > getdate() order by expiration_date desc"
Set rsscroll = conn.execute(strSQLscroll)
if not rsscroll.eof then
rsArray = rsscroll.GetRows()
intRow = UBound(rsArray, 2) + 1
response.write "rows returned: " & intRow
' ... do any other operations here ...
end if
rsscroll.close: set rsscroll = nothing
oConn.close: set oConn = nothing
%>