insert query with sequential primary key

Here are some notes that may help you towards your goal, however life would be a lot easier and a lot safer with autonumbers. This is VBA as you mention MS Access.

Function NextTranNumber(ByRef FirstTran As Long, _
         ByRef LastTran As Long, Optional BlockSize = 1)
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strSQL As String
Dim lngResult As Long
Dim strCon As String

    lngResult = 0  'assume fail

    strCon = TestCon ''Connection to back-end
    cn.Open strCon

    rs.CursorType = adOpenKeyset
    rs.LockType = adLockPessimistic
    rs.CursorLocation = adUseServer

    ''Where BEInfo is a single line table that holds a transaction seed
    strSQL = "SELECT ASeqNumber FROM BEInfo"

    rs.Open strSQL, cn, , , adCmdText

    'Note this is ADO, so no rs.Edit
    FirstTran = rs!ASeqNumber + 1
    rs!ASeqNumber = rs!ASeqNumber + BlockSize
    rs.Update

    LastTran = rs!ASeqNumber
    rs.Close
    Set rs = Nothing
End Function

Sub TransactionProcessing()
Dim FirstTran As Long
Dim LastTran As Long
Dim db As Database
Dim sSQL As String
Dim Block As Long
Dim rs As DAO.Recordset

    Set db = CurrentDb

    'Existing temporary table
    sSQL = "DELETE FROM FETempTrans"
    db.Execute sSQL, dbFailOnError
    'The records to be added to the main table
    sSQL = "INSERT INTO FETempTrans ( ID, AText ) SELECT 0 AS ID, AText FROM Table1"
    db.Execute sSQL, dbFailOnError

    Block = db.RecordsAffected

    'Reserve a transaction block based on the temp table count
    NextTranNumber FirstTran, LastTran, Block

    Set rs = db.OpenRecordset("FETempTrans")

    Do While Not rs.EOF
        rs.Edit
        rs!ID = FirstTran
        rs.Update
        FirstTran = FirstTran + 1
        rs.MoveNext
    Loop

    If FirstTran - 1 = LastTran Then
        'compare the temp set to the main table
        'if it passes, update the main table
    Else
        'fail
    End If
End Sub

Leave a Comment