Retrieve Autonumber ID after adoCMD INSERT via adoRS query (1 Viewer)

mdlueck

Sr. Application Developer
Local time
Today, 04:02
Joined
Jun 23, 2011
Messages
2,631
In order to obtain the Autonumber record ID from a SQL INSERT done via an adoCMD object, I found the following way to obtain the new record's ID:

Code:
Public Function Insert() As Long
On Error GoTo Err_Insert

  Dim adoCMD As ADODB.Command
  Dim adoRS As ADODB.Recordset
  Dim strSQL As String

  'Define a query to INSERT a new record into the FE temp table
  strSQL = "INSERT INTO [" & Me.FETempTableName & "] ([id],[sort],[active],[title]) " & _
           "VALUES (?,?,?,?);"

  'Define attachment to database table specifics
  Set adoCMD = New ADODB.Command
  With adoCMD
    .ActiveConnection = CurrentProject.Connection
    .CommandType = adCmdText
    .CommandText = strSQL
    .Parameters.Append .CreateParameter("p1", adSmallInt, adParamInput, 2, 0)
    .Parameters.Append .CreateParameter("p2", adSmallInt, adParamInput, 2, Me.sort)
    .Parameters.Append .CreateParameter("p3", adBoolean, adParamInput, 2, Me.active)
    .Parameters.Append .CreateParameter("p4", adVarChar, adParamInput, 50, Me.title)
    .Execute
  End With

  'Fetch the Autonumber ID the new record is stored at
  strSQL = "SELECT @@Identity AS [aid]"

  'Define attachment to database table specifics
  Set adoRS = New ADODB.Recordset
  With adoRS
    .ActiveConnection = CurrentProject.Connection
    .CursorType = adOpenDynamic
    .LockType = adLockPessimistic
    .Open strSQL

    'Was no record found?
    If .BOF Or .EOF Then
      Insert = 0
    Else
      'Retrieve the ID the new record is stored at
      Me.aid = Nz(adoRS!aid, 0)
      Insert = Me.aid
    End If

    'Close the database table
    .Close
  End With

Exit_Insert:
  'Clean up the connection to the database
  Set adoCMD = Nothing
  Set adoRS = Nothing

  Exit Function

Err_Insert:
  Call errorhandler_MsgBox("Class: clsObjAdminPickListStandardTbl, Function: Insert()")
  Insert = False
  Resume Exit_Insert

End Function
First an ADODB.Command object is used, with accompanying ADODB.Parameters objects, to perform a SQL INSERT into an Access table.

Then immediately following that, an ADODB.Recordset object is used to submit a query retrieving the new record's Autonumber ID.
 

Users who are viewing this thread

Top Bottom