Skip to content

Instantly share code, notes, and snippets.

@eusonlito
Last active March 14, 2023 18:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save eusonlito/d52272c93df18c5cfe2ea779144c0717 to your computer and use it in GitHub Desktop.
Save eusonlito/d52272c93df18c5cfe2ea779144c0717 to your computer and use it in GitHub Desktop.
Drop table column only if exists in a MySQL database
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