Access function or expression equivalent of SQL RO

2019-02-25 07:30发布

问题:

Is there anything I can do in Access that would mimic the behavior of the TSQL ROW_NUMBER() function, when doing an INSERT query?

回答1:

An oldie but goodie:

How to Rank Records Within a Query
http://support.microsoft.com/kb/208946



回答2:

An Other option would be to use a small piece of VBA (that is if you are really working in Access, not just using an Access database)

Option Compare Database
Dim rn As Long

Function ResetRownumber() As String
    rn = 0
    ResetRownumber = "OK"
End Function
Function RowNumber(dummyID As Integer) As Long
    If (dummyID > 0) Then
        rn = rn + 1
        RowNumber = rn
    End If
End Function

You call ResetRownumber() before you start your Query And then

SELECT RowNumber(anyfield) AS RowNum, OtherField FROM SomeTable

This will give you a rownumber. Passing one of the selected fieldnames is not optional, otherwise the VBA function is only called once and not for every row. Warning: Use it only on a limited number of records as your query will be slowing down significantly by calling the VBA code for every selected row.