条件异常处理和变量

时间:2022-05-16 03:58:09

1.变量的定义
DECLARE var_name[,...] type [DEFAULT value]

2.变量的赋值
SET var_name = expr [, var_name = expr] ...
SELECT col_name[,...] INTO var_name[,...] table_expr

#这里payment.amount 改为 amount应该也没问题吧?
SELECT IFNULL(SUM(payment.amount),0) INTO v_payments
FROM payment
WHERE payment.payment_date <= p_effective_date
AND payment.customer_id = p_customer_id;

 

异常处理:

mysql> call actor_insert();

ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

 

A numeric error code (1146). This number is MySQL-specific and is not portable to other database systems.

A five-character SQLSTATE value ('23000'). The values are taken from ANSI SQL and ODBC and are more standardized.

 

 DECLARE handler_type HANDLER FOR condition_value[,...] sp_statement

handler_type 现在还只支持 CONTINUE 和 EXIT 两种,CONTINUE 表示继续执行下面的语句,
EXIT 则表示执行终止,UNDO 现在还不支持。

 

--标准错误码捕获

DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET @x2 = 1;

--捕获 mysql-error-code:

DECLARE CONTINUE HANDLER FOR 1062 SET @x2 = 1;

--事先定义 condition_name:

DECLARE DuplicateKey CONDITION FOR SQLSTATE '23000';  #declare condition

DECLARE CONTINUE HANDLER FOR DuplicateKey SET @x2 = 1; #declare handler

--捕获 SQLEXCEPTION

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET @x2 = 1;

 

·SQLWARNING 是对所有以 01 开头的 SQLSTATE 代码的速记。

·NOT FOUND 是对所有以 02 开头的 SQLSTATE 代码的速记。

·SQLEXCEPTION 是对所有没有被 SQLWARNING 或 NOT FOUND 捕获的 SQLSTATE 代码的速记