2014-12-31 35 views
0

我知道這個查詢用於更改mysql表的字符集和整理。爲數據庫中的每個表執行語句

alter table <some_table> convert to character set utf8 collate utf8_unicode_ci; 

但我需要一個查詢來更改數據庫中的所有表。有沒有可能的解決方案?

回答

2

我寫這個程序在數據庫中執行語句爲每個表:

DROP PROCEDURE IF EXISTS sp_forEveryTable; 
DELIMITER $$ 
CREATE PROCEDURE sp_forEveryTable(IN p_schema varchar(50), IN p_stmt varchar(100)) 
BEGIN 

    DECLARE done INT DEFAULT FALSE; 
    DECLARE v_tbl varchar(50); 
    DECLARE cur CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = p_schema; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 

    OPEN cur; 

    read_loop: LOOP 
    FETCH cur INTO v_tbl; 
    IF done THEN 
     LEAVE read_loop; 
    END IF; 

    SET @sql := REPLACE(p_stmt, '?', v_tbl); 

    IF (UPPER(p_stmt) LIKE 'SELECT %') THEN 
     SET @sql := CONCAT('SELECT "', v_tbl, '", ', SUBSTRING(@sql FROM 7)); 
    ELSE 
     SELECT v_tbl AS 'Execute statement for following table:'; 
    END IF; 

    PREPARE stmt FROM @sql; 
    EXECUTE stmt; 
    DEALLOCATE PREPARE stmt; 
    END LOOP; 

    CLOSE cur; 
END $$ 
DELIMITER ; 

使用方法如下:

CALL sp_forEveryTable('your_database_name', 'ALTER TABLE ? CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci'); 

要在將來在這個數據庫中創建的表有utf8字符集和排序規則默認使用此answer中給出的語句。

相關問題