mysql 儲存過程簡單模板
儲存過程排錯,一般要用錯誤處理器。詳細內容參考上方連結。
使用示例:
##定義一個錯誤資訊展示函式,方便儲存過程展示更精確的錯誤資訊
DELIMITER $$
CREATE FUNCTION fn_get_error()
RETURNS VARCHAR(250)
BEGIN
DECLARE code CHAR(5) DEFAULT '00000';
DECLARE msg TEXT;
DECLARE errno INT;
GET DIAGNOSTICS CONDITION 1 code = RETURNED_SQLSTATE,
errno = MYSQL_ERRNO, msg = MESSAGE_TEXT;
RETURN COALESCE(CONCAT("ERROR ", errno, " (", code, "): ", msg), '-');
END
$$
##定義相關的儲存過程,可參照此模板寫儲存過程,對排錯和維護有意義
DELIMITER $$
CREATE PROCEDURE procedure_name()
BEGIN
DECLARE errpos int default 0;
DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' as No_TLucky, errpos as Position_Error,fn_get_error() AS Error_massage;
set errpos=1;/*錯誤位置1*/
insert into test.test set name='p1';
set errpos=2;
insert into test.test set name='p2';
set errpos=3;
insert into test.test set name='p3';
insert into test.test set name=p2;
END
$$