【问题标题】:Select @@Identity returning 0 for linked table in Access为 Access 中的链接表选择 @@Identity 返回 0
【发布时间】:2009-04-11 05:11:31
【问题描述】:

我正在使用 Access 2007 并且有一些链接到 mySQL 数据库的表。我正在使用 DAO 将记录插入到 mySQL 链接表中,并尝试使用 Select @@identity 检索插入的 PK,但该选择返回 0。

  Dim sql As String

  Dim oDB As Database
  Set oDB = CurrentDb 

  sql = "INSERT INTO Quotes ( CustomerID ) SELECT 1 AS Expr1;" 

  oDB.Execute sql 

  If oDB.RecordsAffected <> 1 Then 
    MsgBox "cannot create new quote"
    Exit Function
  End If

  Dim rsNewID As DAO.Recordset
  Set rsNewID = oDB.OpenRecordset("SELECT @@IDENTITY")  ' Create a recordset and SELECT the new Identity

  Dim intNewID As Long
  intNewID = rsNewID(0).Value ' Store the value of the new identity in variable intNewID
  'This value is 0, why?

我看到another question like this, 没有得到满意的答复

【问题讨论】:

    标签: mysql ms-access ms-access-2007


    【解决方案1】:

    选择 LAST_INSERT_ID()

    【讨论】:

    • 由于某种原因,这在 Access 中不起作用。如果不是 PassThrough 查询,我认为 Access 不能在查询中使用后端函数。它告诉我找不到函数“Last_Insert_ID()”
    【解决方案2】:

    fredrik 获得了 mySQL 语句的部分功劳。需要注意的是,我使用的是 DAO,因此语句由 JET 引擎处理,它不支持此语句。这需要在 Access 中作为传递查询运行才能正常工作。在我使用 fredrik 的 select 语句进行查询后,就成功了。我从我的 DAO 代码中调用了这个 Access 直通查询,它起作用了。

    【讨论】:

      【解决方案3】:

      我没用过mysql。所以,翻译一下我对mysql说的话。

      CustomerID 是标识列吗(即它是否自行生成 ID)?
      如果是这样,请使用返回最后生成的 ID 的函数。

      @@Identity 函数是人们在 SQL Server 中使用的。我不知道 mysql 中的等价物。
      见this

      看上面的代码,你不需要打开第二个记录集。 rsNewID1 应该可以帮助您获取最后插入的 ID。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-09
        • 2015-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-15
        • 1970-01-01
        相关资源
        最近更新 更多