批量修改表和表字段编码格式和排序规则

发布时间:2022-08-04 17:54:49 作者:yexindonglai@163.com 阅读(1125)

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

  1. SELECT CONCAT('ALTER TABLE ',TABLE_SCHEMA,'.','`', TABLE_NAME, '` MODIFY `', COLUMN_NAME, '` ', DATA_TYPE,
  2. '(', CHARACTER_MAXIMUM_LENGTH, ') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci',
  3. (CASE WHEN IS_NULLABLE = 'NO' THEN ' NOT NULL' ELSE '' END),
  4. IF(COLUMN_KEY = 'PRI', '', (CASE WHEN ISNULL(column_default) THEN CONCAT(' ') ELSE CONCAT(' DEFAULT \'' , column_default ,'\'') END)),
  5. (CASE WHEN IFNULL(column_comment,'')='' THEN '' ELSE CONCAT(' COMMENT \'' , column_comment ,'\'') END),
  6. ';') AS `sql`
  7. FROM information_schema.COLUMNS
  8. WHERE 1=1
  9. AND TABLE_SCHEMA IN( 'rino_device','rino_system','rino_user') #要修改的数据库名称
  10. AND TABLE_NAME='chenfu_table' # 要修改的指定数据表名称
  11. AND DATA_TYPE = 'varchar' # 要修改的指定列类型
  12. AND COLLATION_NAME='utf8mb4_0900_ai_ci'; # 要修改的指定字符集

结果如下

  1. ALTER TABLE rino_device.`rino_device_user_ref` MODIFY `device_id` VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '设备id';
  2. ALTER TABLE rino_device.`rino_device_user_ref` MODIFY `user_id` VARCHAR(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '用户id';
  3. ALTER TABLE rino_device.`rino_device_user_ref` MODIFY `create_by` VARCHAR(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '创建人';

批量修改表字符集和排序规则

  1. SELECT
  2. CONCAT("ALTER TABLE ",TABLE_SCHEMA,".`",TABLE_NAME,
  3. "` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;") AS target_tables
  4. FROM INFORMATION_SCHEMA.TABLES
  5. WHERE TABLE_SCHEMA IN( 'rino_device','rino_system','rino_user','rino_product') # 库名
  6. AND TABLE_TYPE="BASE TABLE"; # 表名

执行结果如下

  1. target_tables
  2. ALTER TABLE rino_device.`rino_device_user_ref` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
  3. ALTER TABLE rino_system.`rino_panel_template` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
  4. ALTER TABLE rino_device.`rino_device` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

关键字Mysql