MySql存储过程:获取上次插入的ID

时间:2015-12-22 13:16:18

标签: mysql stored-procedures

我的程序:

DELIMITER $$

CREATE PROCEDURE `******`.`*********************` 
(   IN customerName varchar(100),IN customerEmail varchar(100),IN address1 varchar(100),IN address2 varchar(100),
    IN zip int,IN city varchar(100),IN state varchar(100),IN country varchar(100),IN region varchar(100),OUT customerId int)
BEGIN

Declare custId int default 0;
Declare zipExist int default 0;

Select Count(*) into zipExist from *****.********** where Zip_Code = zip;

if zipExist = 0 then
Insert into *****.**********(Zip_Code,City,State,Country,Region) values(zip,city,state,country,region); 
end if;

Insert into *****.**********(Address_1,Address_2,ZIP_Code) values(address1,address2,zip);

SET custId = LAST_INSERT_ID();

if custId > 0 then
Insert into *****.**********(Customer_Name,Customer_Email,Address) values(customerName,customerEmail,custId);
end if;

SET customerId = LAST_INSERT_ID();
END $$

在调用该过程时我收到此错误: 错误代码:1062。重复输入' 1'关键' PRIMARY'

我假设custId= Last_Insert_Id();这一行给了我错误的插入ID。因此它无法插入到最后一个表中。 我想知道如何在插入后获得最后插入的id。(Address_id是自动递增)。

表是:

客户:
CustomerId int auto-increment,
CustomerName varchar,
CustomerEmail varchar,
AddressId int fk引用address.AddressId

地址:

AddressId pk int auto-increment,
地址1 varchar,
地址2 varchar,
zip int fk引用zipmaster.zip

zipmaster:

zip int pk auto-increment,
city varchar,
state varchar,
country varchar

1 个答案:

答案 0 :(得分:2)

LAST_INSERT_ID() returns only automatically generated AUTO_INCREMENT values, if the customer_id is not auto-increment you will not get the correct value.

For more information please refer the link :

http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id