[英]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.