我的程序:
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。键“PRIMARY”的重复条目“1”
我假设 custId= Last_Insert_Id();
这一行给我错误的插入 ID。因此它无法插入到最后一张表中。
我想知道插入后如何获取最后插入的ID。(Address_id 是自动递增的)。
表格是:
客户:
CustomerId int 自增,
客户名称 varchar,
客户邮箱 varchar,
AddressId int fk 引用 address.AddressId
地址:
AddressId pk int 自增,
地址 1 varchar,
地址 2 varchar,
zip int fk 引用 zipmaster.zip
压缩大师:
zip int pk自增,
城市变量,
状态变量,
国家/地区 varchar
最佳答案
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
关于MySql 存储过程 : Get Last Inserted Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34416790/