zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

MySQL追加注释或者大量修改注释

mysql 修改 注释 或者 大量 追加
2023-09-11 14:19:24 时间

分类: MySQL

 

MySQL 5.6.14

之前一个项目比较仓促,开发给的建表语句没有注释.
现在要补全注释信息.
但是MySQL后期追加注释比较麻烦
需要使用modify语法。

只要不小心写错一点,就可能导致表结构的变更,而不是注释的变更.

实验表如下:
  1. create table t(  
  2.     c1 int primary key auto_increment,  
  3.     c2 char(20) not null default 'c2'  comment 'c2的注释',  
  4.     c3 date default '2016-01-25' comment 'date类型测试',  
  5.     c4 varchar(20) not null default '' ,  
  6.     c5 bigint ,  
  7.     c6 text comment 'text测试',  
  8.     c7 timestamp not null default current_timestamp on update current_timestamp,  
  9.     c8 datetime not null default now()  
  10. );  


通过如下的SQL,解析元数据信息,可以直接显示modify的内容.
追加或者修改注释之后,执行语句即可.
这样可以避免人为的失误.
  1. SELECT     
  2. concat(    
  3.     'alter table ',     
  4.     table_schema, '.', table_name,     
  5.     ' modify column ', column_name, ' ', column_type, ' ',     
  6.     if(is_nullable = 'YES', ' ', 'not null '),     
  7.     if(column_default IS NULL, '',     
  8.         if(    
  9.             data_type IN ('char', 'varchar')     
  10.             OR     
  11.             data_type IN ('date', 'datetime', 'timestamp') AND column_default != 'CURRENT_TIMESTAMP',     
  12.             concat(' default ''', column_default,''''),     
  13.             concat(' default ', column_default)    
  14.         )    
  15.     ),     
  16.     if(extra is null or extra='','',concat(' ',extra)),  
  17.     ' comment ''', column_comment, ''';'    
  18. ) s    
  19. FROM information_schema.columns    
  20. WHERE table_schema = 'test'    
  21.     AND table_name = 't'   


以实验表为例,生成的modify语句如下.

  1. alter table test.t modify column c1 int(11) not null  auto_increment comment '';  
  2. alter table test.t modify column c2 char(20) not null  default 'c2' comment 'c2的注释';  
  3. alter table test.t modify column c3 date   default '2016-01-25' comment 'date类型测试';  
  4. alter table test.t modify column c4 varchar(20) not null  default '' comment '';  
  5. alter table test.t modify column c5 bigint(20)   comment '';  
  6. alter table test.t modify column c6 text   comment 'text测试';  
  7. alter table test.t modify column c7 timestamp not null  default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP comment '';  
  8. alter table test.t modify column c8 datetime not null  default CURRENT_TIMESTAMP comment '';