1. 程式人生 > >sql server 修改表結構語法大全

sql server 修改表結構語法大全

 

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;