Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fhdalikhan/dd600ccfb2c161c5465037daac4a94c4 to your computer and use it in GitHub Desktop.
Save fhdalikhan/dd600ccfb2c161c5465037daac4a94c4 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 `DropIfExists`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment