Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?

What is the equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?

like image 297
kristof Avatar asked Feb 18 '09 12:02

kristof


People also ask

What is 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.

What are identity () and Scope_identity () functions in SQL?

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.

What is the difference between Scope_identity () and Current_identity ()?

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.

What is select Scope_identity ()?

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.


2 Answers

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 INSERTed 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.

like image 80
Sean Bright Avatar answered Oct 03 '22 19:10

Sean Bright


open MySql command type SELECT LAST_INSERT_ID(); then ENTER

like image 38
Ramgy Borja Avatar answered Oct 03 '22 21:10

Ramgy Borja