1. 语法:
DECLARE handler_action HANDLER
FOR condition_value [, condition_value] ...
statement handler_action:
CONTINUE
| EXIT
| UNDO condition_value:
mysql_error_code
| SQLSTATE [VALUE] sqlstate_value
| condition_name
| SQLWARNING
| NOT FOUND
| SQLEXCEPTION
If one of these conditions occurs, the specified statement
executes. statement
can be a simple statement such as SET
, or a compound statement written using var_name
= value
BEGIN
and END.
http://dev.mysql.com/doc/refman/5.0/en/declare-handler.html
2. 实例
实例1:
DROP TABLE IF EXISTS tb1;
CREATE TABLE tb1(
field1 INT NOT NULL COMMENT 'id',
field2 INT COMMENT 'value',
PRIMARY KEY(field1)
)ENGINE=INNODB DEFAULT CHARSET=UTF8 COMMENT ='临时测试表' DROP PROCEDURE IF EXISTS sp_do_insert;
CREATE PROCEDURE sp_do_insert(
IN in_param1 int,
IN in_param2 int,
OUT out_status tinyint
)
BEGIN
DECLARE CONTINUE HANDLER FOR 1062 SET out_status = 1; SET out_status = 0; INSERT INTO tb1(field1, field2)
VALUES (in_param1, in_param2);
IF out_status=1 THEN
select in_param1, in_param2;
END IF;
END; CALL sp_do_insert(2,200,@out);
SELECT @out;
实例2:begin 。。。end块异常处理
DROP TABLE IF EXISTS tb1; CREATE TABLE tb1( field1 INT NOT NULL COMMENT 'id', field2 INT COMMENT 'value', PRIMARY KEY(field1) )ENGINE=INNODB DEFAULT CHARSET=UTF8 COMMENT ='临时测试表' DROP PROCEDURE IF EXISTS sp_do_insert; CREATE PROCEDURE sp_do_insert( IN in_param1 int, IN in_param2 int, IN in_param3 int, IN in_param4 int, OUT out_status1 tinyint, OUT out_status2 tinyint ) BEGIN BEGIN DECLARE CONTINUE HANDLER FOR 1062 SET out_status1 = 1; SET out_status1 = 0; INSERT INTO tb1(field1, field2)VALUES (in_param1, in_param2); IF out_status1=1 THEN select in_param1, in_param2; select '1062--------11' AS 'first result'; END IF; END; BEGIN DECLARE CONTINUE HANDLER FOR 1062 SET out_status2 = 1; SET out_status2 = 0; INSERT INTO tb1(field1, field2)VALUES (in_param3, in_param4); IF out_status2=1 THEN select in_param3, in_param4; select '1062--------22' AS 'secord result'; END IF; END; END; CALL sp_do_insert(1,100,2,200,@out1,@out2); SELECT @out1,@out2; select * from tb1;
3. server error code
http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
常见errorcode
-
Error:
1172
SQLSTATE:42000
(ER_TOO_MANY_ROWS
)Message: Result consisted of more than one row
-
Error:
1062
SQLSTATE:23000
(ER_DUP_ENTRY
)Message: Duplicate entry '%s' for key %d
-
Error:
1329
SQLSTATE:02000
(ER_SP_FETCH_NO_DATA
)Message: No data - zero rows fetched, selected, or processed