0

我正在尝试在查询中执行以下操作:

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

任何关于如何使用我可以使用 JET 引擎在 MS Access 2003 中执行的查询的指针将不胜感激。

4

1 回答 1

2

您可以使用两个 SQL 语句来完成我认为您想要的。首先是 INSERT。然后“SELECT @@Identity”获取最后添加的自动编号值。使用对象变量与两个 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

我将字段名称 DateValue 括在方括号中,因为它是保留字。

编辑:如果您使用一条 SQL 语句插入多条记录,则 SELECT @@Identity 仍会为您提供最后一个自动编号。这是通过该连接实例执行的插入的最后一个自动编号。而且您没有得到使用的自动编号序列;只有最后一个。

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;"
于 2011-07-26T06:29:30.240 回答