我需要为数据库中的所有表重命名列。 我可以使用此查询获取列列表:
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME= <Column Name>;
但实际上我怎么能尽可能简单地重命名它并且不写
ALTER TABLE <Table Name >RENAME COLUMN <Old name> to <New Name>;
表格。
我试图写一个程序:
DELIMITER $$
DROP PROCEDURE IF EXISTS renameColumn $$
CREATE PROCEDURE renameColumn(IN oldName tinytext, IN newName tinytext)
BEGIN
DECLARE @name VARCHAR(255);
DECLARE exit_loop BOOLEAN;
DECLARE tableName_cursor CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME=oldName;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET exit_loop = TRUE;
OPEN tableName_cursor;
rename_loop: LOOP
FETCH tableName_cursor @name;
ALTER TABLE @name RENAME COLUMN oldName to newName;
IF exit_loop THEN
LEAVE rename_loop;
END IF;
END LOOP rename_loop;
END $$
DELIMITER;
但我有以下错误: 您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在&#39; @name VARCHAR(255)附近使用正确的语法;
DECLARE exit_loop BOOLEAN;
DECLARE ta&#39;在第3行
你能帮我解决这个问题吗
答案 0 :(得分:2)
你可以试试这个。
SELECT CONCAT(
'ALTER TABLE ', TABLE_NAME,
' RENAME COLUMN ', COLUMN_NAME,
' NEW_', COLUMN_NAME,
';') AS rename_script
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'your_db'