How can I alter multiple tables at once in mysql?

对着背影说爱祢 提交于 2019-12-04 00:51:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!