Last active
March 14, 2023 18:35
-
-
Save eusonlito/d52272c93df18c5cfe2ea779144c0717 to your computer and use it in GitHub Desktop.
Drop table column only if exists in a MySQL database
This file contains hidden or 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 `DropColumnIfExists`; | |
DELIMITER $$ | |
CREATE PROCEDURE `DropColumnIfExists` (`@TABLE` VARCHAR(100), `@COLUMN` VARCHAR(100)) | |
`DropColumnIfExists`: BEGIN | |
DECLARE `@EXISTS` INT UNSIGNED DEFAULT 0; | |
SELECT COUNT(*) INTO `@EXISTS` | |
FROM `information_schema`.`columns` | |
WHERE ( | |
`TABLE_SCHEMA` = DATABASE() | |
AND `TABLE_NAME` = `@TABLE` | |
AND `COLUMN_NAME` = `@COLUMN` | |
); | |
IF (`@EXISTS` > 0) THEN | |
SET @SQL = CONCAT('ALTER TABLE `', `@TABLE`, '` DROP COLUMN `', `@COLUMN`, '`;'); | |
PREPARE query FROM @SQL; | |
EXECUTE query; | |
END IF; | |
END $$ | |
DELIMITER ; | |
CALL DropColumnIfExists('table_to_drop_column', 'column_to_drop'); | |
DROP PROCEDURE IF EXISTS `DropColumnIfExists`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment