Skip to content

Instantly share code, notes, and snippets.

@przmv
Created October 10, 2010 07:13
Show Gist options
  • Save przmv/619046 to your computer and use it in GitHub Desktop.
Save przmv/619046 to your computer and use it in GitHub Desktop.
Add column to MySQL table if it's not exists
DROP PROCEDURE IF EXISTS AddColumn;
DELIMITER '//'
CREATE PROCEDURE AddColumn(
IN dbName TINYTEXT,
IN tableName TINYTEXT,
IN fieldName TINYTEXT,
IN fieldDef TEXT)
BEGIN
IF NOT EXISTS (
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME=fieldName
and TABLE_NAME=tableName
and TABLE_SCHEMA=dbName
)
THEN
SET @ddl=CONCAT('ALTER TABLE `',dbName,'`.`',tableName,
'` ADD COLUMN `',fieldName,'` ',fieldDef);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
END IF;
END;
//
DELIMITER ';'
CALL AddColumn('mydatabase', 'mytable', 'newfield', 'INT UNSIGNED NOT NULL DEFAULT 1');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment