批量修改表和表中字段排序规则

批量修改表中字段

SELECT CONCAT('ALTER TABLE `', table_name, '` MODIFY `', column_name, '` ', DATA_TYPE, 
        '(', CHARACTER_MAXIMUM_LENGTH, ') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci', 
        (CASE WHEN IS_NULLABLE = 'NO' THEN ' NOT NULL' ELSE '' END),
		IF(COLUMN_KEY = 'PRI', '', (CASE WHEN ISNULL(column_default)  THEN concat(' DEFAULT NULL ') ELSE concat(' DEFAULT \'' , column_default ,'\'') end)),
        (case when IFNULL(column_comment,'')='' then '' else concat(' COMMENT \'' , column_comment ,'\'') end),
        ';') as `sql`
FROM information_schema.COLUMNS
WHERE 1=1
    and TABLE_SCHEMA = 'chenfu' #要修改的数据库名称
	and TABLE_NAME='chenfu_table'  # 要修改的指定数据表名称
    and DATA_TYPE = 'varchar' # 要修改的指定列类型
    and COLLATION_NAME='utf8mb4_0900_ai_ci'; # 要修改的指定字符集
  • 执行结果如下
ALTER TABLE `order` MODIFY `title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '标题';
ALTER TABLE `order_detail` MODIFY `title` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '标题';

批量修改表编码排序规则

SELECT
CONCAT("ALTER TABLE `",TABLE_NAME,
"` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;")  AS target_tables 
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="chenfu" AND TABLE_TYPE="BASE TABLE";
  • 执行结果如下
ALTER TABLE `order` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE `order_detail` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

参考

MySQL:批量修改表字段的排序规则
MySQL批量修改表字符集排序规则

你可能感兴趣的:(MySQL,数据库,数据库,sql,database)