- July 24, 2007 10:19 AM
ストアドプロシージャやストアドファンクション内では、エラーハンドリングにコンディションとハンドラーを使うことができる。
コンディションとハンドラーのサンプル
コンディションの宣言で、SQLSTATE 23000にdup_keyという名前を指定している。SQLSTATE 23000は、PKへ一意でない値をINSERTした場合などに発生する。
ハンドラーの宣言ではdup_keyが発生した場合に、そのまま処理を続けて、なおかつユーザー変数@garbageに1を設定している。
コンディションとハンドラーのサンプル
[(none)]> use test;コンディションで指定できるSQLSTATEとMySQLエラーコードの一覧は、MySQL AB :: MySQL 5.0 Reference Manual :: 23.4.4.7 Mapping MySQL Error Numbers to SQLStatesやMySQL AB :: MySQL 5.0 Reference Manual :: B.2 Server Error Codes and Messagesに載っている。
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
[test]>
[test]> create table d_table(s1 int, primary key(s1));
Query OK, 0 rows affected (0.03 sec)
[test]>
[test]> delimiter //
[test]> create procedure dohandler()
->
-> begin
-> declare dup_keys condition
-> for sqlstate '23000';
-> declare continue handler for
-> dup_keys set @garbage=1;
-> set @x=1;
-> insert into test.d_table values(1);
-> set @x=2;
-> insert into test.d_table values(1);
-> set @x=3;
-> end//
Query OK, 0 rows affected (0.00 sec)
[test]> delimiter ;
[test]>
[test]> call dohandler();
Query OK, 0 rows affected (0.00 sec)
[test]>
[test]> select @x;
+------+
| @x |
+------+
| 3 |
+------+
1 row in set (0.00 sec)
[test]>
[test]> select @garbage;
+----------+
| @garbage |
+----------+
| 1 |
+----------+
1 row in set (0.00 sec)
コンディションの宣言で、SQLSTATE 23000にdup_keyという名前を指定している。SQLSTATE 23000は、PKへ一意でない値をINSERTした場合などに発生する。
-> declare dup_keys condition
-> for sqlstate '23000';
ハンドラーの宣言ではdup_keyが発生した場合に、そのまま処理を続けて、なおかつユーザー変数@garbageに1を設定している。
-> declare continue handler for
-> dup_keys set @garbage=1;