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
?
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.
You should use SCOPE_IDENTITY() to get last primary key inserted value on your table.
If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.
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.
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.
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