我使用过程在表中插入或更新数据,我想要返回最后插入的id。
这是我的程序:
/* insert or update task */
DROP PROCEDURE IF EXISTS `proc_update_task`;
DELIMITER $$
CREATE PROCEDURE `proc_update_task`(IN TaskID INT, IN Name VARCHAR(100), IN Description TEXT, IN ProjectID INT, IN StatusID INT, IN ExpectedTime TIME, IN PriorityID INT, IN CategoryID INT, IN MilestoneID INT, IN UserID INT, IN DateDeadline DATE, OUT lastID INT)
BEGIN
DECLARE Status INT;
DECLARE Project INT;
DECLARE TimeExp DATE;
DECLARE Priority INT;
DECLARE Milestone INT;
DECLARE Category INT;
DECLARE User INT;
DECLARE Deadline DATE;
SET @Status = StatusID;
SET @Project = ProjectID;
SET @TimeExp = ExpectedTime;
SET @Priority = PriorityID;
SET @Milestone = MilestoneID;
SET @Category = CategoryID;
SET @User = UserID;
SET @Deadline = DateDeadline;
INSERT INTO tasks (ID, Name, Description, Project_ID, Status_ID, TimeExpected, Priority_ID, Category_ID, Milestone_ID, User_ID, DateDeadline)
VALUES (TaskID, Name, Description, @Project, @Status, @TimeExp, @Priority, @Category, @Milestone, @User, @Deadline)
ON DUPLICATE KEY UPDATE
Name=VALUES(Name), Description=VALUES(Description), Project_ID=@Project, Status_ID=@Status, TimeExpected=@TimeExp, Priority_ID=@Priority, Category_ID=@Category, Milestone_ID=@Milestone, User_ID=@User, DateDeadline=@Deadline;
SET lastID = LAST_INSERT_ID();
INSERT INTO debug(debug_output) VALUES (lastID);
END;
最后一位 - INSERT INTO debug(debug_output) VALUES (lastID)
- 只是为了验证,确实LAST_INSERT_ID()
返回的值是0.我知道,LAST_INSERT_ID()
在更新时没有意义,这是精细。但即使插入新记录,我仍然会得到0。
任何想法如何解决这个问题?
谢谢,zbynek
答案 0 :(得分:0)
假设插入ID
-1
值会产生新的ID
,那就错了。当-1
列为ID
或您收到类似
signed
的新行
ERROR 1264(22003):列' id'超出范围值在第1行
当您的ID
列为unsigned
时。
当行更新时,LAST_INSERT_ID
始终为0
,因为您的ON DUPLICATE KEY
子句必须修改为:
...
ON DUPLICATE KEY UPDATE
ID = LAST_INSERT_ID(ID),
Name=VALUES(Name),
...
(注意,如果插入与现有行匹配,它也将为0,但没有更新,例如列Name
具有值Peter
和您希望使用值Peter
更新它(对于每一列,反之亦然))
始终0
,因为您始终为auto_increment
列指定值。