Maestro13
Maestro13

Reputation: 3696

Access vba: how perform inserts in two related tables?

This could very well be a basic question - but I was unable to find any threads on this, so I turn to the experts!

I have a sub in a form where I wish to insert rows in related tables. The parent table has an Id which is an autonumber field; I need to use the Id of a newly created row and insert it as foreign key in the child table. I tried the following:

Dim x As Recordset
Dim newId As Integer

Set x = CurrentDb.OpenRecordset("select * from T")
With x
    .AddNew
    !OtherColumns = SomeValues
    .Update
    newId = .Fields("Id")
End With

As Id is an autonumber column, it is assigned the next available number all right - after this sub ends, the table contains a new row with the Id that has been generated automatically. But variable newId does not contain the new Id value that has been generated for the added row. Instead it contains the Id of the first row in the recordset.

How can I retrieve the new Id?

Upvotes: 1

Views: 1584

Answers (1)

Patrick McDonald
Patrick McDonald

Reputation: 65421

After your first query, you can run a second query "Select @@Identity" to get the last auto-generated number in the current connection, for example (untested)

Dim rs2 As Recordset
Set rs2 = CurrentDb.OpenRecordset("Select @@Identity")
newId = rs2(0)

Upvotes: 2

Related Questions