mysql批量将数据库表名以及字段全部一键转化为大写或者小写
在MySQL中,可以通过编写SQL脚本来批量将数据库表名和字段名转换为大写或小写。以下是转换为大写的示例代码:
DELIMITER $$
CREATE PROCEDURE ConvertTableNamesToUpper()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE oldTableName VARCHAR(255);
DECLARE newTableName VARCHAR(255);
DECLARE tableCur CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = (SELECT DATABASE()) AND table_name NOT LIKE '%%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN tableCur;
read_loop: LOOP
FETCH tableCur INTO oldTableName;
IF done THEN
LEAVE read_loop;
END IF;
SET newTableName = UPPER(oldTableName);
SET @renameTableQuery = CONCAT('RENAME TABLE `', oldTableName, '` TO `', newTableName, '`;');
PREPARE stmt FROM @renameTableQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE tableCur;
END$$
DELIMITER ;
CALL ConvertTableNamesToUpper();
DELIMITER $$
CREATE PROCEDURE ConvertColumnNamesToUpper()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE oldColumnName VARCHAR(255);
DECLARE newColumnName VARCHAR(255);
DECLARE columnCur CURSOR FOR
SELECT CONCAT('`', column_name, '`')
FROM information_schema.columns
WHERE table_schema = (SELECT DATABASE())
AND table_name NOT LIKE '%%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN columnCur;
read_loop: LOOP
FETCH columnCur INTO oldColumnName;
IF done THEN
LEAVE read_loop;
END IF;
SET newColumnName = UPPER(oldColumnName);
SET @renameColumnQuery = CONCAT('ALTER TABLE `', SUBSTRING(newTableName FROM 2), '` CHANGE ', oldColumnName, ' ', newColumnName, ' ...');
-- 请在这里补充新列名对应的列定义
PREPARE stmt FROM @renameColumnQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE columnCur;
END$$
DELIMITER ;
CALL ConvertColumnNamesToUpper();
注意:在执行这些操作之前,请确保已经备份了数据库,以防止数据丢失。另外,示例代码中的...
表示你需要提供对应列的新列类型和约束。
转换为小写的操作只需将UPPER()
函数改为LOWER()
函数,并相应地修改列名。
请注意,这些存储过程需要在数据库中以root或具有足够权限的用户身份执行,因为更改表名可能会影响数据库的完整性和一致性。此外,这些脚本未考虑列的数据类型和约束,你需要在执行前补充相应的列定义。
评论已关闭