问题
I am trying to alter multiple tables and change the size of the username
VARCHAR column to 999 as its current size is too small and now things are screwed up. How can I do this?
I have tried the following and it worked for one table but when trying to update multiple table names it returned errors:
ALTER TABLE `TABLE_NAME` CHANGE `username` VARCHAR( 999 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL
回答1:
You can't do it with a single query. You need to query information_schema
views to get the list of tables and columns to change. You will then use the resulting resultset to create ALTER
queries (either in an external application/script or within MySQL using cursors and prepared statements)
回答2:
I found the only way to do this was via an external file. This is my implimentation :
function changeSchema($oldName, $newName, $type, $len)
{
$res = mysql_query("SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = '$oldName' AND
TABLE_SCHEMA = 'your_database_name'");
if($res)
while($line=mysql_fetch_object($res))
mysql_query("ALTER TABLE `$line->TABLE_NAME` CHANGE `$oldName` `$newName` $type( $len ) NOT NULL ");
}
}
I then was able to modify any table I wanted easily.
回答3:
Write a query file to alter all tables and execute that file.
来源:https://stackoverflow.com/questions/8934779/how-can-i-alter-multiple-tables-at-once-in-mysql