10
4

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でALTER TABLE ADD COLUMN IF NOT EXISTS的なことがしたい

Posted at

やりたいこと

  • テーブルにカラム追加するとき、そのカラムがないときだけカラム追加するようにしたい
    -> 『Duplicate column name』エラーを無視したい
  • Flywayで実行するとき、カラム追加が上手くいってなければFailedにしたい

SQL

プロシージャを利用する。

alter_table.sql
DROP PROCEDURE IF EXISTS alter_table_procedure;

DELIMITER //

CREATE PROCEDURE alter_table_procedure()
BEGIN
  /* SQLEXCEPTIONを無視するように設定 */
  DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN END;
  
  /* 以下のALTER TABLEで『Duplicate column name』エラーが発生してもプロシージャは正常終了する */
  ALTER TABLE user ADD COLUMN age INT NULL AFTER name;
  ALTER TABLE user ADD COLUMN address VARCHAR(50) NULL AFTER age;
END //

DELIMITER ;

CALL alter_table_procedure();

DROP PROCEDURE alter_table_procedure;

/* 追加対象のカラムをSELECTすることで、もしカラム追加できていなかったらエラーとなり
   Flywayのhistoryはfailedとなる */
SELECT age, address FROM user;
10
4
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
10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?