Home > コンディションとハンドラーの使い方

コンディションとハンドラーの使い方

  • July 24, 2007 10:19 AM
ストアドプロシージャやストアドファンクション内では、エラーハンドリングにコンディションとハンドラーを使うことができる。

コンディションとハンドラーのサンプル

[(none)]> use test;
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とMySQLエラーコードの一覧は、MySQL AB :: MySQL 5.0 Reference Manual :: 23.4.4.7 Mapping MySQL Error Numbers to SQLStatesMySQL AB :: MySQL 5.0 Reference Manual :: B.2 Server Error Codes and Messagesに載っている。

コンディションの宣言で、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;



Home > コンディションとハンドラーの使い方

Search
Feeds

Return to page top