如何在MYSQL中一次更改多列的数据类型?

时间:2017-02-08 13:44:45

标签: mysql hibernate

我们开始使用ID作为int(11)。然后我们切换到Hibernate列自动生成,ID变为bigint(20)。因此,除非我将连接列定义从bigint(20)更改为int(11),否则许多外键都停止工作。是否可以编写一个脚本,将所有列的int(11)更改为bigint(20)?

查找要更改的所有列的查询如下:

select table_name, column_name, column_type 
from information_schema.columns
where table_schema = 'rentoptimum' 
  and column_type='int(11)'
order by table_name, ordinal_position;

我可以更新information_schema.columns中的数据,还是应该为每个表编写alter脚本?

1 个答案:

答案 0 :(得分:2)

您可以查询INFORMATION_SCHEMA以动态生成包含修改这些列数据类型所需的ALTER TABLE语句的脚本。

您需要非常小心地仅修改数据类型,而不是列的任何其他属性(可空性,auto_increment,有符号/无符号等)。

这是一个让你入门的例子。这将在给定模式中为每个表生成一个ALTER TABLE语句,即使它有多个要修改的列。它会将int(11)替换为bigint(11),这与您要求的略有不同,但(11)不会影响实际的数据类型。你可以根据需要进行调整。

select concat('alter table `',t.table_schema,'`.`',t.table_name,'`',
  group_concat(' modify column `',c.column_name,'` ',replace(c.column_type,'int','bigint'),
  if(c.is_nullable='yes',' null',' not null '),c.extra),';') as the_ddl 
into outfile '/tmp/so42114820.sql'
from information_schema.columns c 
  inner join information_schema.tables t on t.table_schema = c.table_schema and t.table_name = c.table_name
where t.table_schema = 'your_schema' 
  and t.table_type = 'BASE TABLE'
  and c.data_type = 'int' 
group by t.table_schema,t.table_name;

set @foreign_key_checks = @@foreign_key_checks;
set foreign_key_checks = 0;

\. /tmp/so42114820.sql

set foreign_key_checks = @foreign_key_checks;
相关问题