DB2数据库对现有表格字段修改
数据库表:Websites
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
| 3 | 菜鸟教程 | http://www.runoob.com/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
+----+--------------+---------------------------+-------+---------+
1.添加字段
对已经存在的表格添加字段:
alter table [table_name] add [column_name] [column_type]
例如:
alter table Websites add country1 varchar(30) ;
reorg table Websites;
2.更改字段类型
alter table [table_name] alter column [column_name] set data type [column_type]
例如:
alter table Websites alter column country set data type varchar(60);
reorg table Websites;
注意: 更改字段类型是有限制的,如将字段改为比之前类型长度大的可以,如果要改小或者修改小数点长度,必须先drop掉原来的column,然后再重新添加.
例如我要将一个varchar(10)
的column改为varchar(6)
或者将一个DECIMAL(16, 2)
的column改为DECIMAL(16, 4)
等,均不能使用上述语句修改,另外改为不同的类型,也需要先drop
掉column。
3.去掉字段
alter table [table_name] drop column [column_name]
注意: drop
掉字段之后,可能会导致表查询/插入操作不能执行,需要对表进行reorg
。
例如:
alter table Websites drop column country;
reorg table Websites;
4.为字段添加默认值
alter table [table_name] alter column [column_name] set default [value]
例如:
alter table Websites alter column country set default "CN";
reorg table Websites;
5. 添加带默认值的字段
alter table [table_name] add column [column_name] [column_type] not null with default [value]
例如:
alter table Websites add column country varchar(60) not null with default "CN";
reorg table Websites;
6. 设置字段默认时间为当前时间
alter table [table_name] alter column [column_name] set default current date;
例如:
alter table Websites alter column country set default current date;
reorg table Websites;