What is the equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?
SCOPE_IDENTITY() returns the IDENTITY value inserted in T1. This was the last insert that occurred in the same scope. The SCOPE_IDENTITY() function returns the null value if the function is invoked before any INSERT statements into an identity column occur in the scope.
The @@identity function returns the last identity created in the same session. The scope_identity() function returns the last identity created in the same session and the same scope. The ident_current(name) returns the last identity created for a specific table or view in any session.
SCOPE_IDENTITY() returns the identity value from the first table, because that was the last inserted-identity value within the current scope (the trigger is outside the current scope). The IDENT_CURRENT() function simply returns the last identity value inserted into the specified table, regardless of scope or session.
SELECT SCOPE_IDENTITY() returns the last IDENTITY value produced on a table and by a statement in the same scope, regardless of the table that produced the value. Because Identity is a dynamic database parameter, it can be set and reset at any time during an application.
This is what you are looking for:
LAST_INSERT_ID()
In response to the OP's comment, I created the following bench test:
CREATE TABLE Foo ( FooId INT AUTO_INCREMENT PRIMARY KEY ); CREATE TABLE Bar ( BarId INT AUTO_INCREMENT PRIMARY KEY ); INSERT INTO Bar () VALUES (); INSERT INTO Bar () VALUES (); INSERT INTO Bar () VALUES (); INSERT INTO Bar () VALUES (); INSERT INTO Bar () VALUES (); CREATE TRIGGER FooTrigger AFTER INSERT ON Foo FOR EACH ROW BEGIN INSERT INTO Bar () VALUES (); END; INSERT INTO Foo () VALUES (); SELECT LAST_INSERT_ID();
This returns:
+------------------+ | LAST_INSERT_ID() | +------------------+ | 1 | +------------------+
So it uses the LAST_INSERT_ID()
of the original table and not the table INSERT
ed into inside the trigger.
Edit: I realized after all this time that the result of the SELECT LAST_INSERT_ID()
shown in my answer was wrong, although the conclusion at the end was correct. I've updated the result to be the correct value.
open MySql command type SELECT LAST_INSERT_ID();
then ENTER
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With