views:

813

answers:

1

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

+4  A: 

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() |
+------------------+
|                5 |
+------------------+

So it uses the LAST_INSERT_ID() of the original table and not the table INSERTed into inside the trigger.

Sean Bright
Thanks Sean. How does it behave when the table I am inserting the data into has a trigger that inserts data in another table which has an autoincrement field too? Would it return the ID of the original table or the one affected by the trigger?
kristof
Thanks Sean for testing this
kristof