Access vba:如何在两个相关表中执行插入?
这很可能是一个基本问题 - 但我找不到任何关于此的线索,所以我求助于专家!
我有一个子表单,我希望在相关表中插入行。父表有一个 Id,它是一个自动编号字段;我需要使用新创建的行的 ID 并将其作为外键插入子表中。我尝试了以下操作:
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
由于 Id 是自动编号列,因此它会被分配下一个可用的编号 - 在此子结束后,该表包含一个带有自动生成的 Id 的新行。 但变量 newId 不包含为添加的行生成的新 Id 值。相反,它包含记录集中第一行的 ID。
如何找回新的ID?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在第一个查询之后,您可以运行第二个查询
“Select @@Identity”
来获取当前连接中最后一个自动生成的号码,例如(未经测试)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)