访问查询添加记录号

时间:2019-02-09 01:46:40

标签: sql ms-access

将作为行号的字段添加到现有访问查询的最简单方法是什么?

现有查询为

Select * from myQuery

我环顾四周,看来大多数解决方案都涉及使用count函数,并且需要一个“ ID”字段,因此,我想知道是否有一种方法可以在没有ID字段的情况下进行操作

2 个答案:

答案 0 :(得分:0)

没有一种“简便”的方法。如果您有主键或唯一列,则可以使用子查询:

private static bool TryF(bool ok, out (string name, int val) result)
{
   if (!ok)
   {
      result = default;
      return false;
   }
   result =  ("John", 5);
   return true;
}

...


if (!TryF(false, out var result))
   return;

// continue

但是,性能可能仅在较小的桌子上才可以接受。

一个更好的选择是定义一个带有自动编号列的临时表,然后将数据插入该表:

select (select count(*)
        from myQuery as q2
        where q2.pk <= q.pk
       ) as seqnum,
       q.*
from myQuery as q;

答案 1 :(得分:0)

尽管打算用于表单,但是您可以使用文章中的 RecordNumber 函数:

Sequential Rows in Microsoft Access

并导出这些记录。

' Creates and returns a sequential record number for records displayed
' in a form, even if no primary or unique key is present.
' For a new record, Null is returned until the record is saved.
'
' 2018-08-23. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function RecordNumber( _
    ByRef Form As Access.Form, _
    Optional ByVal FirstNumber As Long = 1) _
    As Variant

    ' Error code for "There is no current record."
    Const NoCurrentRecord   As Long = 3021

    Dim Records             As DAO.Recordset

    Dim Number              As Variant
    Dim Prompt              As String
    Dim Buttons             As VbMsgBoxStyle
    Dim Title               As String

    On Error GoTo Err_RecordNumber

    If Form Is Nothing Then
        ' No form object is passed.
        Number = Null
    ElseIf Form.Dirty = True Then
        ' No record number until the record is saved.
        Number = Null
    Else
        Set Records = Form.RecordsetClone
        Records.Bookmark = Form.Bookmark
        Number = FirstNumber + Records.AbsolutePosition
        Set Records = Nothing
    End If

Exit_RecordNumber:
    RecordNumber = Number
    Exit Function

Err_RecordNumber:
    Select Case Err.Number
        Case NoCurrentRecord
            ' Form is at new record, thus no Bookmark exists.
            ' Ignore and continue.
        Case Else
            ' Unexpected error.
            Prompt = "Error " & Err.Number & ": " & Err.Description
            Buttons = vbCritical + vbOKOnly
            Title = Form.Name
            MsgBox Prompt, Buttons, Title
    End Select

    ' Return Null for any error.
    Number = Null
    Resume Exit_RecordNumber

End Function

如果必须使用查询,那么如果可以通过串联两个或多个字段来构建唯一键,则ID不是必需的,例如:

SELECT RowNumber([Field1] & "¤" & [Field2] & "¤" & [Field3]) AS RowID, *
FROM SomeTable
WHERE (RowNumber([Field1] & "¤" & [Field2] & "¤" & [Field3]) <> RowNumber("","",True));

使用功能 RowNumber

' Builds consecutive row numbers in a select, append, or create query
' with the option of a initial automatic reset.
' Optionally, a grouping key can be passed to reset the row count
' for every group key.
'
' 2018-08-23. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function RowNumber( _
    ByVal Key As String, _
    Optional ByVal GroupKey As String, _
    Optional ByVal Reset As Boolean) _
    As Long

    ' Uncommon character string to assemble GroupKey and Key as a compound key.
    Const KeySeparator      As String = "¤§¤"
    ' Expected error codes to accept.
    Const CannotAddKey      As Long = 457
    Const CannotRemoveKey   As Long = 5

    Static Keys             As New Collection
    Static GroupKeys        As New Collection

    Dim Count               As Long
    Dim CompoundKey         As String

    On Error GoTo Err_RowNumber

    If Reset = True Then
        ' Erase the collection of keys and group key counts.
        Set Keys = Nothing
        Set GroupKeys = Nothing
    Else
        ' Create a compound key to uniquely identify GroupKey and its Key.
        ' Note: If GroupKey is not used, only one element will be added.
        CompoundKey = GroupKey & KeySeparator & Key
        Count = Keys(CompoundKey)

        If Count = 0 Then
            ' This record has not been enumerated.
            '
            ' Will either fail if the group key is new, leaving Count as zero,
            ' or retrieve the count of already enumerated records with this group key.
            Count = GroupKeys(GroupKey) + 1
            If Count > 0 Then
                ' The group key has been recorded.
                ' Remove it to allow it to be recreated holding the new count.
                GroupKeys.Remove (GroupKey)
            Else
                ' This record is the first having this group key.
                ' Thus, the count is 1.
                Count = 1
            End If
            ' (Re)create the group key item with the value of the count of keys.
            GroupKeys.Add Count, GroupKey
        End If
        ' Add the key and its enumeration.
        ' This will be:
        '   Using no group key: Relative to the full recordset.
        '   Using a group key:  Relative to the group key.
        ' Will fail if the key already has been created.
        Keys.Add Count, CompoundKey
    End If

    ' Return the key value as this is the row counter.
    RowNumber = Count

Exit_RowNumber:
    Exit Function

Err_RowNumber:
    Select Case Err
        Case CannotAddKey
            ' Key is present, thus cannot be added again.
            Resume Next
        Case CannotRemoveKey
            ' GroupKey is not present, thus cannot be removed.
            Resume Next
        Case Else
            ' Some other error. Ignore.
            Resume Exit_RowNumber
    End Select

End Function