How to change collation of all rows from latin1_swedish_ci to utf8_unicode_ci?

后端 未结 2 1243
滥情空心
滥情空心 2021-01-31 10:36

I ignorantly used the default latin1_swedish_ci character encoding for all of the varchar rows in my database during development and I\'ve determined that this is the root of th

2条回答
  •  故里飘歌
    2021-01-31 11:11

    If the columns are using the default table character set then it's just one query per table to convert:

    ALTER TABLE t CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
    

    If the character set is set individually on each column, AFAIK there is no way to do that on all columns of all tables in the database directly in MySql, but you could write a tiny program in your language of choice that does so.

    Your program would query the INFORMATION_SCHEMA.COLUMNS table and look at the CHARACTER_SET_NAME column:

    SELECT * FROM `INFORMATION_SCHEMA.COLUMNS`
    WHERE TABLE_SCHEMA = 'dbname' AND CHARACTER_SET_NAME = 'latin1'
    

    For each result row it's trivial to synthesize and execute an ALTER TABLE query on the spot that changes the character set and collation appropriately:

    ALTER TABLE t MODIFY col TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
    

    In the above query t, col and TEXT would be the values of the TABLE_NAME, COLUMN_NAME and DATA_TYPE columns from the INFORMATION_SCHEMA.COLUMNS result set.

提交回复
热议问题