MySQL在存儲過程的異常處理部分使用多個語句
-- 創建測試表格,且沒有任何數據
drop table if exists t;
create table t(id int);
-- 創建存儲過程
drop procedure if exists test;
delimiter |
create procedure test()
begin
declare vId int;
-- 游標,沒有數據的結果集
declare cTest cursor for select * from t;
-- 使用begin, end在發生異常時執行多個命令
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' begin
set @done=1;
set @done2 = 222;
-- 各種語句都可以使用
insert into t values (1);
end;
-- 啟動游標
open cTest;
-- 沒有數據,拋出異常
fetch next from cTest into vid;
set @done2 = 333;
close cTest;
end;
|
delimiter ;
-- 測試調用
call test();
-- 查看結果
select @done2 from dual;
select * from t;
結果
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 6
Server version: 5.1.30-community MySQL Community Server (GPL)
Type 'help;' or 'h' for help. Type 'c' to clear the buffer.
mysql教程> use test;
Database changed
mysql> -- 測試在數據庫教程的異常裡使用多個語句
mysql> -- 創建測試表格,且沒有任何數據
mysql> drop table if exists t;
Query OK, 0 rows affected, 1 warning (0.03 sec)
mysql> create table t(id int);
Query OK, 0 rows affected (0.17 sec)
mysql> -- 創建存儲過程
mysql> drop procedure if exists test;
Query OK, 0 rows affected, 1 warning (0.02 sec)
mysql> delimiter |
mysql> create procedure test()
-> begin
-> declare vId int;
-> -- 游標,沒有數據的結果集
-> declare cTest cursor for select * from t;
-> -- 使用begin, end在發生異常時執行多個命令
-> DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' begin
-> set @done=1;
-> set @done2 = 222;
-> -- 各種語句都可以使用
-> insert into t values (1);
-> end;
-> -- 啟動游標
-> open cTest;
-> -- 沒有數據,拋出異常
-> fetch next from cTest into vid;
-> set @done2 = 333;
-> close cTest;
-> end;
-> |
Query OK, 0 rows affected (0.05 sec)
mysql> delimiter ;
mysql>
mysql> -- 測試調用
mysql> call test();
Query OK, 0 rows affected (0.13 sec)
mysql> -- 查看結果
mysql> select @done2 from dual;
+--------+
| @done2 |
+--------+
| 333 |
+--------+
1 row in set (0.00 sec)
mysql> select * from t;
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql>