MySQL 5.6.14
以前一個項目比較倉促,開發給的建表語句沒有註釋.
如今要補全註釋信息.
可是MySQL後期追加註釋比較麻煩
須要使用modify語法。
只要不當心寫錯一點,就可能致使表結構的變動,而不是註釋的變動.
實驗表以下:
- create table t(
- c1 int primary key auto_increment,
- c2 char(20) not null default 'c2' comment 'c2的註釋',
- c3 date default '2016-01-25' comment 'date類型測試',
- c4 varchar(20) not null default '' ,
- c5 bigint ,
- c6 text comment 'text測試',
- c7 timestamp not null default current_timestamp on update current_timestamp,
- c8 datetime not null default now()
- );
經過以下的SQL,解析元數據信息,能夠直接顯示modify的內容.
追加或者修改註釋以後,執行語句便可.
這樣能夠避免人爲的失誤.
- SELECT
- concat(
- 'alter table ',
- table_schema, '.', table_name,
- ' modify column ', column_name, ' ', column_type, ' ',
- if(is_nullable = 'YES', ' ', 'not null '),
- if(column_default IS NULL, '',
- if(
- data_type IN ('char', 'varchar')
- OR
- data_type IN ('date', 'datetime', 'timestamp') AND column_default != 'CURRENT_TIMESTAMP',
- concat(' default ''', column_default,''''),
- concat(' default ', column_default)
- )
- ),
- if(extra is null or extra='','',concat(' ',extra)),
- ' comment ''', column_comment, ''';'
- ) s
- FROM information_schema.columns
- WHERE table_schema = 'test'
- AND table_name = 't'
以實驗表爲例,生成的modify語句以下.
- alter table test.t modify column c1 int(11) not null auto_increment comment '';
- alter table test.t modify column c2 char(20) not null default 'c2' comment 'c2的註釋';
- alter table test.t modify column c3 date default '2016-01-25' comment 'date類型測試';
- alter table test.t modify column c4 varchar(20) not null default '' comment '';
- alter table test.t modify column c5 bigint(20) comment '';
- alter table test.t modify column c6 text comment 'text測試';
- alter table test.t modify column c7 timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP comment '';
- alter table test.t modify column c8 datetime not null default CURRENT_TIMESTAMP comment '';