首页 > 解决方案 > Microsoft Access 到 SQL Server 转换 - 插入时无效使用 null

问题描述

我正在迁移旧版 Microsoft Access 应用程序以使用 SQL Server 作为后端。我注意到自从切换到 SQL Server 以来,所有插入现在都出现了无效使用 null 错误。

通过一些测试,我发现这是由于 VBA 是如何编写的。主键在创建记录之前被引用,毫不奇怪它为空。

Dim recordSet  As DAO.Recordset
Dim newID As Long

Set recordSet = dbLocal.OpenRecordset("Select * FROM tblUser", dbOpenDynaset, dbSeeChanges)
 With recordSet
  .AddNew
   newID = !UserID
  .Update
 End With
recordset.Close

现在这在旧的 Access to Access 应用程序中工作正常。它是如何做到这一点的,我怎样才能使它与新的 SQL Server 后端一起工作?(我知道我可以将代码更改为不引用它,但是这会在应用程序中多次发生,因此我不希望这样做)。

标签: sql-servervbams-accessnullms-access-2010

解决方案


我很惊讶这曾经奏效。正确的做法是这样的:

With myRecordSet
    .AddNew
    ' Set all data columns (not the IDENTITY column)
    !Data = someData
    ' Save new record
    .Update

    ' Move the recordset pointer to the new record to read its ID
    .Bookmark = .LastModified
    newID = !UserID
    ' Done
    .Close
End With

https://docs.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/recordset-lastmodified-property-dao


推荐阅读