4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLのトリガを一時的に無効にする

Posted at

MySQLのトリガを一時的に無効にする方法を調べてみました。

SET FOREIGN_KEY_CHECKS = FALSE

のトリガバージョンに当たる機能は、MySQL5.6時点で提供されてないので、自前でトリガ無効機能を実装する必要があります。

具体的には、トリガ定義で実行フラグセッション変数を参照して条件分岐するように書いてやるとうまくいきました。

create table hoge (
  id integer primary key auto_increment,
  val varchar(255)
);

DELIMITER $$
DROP TRIGGER IF EXISTS `valCheck_beforeInsert` $$
CREATE TRIGGER `valCheck_beforeInsert`
BEFORE INSERT ON `hoge` FOR EACH ROW

thisTrigger: BEGIN
  # トリガ有効フラグセッション変数をチェック
  IF (@TRIGGER_CHECKS = FALSE)
  THEN
    LEAVE thisTrigger;
  END IF;

  # トリガ処理
  SET NEW.val = 'moge';
END $$
DELIMITER ;

これで、@TRIGGER_CHECKS の値でトリガ有効/無効を切り替えることができるようになりました。

> insert into hoge values ();

> SET @TRIGGER_CHECKS = FALSE;

> insert into hoge values ();

> SET @TRIGGER_CHECKS = TRUE;

> insert into hoge values ();

> select * from hoge;
+----+------+
| id | val  |
+----+------+
|  1 | moge |
|  2 | NULL |
|  3 | moge |
+----+------+
3 rows in set (0.00 sec)

動いてますね。
セッション変数を使ってますので、コネクションごとに独立して有効/無効を切り替えられます。

この記事を参考にしました。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?