2015-03-13 80 views
0

我使用過程插入或更新表中的數據,並且希望返回最後插入的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.

任何想法如何解決這個問題?

感謝,茲比涅克

+1

你確定MySQL自動生成任何id在這種情況下?它看起來像你自己插入ID – nos 2015-03-13 13:05:41

+0

我不這麼認爲 - 我插入的ID是-1,在這種情況下,一個新行插入自動生成的ID,或者它是一些值> 0,它總是重複因此該行將被更新 – Zbynek 2015-03-13 13:10:41

回答

0

你錯了假設插入的-1ID值將產生一個新的ID。無論是新行插入值-1IDsigned或你喜歡

ERROR 1264(22003)錯誤:出於對列「身份證」的範圍值在第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(每列反之亦然))

更新它和它的ALWA ys 0,因爲您總是爲auto_increment列指定一個值。

+0

好的,謝謝。我改變了程序,現在它包含if條件來決定是否更新值或插入新行,並返回last_insert_id現在是正確的。 – Zbynek 2015-03-13 13:45:08