先来解释下什么是错误缓冲区?
针对的表结构为:
CREATE TABLE `t_datetime` (
`id` int(11) NOT NULL,
`log_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`end_time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
存储过程代码为:
DELIMITER $$
USE `new_t`$$
DROP PROCEDURE IF EXISTS `sp_do_update`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_do_update`(
IN f_id INT,
IN f_log_time VARCHAR(255),
IN f_end_time VARCHAR(255)
)
BEGIN
DECLARE i_con1 TINYINT DEFAULT 0;
DECLARE i_code CHAR(5) DEFAULT '00000';
DECLARE i_msg TEXT;
DECLARE i_rows INT;
DECLARE i_con1 CONDITION FOR 1048; — 这个错误代码代表字段限制不能NULL。
DECLARE CONTINUE HANDLER FOR i_con1
BEGIN
SET i_con1 = 1;
get diagnostics CONDITION 1
i_code = returned_sqlstate, i_msg = message_text;
END;
UPDATE t_datetime
SET log_time = IFNULL(f_log_time,NULL),
end_time = IFNULL(f_end_time,NULL)
WHERE id = f_id;
IF i_con1 = 0 THEN
get diagnostics i_rows = ROW_COUNT;
SET @i_result = CONCAT("Update succeeded, affected ", i_rows,'.');
ELSE
SET @i_result = CONCAT('Update failed, error code is 1042, related message is ',i_msg,'.');
END IF;
SELECT @i_result;
END$$
DELIMITER ;
我们来执行上面的存储过程,完了后,就能把错误信息保存到SESSION 变量@i_result 中。这样,方便了后期进行各种输出。
CALL sp_do_update(1,NOW(),DATE_ADD(NOW(),INTERVAL 1 DAY));
Result.
Update succeeded, affected 1.
CALL sp_do_update(1,NULL,NULL);
Result.
Update failed, error code is 1042, related message is Column 'log_time' cannot be null.