lastInsertId not working with after insert trigger
PHP Driver version or file name
5.3.0+11108
SQL Server version
13.0.4224.16 (Developer edition)
Client operating system
Windows NT NL011634 10.0 build 17134 (Windows 10) i586
PHP version
7.0.18
Problem description
After inserting a record in a table with an 'after insert' trigger that has his own insert logic, the lastInsertId method returns the last id of the inserted record of the trigger instead of the original table. Please note: the whole query runs in an uncommitted transaction.
Example: Table USER has an after insert trigger that inserts a record into the LOG table. When inserting a new record into USER, the lastInsertId method returns the last id of the LOG table.
Trying to resolve the issue by using SCOPE_IDENTITY doesn't seems to work in my case. It looks like the prepared statement used for the insert, uses his own scope and therefore SCOPE_IDENTITY returns null.
Expected behavior and actual behavior
Return the last insert id of the original scope, not of the resulting triggers.
@julianrantwijk It seems to me that this behaviour of lastInsertId is not unreasonable, but SCOPE_IDENTITY should definitely provide a workaround if you want a different behaviour. Could you provide a repro script? A minimal script showing how lastInsertId works with AFTER INSERT and how SCOPE_IDENTITY doesn't work should suffice.
This is by design @julianrantwijk.
To conform to the PDO::lastInsertId standard in PHP.net, PDO::lastInsertId is essentially SELECT @@IDENTITY when no sequence name is provided, as shown in the lastInsertId implementation,
I agree with @david-puglielli. When using a trigger that has its own insertion, SCOPE_IDENTITY would be the more logical choice than @@IDENTITY. Yet, a prepared statement has an isolated scope, as explained on this page.
Therefore, IDENT_CURRENT may be what you're looking for. The related issue #416 might give you some ideas as well.
SInce we haven't heard from you for more than two weeks, we are going to close this issue. However, please feel free to reopen this issue anytime.