简体   繁体   English

如何在MS Access中执行查询时保留主键的自动编号?

[英]How to retain the AutoNumber of a Primary Key when executing a query in MS Access?

I am trying to do something like the following in a query: 我试图在查询中执行以下操作:

Dim rs As RecordSet
Dim NewPrimaryKey as Long

Set rs = Currentdb.OpenRecordset("SELECT * FROM MyTable WHERE MyPrimaryKey Is Null;")

With rs
      .AddNew
      NewPrimaryKey = !MyPrimaryKey
      !DateValue = Now()
      ...
      .Update
End With

Any pointers on how to do t his using a query that I can execute in MS Access 2003 using the JET engine would be greatly appreciated. 任何关于如何使用我可以使用JET引擎在MS Access 2003中执行的查询的指针都将非常感激。

You can use two SQL statements to accomplish what I think you want. 您可以使用两个SQL语句来完成我想要的任何内容。 First an INSERT. 首先是INSERT。 Then "SELECT @@Identity" to get the last added autonumber value. 然后“SELECT @@ Identity”获取最后添加的自动编号值。 Use an object variable for the database connection with both SQL statements. 对两个SQL语句的数据库连接使用对象变量。

Dim db As DAO.Database
Dim NewPrimaryKey As Long
Dim strInsert As String

strInsert = "INSERT INTO MyTable ([DateValue])" & vbCrLf & _
    "VALUES (Now());"
Set db = CurrentDb
db.Execute strInsert, dbFailOnError
NewPrimaryKey = db.OpenRecordset("SELECT @@Identity")(0)
Debug.Print NewPrimaryKey
Set db = Nothing

I enclosed the field name DateValue in square brackets because it is a reserved word. 我将字段名称DateValue括在方括号中,因为它是一个保留字。

Edit : If you insert multiple records with one SQL statement, SELECT @@Identity will still give you the last autonumber. 编辑 :如果您使用一个SQL语句插入多个记录,SELECT @@ Identity仍将为您提供最后一个自动编号。 It's the last autonumber for inserts performed through that connection instance. 它是通过该连接实例执行的插入的最后一个自动编号。 And you don't get a sequence of the autonumbers used; 而且你没有得到一系列自动编号; only the last one. 只有最后一个。

strInsert = "INSERT INTO MyTable3 ([some_text])" & vbCrLf & _
    "SELECT TOP 3 foo_text FROM tblFoo" & vbCrLf & _
    "WHERE foo_text Is Not Null ORDER BY foo_text;"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM