Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How should I use the mysql and awk to change the charset for all the fields and tables for a specific database? I did not include username or password, so for sure it will not work.

Should I run it as it is and wait or does it need to be modified to work with authentication?

mysql --database=dbname -B -N -e "SHOW TABLES" \
| awk '{print "SET foreign_key_checks = 0; ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; "}' \
| mysql --database=dbname &
share|improve this question

migrated from stackoverflow.com Apr 26 '13 at 7:47

This question came from our site for professional and enthusiast programmers.

First backup the database. Sometimes character conversions can give unexpected results.

I have had good success using these instructions:

SELECT CONCAT('ALTER TABLE ',  table_name, ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;') INTO OUTFILE '/tmp/altertablesstatements.sql'
FROM
information_schema.tables
WHERE
    table_schema='<database-name>'
AND table_collation != 'utf8' 
GROUP BY table_name;

Add disable foreign_key_checks to first line of sql.

echo 'SET foreign_key_checks = 0;' >> /tmp/altertablesstatements.sql

Import the changes

mysql DATABASE  < /tmp/altertablesstatements.sql

Converting Columns

SELECT CONCAT(  'ALTER TABLE <DATABASE>.', table_name,  ' CHANGE ',COLUMN_NAME,'  ',COLUMN_NAME,' ',COLUMN_TYPE,' CHARACTER SET utf8 COLLATE utf8_general_ci',
IF(IS_NULLABLE='NO',' NOT NULL;',' NULL;')) INTO OUTFILE '/tmp/altercolumnsstatements.sql'
FROM information_schema.COLUMNS AS tb
WHERE TABLE_SCHEMA =  '<DATABASE>'
AND character_set_name != 'utf8';

Add disable foreign_key_checks to first line of sql.

echo 'SET foreign_key_checks = 0;' >> /tmp/altercolumnsstatements.sql

Import the changes

mysql DATABASE  < /tmp/altercolumnsstatements.sql

https://confluence.atlassian.com/jirakb/how-to-change-all-columns-and-tables-collation-to-utf8_bin-in-mysql-601456761.html

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.