Created
March 31, 2015 09:33
-
-
Save carltondickson/9dfeb4c81d77a6cdf2a2 to your computer and use it in GitHub Desktop.
MySQL - Drop INDEX or COLUMN with IF EXISTS check first
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 INDEX | |
SELECT IF ( | |
EXISTS( | |
SELECT * FROM INFORMATION_SCHEMA.statistics | |
WHERE table_schema = DATABASE() AND TABLE_NAME = '<table_name>' AND index_name LIKE '<index_name>' | |
) | |
,'ALTER TABLE `<table_name>` DROP INDEX `<index_name>`' | |
,'select "index <index_name> does not exist";') INTO @a; | |
PREPARE stmt1 FROM @a; | |
EXECUTE stmt1; | |
DEALLOCATE PREPARE stmt1; | |
# DROP COLUMN | |
SELECT IF ( | |
EXISTS( | |
SELECT * FROM INFORMATION_SCHEMA.columns WHERE table_schema = DATABASE() AND TABLE_NAME = '<table_name>' AND COLUMN_NAME = '<column_name>' | |
) | |
,'ALTER TABLE `<table_name>` DROP COLUMN `<column_name>`' | |
,'select "column <index_name> does not exist";') INTO @a; | |
PREPARE stmt1 FROM @a; | |
EXECUTE stmt1; | |
DEALLOCATE PREPARE stmt1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment