Stored-Procedures
有沒有辦法跳過程序中的錯誤並恢復程序
當表中有唯一鍵(不是
PRIMARY KEY
)並且過程正在執行時,如果出現重複鍵錯誤,整個過程將停止。我想恢復錯誤並再次呼叫該過程。程序,流程:
DELIMITER $$ CREATE PROCEDURE `injatest`.`LoadData` () BEGIN DECLARE x INT; SET x = 1; WHILE x <= 14400 DO INSERT INTO junc_question_course_iq(q_id,iq_id,ct_id) VALUES (CEIL(RAND()*1000), CEIL(RAND()*48), CEIL(RAND()*10)); SET x = x + 1; END WHILE; END $$ DELIMITER ;
我想在聯結表中插入大約 14000 條記錄,但是當唯一(iq_id,q_id)存在重複鍵時會出現問題?做什麼?
您可以
DECLARE CONTINUE HANDLER FOR SQLSTATE
通過將空塊聲明為異常處理程序來忽略密鑰衝突,如下所示:DELIMITER $$ CREATE PROCEDURE `injatest`.`LoadData` () BEGIN DECLARE x INT; DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' BEGIN END; SET x = 1; WHILE x <= 14400 DO INSERT INTO junc_question_course_iq(q_id,iq_id,ct_id) VALUES (CEIL(RAND()*1000), CEIL(RAND()*48), CEIL(RAND()*10)); SET x = x + 1; END WHILE; END $$ DELIMITER ;