Fetch last inserted ID form stored procedure in MySQL

后端 未结 2 391
暗喜
暗喜 2020-12-29 21:56

How to fetch last inserted id?

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insertzonemsg`

   (IN User_Id INT(10),
    IN zid INT(10),
          


        
2条回答
  •  轮回少年
    2020-12-29 22:31

    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.

提交回复
热议问题