Forked from kmoormann/IdempotentSQLAlterTableAddColumn.sql
Last active
July 16, 2019 17:16
-
-
Save grocky/018908bd460550b55bcf7fec83fc76a4 to your computer and use it in GitHub Desktop.
Idempotent SQL Alter Table Statements
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
-- Idempotently add the tasks.id column | |
SET @table_name = 'tasks'; | |
SET @column_name = 'id'; | |
SET @preparedStatement = (SELECT IF( | |
( | |
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS | |
WHERE table_name = @table_name | |
AND column_name = @column_name | |
AND data_type = 'BIGINT' | |
) > 0, | |
"SELECT 1", | |
CONCAT("ALTER TABLE ", @table_name, " ADD COLUMN ", @column_name, " BIGINT(20) COMMENT 'primary key for tasks';") | |
)); | |
PREPARE alterIfNotExists FROM @preparedStatement; | |
EXECUTE alterIfNotExists; | |
DEALLOCATE PREPARE alterIfNotExists; |
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
-- Idempotently remove the tasks.id column | |
SET @table_name = 'tasks'; | |
SET @column_name = 'id'; | |
SET @preparedStatement = (SELECT IF( | |
( | |
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS | |
WHERE table_name = @table_name | |
AND column_name = @column_name | |
) > 0, | |
CONCAT("ALTER TABLE ", @table_name, " DROP COLUMN ", @column_name), | |
"SELECT 1" | |
)); | |
PREPARE alterIfNotExists FROM @preparedStatement; | |
EXECUTE alterIfNotExists; | |
DEALLOCATE PREPARE alterIfNotExists; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment