DELIMITER $$
USE `new_feature`$$
DROP PROCEDURE IF EXISTS `sp_do_insert`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_do_insert`(
IN f_id INT,
IN f_log_time VARCHAR(255),
IN f_end_time VARCHAR(255)
)
BEGIN
DECLARE done1 TINYINT DEFAULT 0; -- 保存是否发生异常的布尔值。
DECLARE i TINYINT DEFAULT 1;
DECLARE v_errcount INT DEFAULT 0; -- 获取一次错误数据条数
DECLARE v_errno INT DEFAULT 0; -- 获取错误代码
DECLARE v_msg TEXT; -- 获取错误详细信息
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION -- 定义一个异常处理块
BEGIN
SET done1 = 1; -- 发生异常,设置为1.
get diagnostics v_errcount = number;
SET v_msg = '';
WHILE i <= v_errcount
DO
GET DIAGNOSTICS CONDITION i
v_errno = MYSQL_ERRNO, v_msg = MESSAGE_TEXT;
SET @stmt = CONCAT('select ',v_errno,',"',v_msg,'","',NOW(),'" into @errno',i,',@msg',i,',@log_timestamp',i,';');
PREPARE s1 FROM @stmt;
EXECUTE s1;
SET i = i + 1;
END WHILE;
DROP PREPARE s1;
END;
INSERT INTO t_datetime (id,log_time,end_time) VALUES(f_id,f_log_time,f_end_time);
IF done1 = 1 THEN -- 把错误数据记录到表tb_log里。
SET i = 1;
WHILE i <= v_errcount
DO
SET @stmt = CONCAT('insert into tb_log ');
SET @stmt = CONCAT(@stmt,' select @errno',i,',@msg',i,',@log_timestamp');
PREPARE s1 FROM @stmt;
EXECUTE s1;
SET i = i + 1;
END WHILE;
DROP PREPARE s1;
END IF;
END$$
DELIMITER ;
MySQL5.7发布后,现在可以精简我的代码了。
DELIMITER $$
USE `new_feature`$$
DROP PROCEDURE IF EXISTS `sp_do_insert`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_do_insert`(
IN f_id INT,
IN f_log_time VARCHAR(255),
IN f_end_time VARCHAR(255)
)
BEGIN
DECLARE i TINYINT DEFAULT 1;
DECLARE v_errcount INT DEFAULT 0; -- 获取一次错误数据条数
DECLARE v_errno INT DEFAULT 0; -- 获取错误代码
DECLARE v_msg TEXT; -- 获取错误详细信息
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION -- 定义一个异常处理块
BEGIN
get stacked diagnostics v_errcount = number;
WHILE i <= v_errcount
DO
GET stacked DIAGNOSTICS CONDITION i -- 把错误数据分别保存在变量里
v_errno = MYSQL_ERRNO, v_msg = MESSAGE_TEXT;
INSERT INTO tb_log VALUES (v_errno,v_msg,NOW());
SET i = i + 1;
END WHILE;
END;
INSERT INTO t_datetime (id,log_time,end_time) VALUES(f_id,f_log_time,f_end_time);
END$$
DELIMITER ;