[英]MS Access SQL pagination with a query (no unique identifier) or ROW_NUMBER?
我試圖一次從SQL查詢中獲取100行並將其用於分頁。 該查詢從具有100,000+行的表中返回約2000行。 但是,該表沒有唯一的標識符。
SELECT TOP 100 * FROM tbl_Items WHERE tbl_Items.Repair_Required = true
我已經研究過使用ROW_NUMBER,但似乎在MS Access中不可用。 我還研究了如何使用“自我連接”來創建自定義row_number,正如Gord Thompson在此處回答的那樣: 訪問查詢在T-SQL中產生類似ROW_NUMBER()的結果 。 但是,將我的100,000+表與自身連接起來在性能上並不容易。
我有什么選擇?
這是一個使用集合的方法,它的運行速度非常快:
Public Function RowCounter( _
ByVal strKey As String, _
ByVal booReset As Boolean, _
Optional ByVal strGroupKey As String) _
As Long
' Builds consecutive RowIDs in select, append or create query
' with the possibility of automatic reset.
' Optionally a grouping key can be passed to reset the row count
' for every group key.
'
' Usage (typical select query):
' SELECT RowCounter(CStr([ID]),False) AS RowID, *
' FROM tblSomeTable
' WHERE (RowCounter(CStr([ID]),False) <> RowCounter("",True));
'
' The Where statement resets the counter when the query is run
' and is needed for browsing a select query.
'
' Usage (typical append query, manual reset):
' 1. Reset counter manually:
' Call RowCounter(vbNullString, False)
' 2. Run query:
' INSERT INTO tblTemp ( RowID )
' SELECT RowCounter(CStr([ID]),False) AS RowID, *
' FROM tblSomeTable;
'
' Usage (typical append query, automatic reset):
' INSERT INTO tblTemp ( RowID )
' SELECT RowCounter(CStr([ID]),False) AS RowID, *
' FROM tblSomeTable
' WHERE (RowCounter("",True)=0);
'
' 2002-04-13. Cactus Data ApS. CPH
' 2002-09-09. Str() sometimes fails. Replaced with CStr().
' 2005-10-21. Str(col.Count + 1) reduced to col.Count + 1.
' 2008-02-27. Optional group parameter added.
Static col As New Collection
Static strGroup As String
On Error GoTo Err_RowCounter
If booReset = True Or strGroup <> strGroupKey Then
Set col = Nothing
strGroup = strGroupKey
Else
col.Add col.Count + 1, strKey
End If
RowCounter = col(strKey)
Exit_RowCounter:
Exit Function
Err_RowCounter:
Select Case Err
Case 457
' Key is present.
Resume Next
Case Else
' Some other error.
Resume Exit_RowCounter
End Select
End Function
請研究在線注釋和示例。
當然,您可以將其應用於具有2000條記錄的查詢,而不是源表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.