MySQL追加註釋或者大量修改註釋

分類: MySQLsql

 

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 '';  
相關文章
相關標籤/搜索