客户给了我一个旧数据库old_data,它包含一堆表,我将在新系统中逐渐激活它们。不幸的是,有两个表包含一列名称hash,该列与Ruby on, L$ F: ^+ A, ]! O; b
Rails我不能很好地浮动。我用它来解决这个项目。8 j5 w& [4 b0 l% E# [) t: Q
没有办法告诉我MySQL在MySQL控制台来遍历所有表(8).0.12版本)在给定的数据库和列重命名中hash,以old_hash若该列存在?/ x) S' }& q% e( O2 g8 ]
% Y7 m+ w. e1 n; q0 C* M0 M" m解决方案: / `) o( \; _3 h1 C3 A4 t0 K
幸运的是,MySQL 8带有ALTER TABLE RENAME COLUMN a TO b语法,所以你可以一个相当简单的存储过程来执行此操作。+ N: F7 U6 l& x: B
DELIMITER //CREATE PROCEDURE rename_columns(IN name_of_database CHAR(64) IN old_name_of_column CHAR(64) IN new_name_of_column CHAR(64))BEGIN DECLARE done INT DEFAULT FALSE; DECLARE name_of_table CHAR(64); DECLARE table_cursor CURSOR FOR SELECT TABLE_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = name_of_database AND COLUMN_NAME = old_name_of_column; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN table_cursor; table_loop: LOOP FETCH table_cursor INTO name_of_table; IF done THEN LEAVE table_loop; END IF; SET @alter_sql = CONCAT ALTER TABLE ',name_of_database,'.',name_of_table, RENAME COLUMN ',old_name_of_column,' TO ',new_name_of_column); PREPARE alter_statement FROM @alter_sql; EXECUTE alter_statement; DEALLOCATE PREPARE alter_statement; END LOOP; CLOSE table_cursor;END//DELIMITER ;CALL rename_columns('old_data','hash','old_hash');在5.在早期版本中,它更复杂,因为你需要生成一个ALTER TABLE CHANGE a b ...包含完整列定义的句子。