在經典 ASP 開發中,快速取得資料表符合條件的行數是常見需求。利用系統預存程序 sp_spaceused 可高效獲取資料表總行數;若需條件篩選,則需自行撰寫 COUNT(*) 查詢。本文提供兩種函數實作。
sp_spaceused 回傳資料表空間使用資訊,包含 rows 欄位即為總行數,速度極快(不掃描資料列)。
<%
'===============================================================
' GetTblRows - 取得資料表總行數
' 參數:TblName - 資料表名稱
' 回傳:行數 (字串),錯誤時回傳錯誤訊息
'===============================================================
Function GetTblRows(TblName)
If TblName = "" Then
GetTblRows = "錯誤:未指定資料表名稱"
Exit Function
End If
Dim rs, sql
Set rs = Server.CreateObject("ADODB.Recordset")
sql = "EXEC sp_spaceused " & TblName
rs.Open sql, conn, 1, 1 ' adOpenKeyset, adLockReadOnly
If Not rs.EOF Then
GetTblRows = Trim(rs("rows"))
Else
GetTblRows = "0"
End If
rs.Close
Set rs = Nothing
End Function
%>
<!-- 頁面中直接輸出 -->
<%= GetTblRows("Products") %>
當需要依條件統計時(如「狀態=啟用的商品數」),必須使用 SELECT COUNT(*)。
<%
'===============================================================
' GetConditionalRowCount - 依條件取得行數
' 參數:
' TableName - 資料表名稱
' WhereClause - WHERE 條件(不含 WHERE 關鍵字),如 "Status=1 AND CategoryID=5"
' 回傳:長整數行數
'===============================================================
Function GetConditionalRowCount(TableName, WhereClause)
If TableName = "" Then
Err.Raise vbObjectError + 513, "GetConditionalRowCount", "資料表名稱不可為空"
End If
Dim rs, sql
Set rs = Server.CreateObject("ADODB.Recordset")
If WhereClause = "" Then WhereClause = "1=1"
sql = "SELECT COUNT(*) AS RowCount FROM " & TableName & " WHERE " & WhereClause
rs.Open sql, conn, 1, 1
If Not rs.EOF Then
GetConditionalRowCount = CLng(rs("RowCount"))
Else
GetConditionalRowCount = 0
End If
rs.Close
Set rs = Nothing
End Function
%>
<%
Dim activeCount
activeCount = GetConditionalRowCount("Products", "Status=1 AND CategoryID=5")
Response.Write "啟用中的商品數:" & activeCount
%>
| 方法 | 適用場景 | 效能 | 備註 |
|---|---|---|---|
sp_spaceused |
全表總行數、空間資訊 | 極快 (O(1),讀取系統目錄) | 不支援 WHERE 條件 |
COUNT(*) |
條件篩選統計 | 需掃描索引/資料表 | 加上 WHERE 欄位索引可大幅加速 |
Recordset.RecordCount |
已開啟 Recordset 時 | 視游標類型而定 | 前進游標不可靠,建議改用 COUNT(*) |
conn 應為有效開啟的 ADODB.Connection,建議使用連線池與全域連線管理。On Error Resume Next 捕獲資料庫錯誤,記錄日誌並回傳預設值。TableName、WhereClause 若源自用戶輸入,嚴格驗證白名單或使用參數化查詢(COUNT 查詢可參數化條件值,但資料表名無法參數化)。