Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch last inserted ID form stored procedure in MySQL

Tags:

mysql

How to fetch last inserted id?

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insertzonemsg`     (IN User_Id INT(10),     IN zid INT(10),     IN update_titles VARCHAR(50),     IN textarea1s TEXT,     IN filupload1s TEXT,     IN audio1s VARCHAR(100),     OUT out_id INT(10))         BEGIN         INSERT INTO zone_message_master         **(user_id,ZoneID,update_title,textarea1,filupload1,         audio1,LastUpdate)**         VALUE         **(User_Id,zid,update_titles,textarea1s,         filupload1s,audio1s,NOW());**  SELECT **id** as **out_id** FROM **zone_message_master** LAST_INSERT_ID(); END$$ 

I need to return last inserted ID as out_id form the Table zone_message_master?

like image 949
Ekky Avatar asked Oct 31 '12 05:10

Ekky


People also ask

How do I get the last inserted id in MySQL?

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.

How do I get the last inserted record in SQL?

You should use SCOPE_IDENTITY() to get last primary key inserted value on your table.

How can I get last inserted record in MySQL using PHP?

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.

Is MySQL LAST_INSERT_ID reliable?

This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions. and even go so far as to say: Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid.


1 Answers

You need to use SET statement. For example -

Table:

CREATE TABLE table1(   id INT(11) PRIMARY KEY AUTO_INCREMENT,   column1 VARCHAR(10),   column2 VARCHAR(10) ); 

Procedure's body:

BEGIN   INSERT INTO table1(column1, column2) VALUES ('value1', 'value2');   SET out_param = LAST_INSERT_ID(); END 

Note, that ID field is not specified in INSERT statement. This value will be inserted automatically; and of course, this ID field must have AUTO_INCREMENT option.

like image 142
Devart Avatar answered Sep 22 '22 16:09

Devart