1.增加字段
? ?
alter table docdsp add dspcode char(200)
2.刪除字段
? ??
alter table table_name drop column column_name
3.修改字段類型
? ??
alter table table_name alter column column_name new_data_type
?2.6.1. 增加字段
要增加一個字段,使用這條命令:
alter table products add column description text;
新增的字段對于表中已經存在的行而言最初將先填充空值。
你也可以同時在該字段上定義約束,使用通常的語法:
alter table products add column description text check (description <> '');
一個新字段不能用非空約束,因為最初的時候該字段必須包含空值。 但是你可以稍后增加一個非空約束。同樣,你也不能在一個新字段 上定義缺省值。根據 sql 標準的說明,這樣需要對現存行的新 字段填充缺省值,而這個特性還沒有實現。但是你可以稍后調整 字段缺省。
2.6.2. 刪除字段
要刪除一個字段,使用這個命令:
alter table products drop column description;
2.6.3. 增加約束
要增加一個約束,使用表約束語法。比如:
alter table products add check (name <> ''); alter table products add constraint some_name unique (product_no); alter table products add foreign key (product_group_id) references product_groups;
要增加一個不能寫成表約束的非空約束,使用下面語法:
alter table products alter column product_no set not null;
這個約束將立即進行檢查,所以表在添加約束之前必須符合約束條件。
2.6.4. 刪除約束
要刪除一個約束,你需要知道它的名字。如果你給了它一個名字, 那么事情就好辦了。否則系統會分配一個生成的名字,這樣你就需要 把它找出來了。psql 的命令 \d tablename 在這兒可以幫忙; 其它接口可能也提供了檢查表的細節的方法。然后就是這條命令:
alter table products drop constraint some_name;
除了非空約束外,所有約束類型都這么用。要刪除非空類型,用
alter table products alter column product_no drop not null;
(要記得非空約束沒有名字。)
2.6.5. 改變缺省值
要給一個字段設置缺省值,使用一個象下面這樣的命令:
alter table products alter column price set default 7.77;
要刪除缺省值,用
alter table products alter column price drop default;
這樣相當于把缺省設置為空,至少在 postgresql里是這樣的。 結果是,如果我們刪除一個還沒有定義的缺省值不算錯誤,因為缺省隱含就是空值。
2.6.6. 給字段改名字
重命名一個字段:
alter table products rename column product_no to product_number;
2.6.7. 給表改名字
to rename a table:alter table products rename to items;