Last active
May 7, 2021 03:30
-
-
Save betafcc/a570dafd812fa8787a05656993998b27 to your computer and use it in GitHub Desktop.
Automatically converts a column to enum type, getting the values from the column itself
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
-- usage: CALL convert_to_enum('my_table', 'my_column'); | |
DELIMITER $$ | |
CREATE PROCEDURE `convert_to_enum`(IN tablename TEXT, IN colname TEXT) | |
BEGIN | |
SET @temp = CONCAT( | |
"SELECT CONCAT(\"ENUM('\", GROUP_CONCAT(DISTINCT ", | |
colname, | |
" ORDER BY ", | |
colname, | |
" SEPARATOR \"', '\"), \"')\") INTO @temp FROM ", | |
tablename | |
); | |
PREPARE stmt FROM @temp; EXECUTE stmt; DEALLOCATE PREPARE stmt; | |
SET @temp = CONCAT('ALTER TABLE ', tablename, ' MODIFY COLUMN ', colname, ' ', @temp, ';'); | |
PREPARE stmt FROM @temp; EXECUTE stmt; DEALLOCATE PREPARE stmt; | |
END$$ | |
DELIMITER ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment