Mysql: Set column charset

后端 未结 4 591
再見小時候
再見小時候 2020-12-25 10:44

I have an existing table and I want to convert the charset only for one specific column to utf-8.

I know that this command ALTER TABLE table_name CONVERT TO CH

4条回答
  •  死守一世寂寞
    2020-12-25 11:45

    I share that, it can always help... I modified a database recently; moving from utf8 to utf8mb4; here is the script that allowed me to generate the alters...

    Generate SQL commands to alter the tables:

    SELECT CONCAT("ALTER TABLE `",`TABLE_NAME`,"` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") 
    FROM `information_schema`.`TABLES` 
    WHERE `TABLE_SCHEMA` = 'xxxx';
    

    Generate SQL commands to alter each column:

    SELECT CONCAT("ALTER TABLE `",`TABLE_NAME`,"` MODIFY `",`COLUMN_NAME`,"` ",COLUMN_TYPE," CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ",IF(`IS_NULLABLE`='YES', 'NULL', 'NOT NULL')," ",IF(`COLUMN_DEFAULT` IS NOT NULL, CONCAT(" DEFAULT '", `COLUMN_DEFAULT`, "'"), ''),";") 
    FROM `information_schema`.`COLUMNS` 
    WHERE `TABLE_SCHEMA` = 'xxx' AND `TABLE_NAME` = 'xxxx' AND (`CHARACTER_SET_NAME` IS NOT NULL OR `COLLATION_NAME` IS NOT NULL);
    

    Note that for foreign keys and primary keys that make a relationship, you will need to disable foregin key checks before modifying the column

    SET FOREIGN_KEY_CHECKS=0;
    

    and enable afterwards.

    SET FOREIGN_KEY_CHECKS=1;
    

提交回复
热议问题