18

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
iainn
  • 16,826
  • 9
  • 33
  • 40
John Doe
  • 3,559
  • 15
  • 62
  • 111

3 Answers3

10

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)

pelumi
  • 1,530
  • 12
  • 21
Mchl
  • 61,444
  • 9
  • 118
  • 120
  • How can I query `information_schema`? Could you show me an example? – John Doe Jan 19 '12 at 23:24
  • 1
    http://stackoverflow.com/questions/193780/how-to-find-all-the-tables-in-mysql-with-specific-column-names-in-them/193860#193860 – Ken Jan 20 '12 at 06:57
3

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.

Raath
  • 689
  • 1
  • 6
  • 21
1

Write a query file to alter all tables and execute that file.

Naveen Kumar
  • 4,543
  • 1
  • 18
  • 36