Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the latest inserted id in a trigger?

I use a trigger to insert a row and want to use the last created id for using in the subsequent query.

How could I do this?

The code looks like:

BEGIN
IF (NEW.counter >= 100) THEN
INSERT INTO tagCategories (name, counter) VALUES ('unnamed', NEW.counter);
// here i want to have access to the above inserted id
UPDATE tagCategories2tagPairs SET tagCategoryId = <<ID_HERE>> WHERE tagPairId = OLD.id
END IF;
END
like image 239
ajsie Avatar asked Feb 15 '10 00:02

ajsie


People also ask

How do I get the latest inserted record ID in SQL?

The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How do I find the last inserted record id?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.

How do I get the last inserted row id in SQL Server?

To get an ID of last inserted record, you can use this T-SQL: INSERT INTO Persons (FirstName) VALUES ('Joe'); SELECT ID AS LastID FROM Persons WHERE ID = @@Identity; You can use query like this inside stored procedure or as an ad-hoc query.


1 Answers

Have you looked at LAST_INSERT_ID()? But be aware:

If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only.

like image 54
Mitch Wheat Avatar answered Sep 28 '22 20:09

Mitch Wheat