MariaDB数据库COLLATE更改查询

时间:2017-11-15 14:21:40

标签: database character-encoding mariadb collation

我有3个查询来更改COLLATION。他们应该工作,但他们没有。看起来只有第二个查询的[!varchar]列会受到影响。有谁能告诉那里有什么问题?我需要将 utf8_general_ci 转换为 utf8_bin 。 我得到的结果如下:

ALTER TABLE AO_21F425_MESSAGE_MAPPING_AO MODIFY MESSAGE_ID varchar CHARACTER SET UTF8 COLLATE utf8_bin NOT NULL;
ALTER TABLE AO_21F425_MESSAGE_MAPPING_AO MODIFY USER_HASH varchar CHARACTER SET UTF8 COLLATE utf8_bin NOT NULL;
ALTER TABLE AO_38321B_CUSTOM_CONTENT_LINK MODIFY LINK_URL varchar CHARACTER SET UTF8 COLLATE utf8_bin;

依此类推......但DB没有变化。

1)更改类型为VARCHAR

的列
SELECT CONCAT('ALTER TABLE `', table_name,
        '` MODIFY `', column_name, '` ', DATA_TYPE, '(', CHARACTER_MAXIMUM_LENGTH, 
        ') CHARACTER SET UTF8 COLLATE utf8_bin',
        (CASE WHEN IS_NULLABLE = 'NO' THEN ' NOT NULL' ELSE '' END), ';')
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = 'my_database_name'
AND DATA_TYPE = 'varchar'
AND
(
    CHARACTER_SET_NAME != 'utf8'
    OR
    COLLATION_NAME != 'utf8_bin'
);

2)更改VARCHAR类型以外的列

SELECT CONCAT('ALTER TABLE `', table_name,
    '` MODIFY `', column_name, '` ', DATA_TYPE,
    ' CHARACTER SET UTF8 COLLATE utf8_bin',
    (CASE WHEN IS_NULLABLE = 'NO' THEN ' NOT NULL' ELSE '' END), ';')
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = 'my_database_name'
AND DATA_TYPE != 'varchar'
AND
(
    CHARACTER_SET_NAME != 'utf8'
    OR
    COLLATION_NAME != 'utf8_bin'
);

3)更改表级

SELECT CONCAT('ALTER TABLE ',  table_name, ' CHARACTER SET utf8 COLLATE utf8_bin;')
FROM information_schema.TABLES AS T, information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` AS C
WHERE C.collation_name = T.table_collation
AND T.table_schema = 'my_database_name'
AND
(
    C.CHARACTER_SET_NAME != 'utf8'
    OR
    C.COLLATION_NAME != 'utf8_bin'
);

2 个答案:

答案 0 :(得分:0)

当心; ALTER可能不是你想要的!

您来自charset latin1并且数据现在正确编码为latin1吗?然后你需要ALTER TABLE ... CONVERT TO ...

你来自latin1,但字节是utf8吗?然后你需要两个改变。

你的具体情况是什么?

在确定您真正需要的内容后,请提供由此产生的ALTERs供我们批评。

这些链接可能有所帮助:

更多

ALTER  TABLE AO_21F425_MESSAGE_MAPPING_AO MODIFY MESSAGE_ID
      varchar CHARACTER SET UTF8 COLLATE utf8_bin NOT NULL;

您必须指定varchar

的大小

答案 1 :(得分:0)

我找到了解决问题的方法。它做得非常好。只需粘贴到控制台即可。

DB="your_database_name"; ( echo 'ALTER DATABASE `'"$DB"'` CHARACTER SET utf8 COLLATE utf8_bin;'; mysql "$DB" -e "SHOW TABLES" --batch --skip-column-names | xargs -I{} echo 'ALTER TABLE `'{}'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;' ) | mysql "$DB"