【MySQL】 批量更改库,表,字段的字符集
库一级的更改:
-- 单个库字符集更改
ALTER DATABASE `ymcd_aisw` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
ALTER DATABASE `ymcd_aisw` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci';
-- 批量修改库的字符集
SELECT concat('ALTER TABLE ',TABLE_NAME,' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '指定数据库';
表一级的更改:
-- 批量改表的字符集
SELECT CONCAT('ALTER TABLE `', TABLE_SCHEMA, '`.`', TABLE_NAME, '` CHARACTER SET = utf8, COLLATE = utf8_general_ci;')
FROM information_schema.`TABLES`
WHERE `TABLE_SCHEMA` = 'ymcd_aisw' -- 指定单库
-- `TABLE_SCHEMA` IN ('x111', 'xaaaq') -- 指定多库
字段一级的更改:
-- 批量改字段
-- 主键字符字段不涉及索引问题,联合主键也是一样
SELECT CONCAT(
-- 指定的库和表名
'ALTER TABLE `', TABLE_SCHEMA, '`.`', TABLE_NAME, '` ',
-- 指定的字段和数据类型
'MODIFY COLUMN `', COLUMN_NAME, '` ', COLUMN_TYPE,
-- 指定的字符集和对应的排序规则
' CHARACTER SET utf8 COLLATE utf8_general_ci ',
-- 是否非空和默认值的组合
(CASE
WHEN IS_NULLABLE = 'NO' AND COLUMN_DEFAULT IS NULL THEN 'NOT NULL '
WHEN IS_NULLABLE = 'NO' AND COLUMN_DEFAULT IS NOT NULL THEN CONCAT('NOT NULL DEFAULT "', COLUMN_DEFAULT, '" ')
WHEN IS_NULLABLE = 'YES' AND COLUMN_DEFAULT IS NULL THEN 'NULL DEFAULT NULL '
WHEN IS_NULLABLE = 'YES' AND COLUMN_DEFAULT IS NOT NULL THEN CONCAT('NULL DEFAULT "', COLUMN_DEFAULT, '" ')
END),
-- 保留原始注释信息
'COMMENT "', COLUMN_COMMENT, '";'
)
FROM information_schema.`COLUMNS`
WHERE
CHARACTER_SET_NAME = 'utf8mb4' -- 根据原字符集来筛选
AND `TABLE_SCHEMA` = 'ymcd_aisw' -- 指定单库
-- `TABLE_SCHEMA` IN('') -- 指定多库
转载于:https://www.cnblogs.com/mindzone/p/16011871.html
生成sql后需要复制出来执行下