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

后端 未结 2 1241
滥情空心
滥情空心 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:00

    You can actually do this inside MySQL, using a procedure.

    Based on https://stackoverflow.com/a/12718767/1612273. It uses the current database, so make sure you're doing it on the right one!

    delimiter //
    
    DROP PROCEDURE IF EXISTS convert_database_to_utf8 //
    
    CREATE PROCEDURE convert_database_to_utf8()
    BEGIN
        DECLARE table_name VARCHAR(255);
        DECLARE done INT DEFAULT FALSE;
    
        DECLARE cur CURSOR FOR
            SELECT t.table_name FROM information_schema.tables t WHERE t.table_schema = DATABASE() AND t.table_type='BASE TABLE';
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    
        OPEN cur;
            tables_loop: LOOP
                FETCH cur INTO table_name;
    
                IF done THEN
                    LEAVE tables_loop;
                END IF;
    
                SET @sql = CONCAT("ALTER TABLE ", table_name, " CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
                PREPARE stmt FROM @sql;
                EXECUTE stmt;
                DROP PREPARE stmt;
            END LOOP;
        CLOSE cur;
    END //
    
    delimiter ;
    call convert_database_to_utf8();
    

提交回复
热议问题