我使用過程插入或更新表中的數據,並且希望返回最後插入的ID。mysql過程中的last_insert_id()返回0
這裏是我的方法:
/* 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), [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected];
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.
任何想法如何解決這個問題?
感謝,茲比涅克
你確定MySQL自動生成任何id在這種情況下?它看起來像你自己插入ID – nos 2015-03-13 13:05:41
我不這麼認爲 - 我插入的ID是-1,在這種情況下,一個新行插入自動生成的ID,或者它是一些值> 0,它總是重複因此該行將被更新 – Zbynek 2015-03-13 13:10:41