Skip to content

Instantly share code, notes, and snippets.

@betafcc
Last active May 7, 2021 03:30
Show Gist options
  • Save betafcc/a570dafd812fa8787a05656993998b27 to your computer and use it in GitHub Desktop.
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
-- 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