1.添加字段
alter table [table_name] add [column_name] [column_type] add [column_name] [column_type];
2.添加字段帶默認值
alter table [table_name] add column [column_name] [column_type] not null with default [value];
3.刪除字段
alter table [table_name] drop column [column_name];
4.修改字段類型
alter table [table_name] alter column [column_name] set data type [column_type];
5.將原表列not null屬性修改為null屬性
alter table [table_name] alter column [column_name] drop not null;
以上所有的修改都會將表處於reorg pending狀態所以我們必須進行reorg才能使該表恢復到正常狀態。否則表不可以使用,查詢或更新報錯 DB2 sqlstate 57016
6.如果要修改為null屬性的字段有約束性,則不能直接修改。
6.1檢查約束性
select CONSTNAME, TYPE from SYSCAT.TABCONST where TABNAME=[table_name];
主要看type,一般type的值有P(主鍵約束)、U(唯一性約束)、K(列值檢查)、F(外鍵)
以主鍵為例:
6.2刪除主鍵:
ALTER TABLE [table_name] DROP PRIMARY KEY;
6.3 reorg操作見第7步
6.4 新增主鍵(沒有則跳過)
alter table [table_name] add constraint MY_TABLE_PK PRIMARY KEY([column1],[column2]...);
MY_TABLE_PK 名稱隨意,我習慣用表名_PK
6.5 修改為null屬性
alter table [table_name] alter column [column] drop not null;
7.reorg操作
reorg table [table_name]
如果我們不是DBA的話,好多鏈接數據庫的客戶端工具是不能執行 reorg table [table_name] 的,我們可以用下面的語句執行reorg操作:
call SYSPROC.ADMIN_CMD('reorg table [table_name]')
實際上reorg就是調用的SYSPROC.ADMIN_CMD