(1)条件是用来定义在处理过程中遇到问题时相应的处理步骤。
(2)条件定义的语法:
DECLARE condition_name CONDITION FOR codition_value
condition_value:
SQLSTATE [VALUE] sqlstate_value
| mysql_error_code
(3) 条件处理的语法:
DECLARE handler_type HANDLER FOR condition_value [,...] sp_statement
handler_type:
CONTINUE | EXIT | UNDO
conditon_value:
SQLSTATE [VALUE] sqlstate_value
| condition_name
| SQLWARING
| NOT FOUND
| SQLEXCEPTION
| mysql_error_code
示例:
下面对比有条件处理和没条件处理
没条件处理:(已经插入主键ID 1~200的记录)
CREATE PROCEDURE actor_insert()
BEGIN
SET @x=1;
INSERT INTO actor(actor_id, first_name,last_name) VALUES(201 , 'TEST', '201');
SET @X=2;
INSERT INTO actor(actor_id,first_name,last_name) VALUES(1,'TEST',‘1’);
SET @x=3;
END ;
$$
call actor_insert()
增加了条件语句,用于处理主键重异常
CREATE PROCEDURE actor_insert()
BEGIN
DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET @X2=1;
SET @X=1;
INSERT INTO actor(actor_id,first_name,last_name) VALUES(201,'TEST','201');
SET @x=2;
INSERT INTO actor(actor_id,first_name,last_name) VALUES(1,'TEST','1');
SET @X=3;
END ;
注释:调用条件处理的过程,再遇到主键重的错误时,会按照定义的处理方式进行处理。
handler_type: 支持CONTINUE(继续执行)和EXIT(执行终止)
continue_value的值分为:自定义(declare 声明变量);SQLDATA 值 ; mysql-error-code ; SQLWARNING ; NOT FOUND ; SQLEXCEPTION