重命名mysql数据库中所有表的列

fd3cxomn  于 2023-02-03  发布在  Mysql
关注(0)|答案(2)|浏览(138)

我需要重命名我的数据库中的所有表的列。我可以使用此查询获得列的列表:

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服务器版本的手册,以获得在'@name VARCHAR(255)附近使用的正确语法;
声明退出循环布尔值;
在第3行声明ta'
你能帮我解决这个问题吗

ao218c7q

ao218c7q1#

你可以试试这个。

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'
yzuktlbb

yzuktlbb2#

尝试以下解决方案,希望它会有所帮助

DECLARE @name VARCHAR(50) -- database name 

DECLARE db_cursor CURSOR FOR 
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME= 'OldColumn';

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @name  

WHILE @@FETCH_STATUS = 0  
BEGIN  
      set @name = @name + '.OldColumn'
      EXEC sp_rename  @name, 'NewColumn', 'COLUMN';
      print(@name)
      FETCH NEXT FROM db_cursor INTO @name 
END 

CLOSE db_cursor  
DEALLOCATE db_cursor

相关问题