Stop Access from using wrong identity when appending to linked table on SQL server

前端 未结 3 1337
野的像风
野的像风 2020-12-20 22:21

TL:DR; version:

If I insert a record into a linked table that has a trigger that inserts a record in a different table, Access displays the global i

3条回答
  •  礼貌的吻别
    2020-12-20 22:37

    An ODBC trace reveals that Access is indeed calling SELECT @@IDENTITY (as opposed to SCOPE_IDENTITY()) after inserting the row into the SQL Server linked table:

    Database1       e00-1490    EXIT  SQLExecDirectW  with return code 0 (SQL_SUCCESS)
            HSTMT               0x00000000004D6990
            WCHAR *             0x000000000F314F28 [      -3] "INSERT INTO  "dbo"."Table1"  ("txt") VALUES (?)\ 0"
            SDWORD                    -3
    
    ...
    
    Database1       e00-1490    EXIT  SQLExecDirectW  with return code 0 (SQL_SUCCESS)
            HSTMT               0x00000000004D6990
            WCHAR *             0x000007FED7E6EE58 [      -3] "SELECT @@IDENTITY\ 0"
            SDWORD                    -3
    

    Furthermore, this behaviour appears to depend on the ODBC driver being used, since a similar test with MySQL Connector/ODBC shows that Access does not call the corresponding MySQL function LAST_INSERT_ID() after inserting a row into a MySQL linked table.

    Given that Access is calling SELECT @@IDENTITY, we must modify our trigger as follows (source: here) to reset the @@IDENTITY value back to its original value

    create trigger mytable_insert_trigger on mytable for insert as
    
    declare @identity int
    declare @strsql varchar(128)
    
    set @identity=@@identity
    --your code
    --insert into second table ...
    --your code
    set @strsql='select identity (int, ' + cast(@identity as varchar(10)) + ',1) as id into #tmp'
    execute (@strsql)
    

提交回复
热议问题