Created
October 10, 2010 07:13
-
-
Save przmv/619046 to your computer and use it in GitHub Desktop.
Add column to MySQL table if it's not exists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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