SQL 修改表結構

2021-05-27 09:28:19 字數 2364 閱讀 4677

資料庫修改表結構sql

修改表結構包括:

增加字段、刪除字段、增加約束、刪除約束、修改預設值、修改字段資料型別、重新命名字段、重新命名表。

所有這些動作都是用 alter table 命令執行的。

1、    增加字段

alter table products add description text;

你也可以同時在該字段上定義約束,使用通常的語法:

alter table products add  description text check (description <> '');實際上,所有在 create table 裡描述的可以應用於字段之選項都可以在這裡使用。不過,我們要注意的是預設值必須滿足給出的約束,否則 add 將會失敗。 另外,你可以在你正確填充了新字段的數值之後再增加約束(見下文)。

2、 刪除字段

要刪除乙個字段,使用下面這樣的命令:

alter table products drop column description;不管欄位裡有啥資料,都會消失。和這個字段相關的約束也會被刪除。 不過,如果這個欄位被另外乙個表的外來鍵所引用,postgresql 則不會隱含地刪除該約束。你可以通過使用 cascade 來授權刪除任何依賴該字段的東西:

alter table products drop column description cascade;

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 teacher add constraint df_*** default('男') for ***

要增加乙個不能寫成表約束的非空約束,使用下面語法:

alter table products alter column product_no set not null;

這個約束將立即進行檢查,所以表在新增約束之前必須符合約束條件。

4、 刪除約束

要刪除乙個約束,你需要知道它的名字。如果你給了它乙個名字, 那麼事情就好辦了。否則系統會分配乙個生成的名字,這樣你就需要 把它找出來了。psql 的命令 \d tablename 在這兒可以幫忙; 其它介面可能也提供了檢查表的細節的方法。然後就是這條命令:

alter table products drop constraint some_name;(如果你在處理乙個生成的約束名,比如 $2,別忘了你需要給它 新增雙引號,讓它成為乙個有效的識別符號。)

和刪除字段一樣,如果你想刪除有著被依賴關係地約束,你需要用 cascade。 乙個例子是某個外來鍵約束依賴被引用欄位上的唯一約束或者主鍵約束。

除了非空約束外,所有約束型別都這麼用。要刪除非空型別,用

alter table products alter column product_no drop not null;(要記得非空約束沒有名字。)

5、改變乙個欄位的預設值

要給乙個字段設定預設值,使用乙個象下面這樣的命令:

alter table products alter column price set default 7.77;請注意這麼做不會影響任何表中現有的資料行, 它只是為將來 insert 命令改變預設值。

要刪除預設值,用

alter table products alter column price drop default;這樣實際上相當於把預設設定為空。 結果是,如果我們刪除乙個還沒有定義的預設值不算錯誤,因為預設隱含就是空值。

6、 修改乙個欄位的資料型別

alter table products alter column price type numeric(10,2);只有在字段裡現有的每個項都可以用乙個隱含的型別轉換轉換城新的型別時才可能成功。如果需要更複雜的轉換,你可以增加乙個 using 子句,它宣告如何從舊值裡計算新值。

postgresql 將試圖把字段的預設值(如果存在)轉換成新的型別, 還有涉及該字段的任何約束。但是這些轉換可能失敗,或者可能生成奇怪的結果。 在修改某欄位型別之前,你最好刪除那些約束,然後再把自己手工修改過的新增上去。

7、給字段改名字

alter table products rename column product_no to product_number;

8、. 給表改名字

alter table products rename to items;

sql修改表結構

增加字段 alter table docdsp add dspcode char 200 刪除字段 alter table table name drop column column name 修改字段型別 alter table table name alter column column nam...

SQL指令碼修改表結構

sql指令碼修改表結構 新建表 create table 表名 自動編號字段 int identity 1,1 primary key 欄位1 nvarchar 50 default 預設值 null 欄位2 ntext null 欄位3 datetime,欄位4 money null 欄位5 in...

SQL指令碼修改表結構

sql指令碼修改表結構 新建表 create table 表名 自動編號字段 int identity 1,1 primary key 欄位1 nvarchar 50 default 預設值 null 欄位2 ntext null 欄位3 datetime,欄位4 money null 欄位5 in...