Oracle資料庫設計 定義約束 Check約束

2021-04-02 17:50:02 字數 2455 閱讀 9269

看下面的例子:

create table temp (age number(3));

alter table temp add constraint ck_temp_age check

((age>0) and (age <= 125));

現在我們能夠插入age表的集合是或null,這和我們實際的現實生活是符合的。

為限制age欄位取值範圍不能為空,增加not null約束。

create table temp (age number(3) not null);

alter table temp add constraint ck_temp_age check

((age>0) and (age<=125));

下面的操作就會獲得乙個oracle錯誤:

sql> insert into temp values (130);

insert into temp values (130)

*ora-02290: check constraint (scott.ck_temp_age) violated.

當oracle 執行插入操作時,會檢查check約束條件表示式結果是否為true,不為true則拒絕執行。

check約束可以使用組合條件:

create table temp (a number);

alter table temp add constraint ck_temp_a check

(((a>=0) and (a<=10)) or (a=999) or (a=9999));

oracle中沒有boolean型別,pl/sql有boolean型別.為了替代乙個boolean列使用check約束

create table temp(enabled number(1) not null);

alter table temp add constraint ck_temp_enabled check

(enabled in (0, 1));

也可以使用varchar2型別

create table temp(enabled varchar2(1) not null);

alter table temp add constraint ck_temp_enabled check

(enabled in ('t', 'f', 't', 'f'));

一、多欄位約束

check約束可以是乙個多欄位的組合,如下:

create table box

(length number(2) not null,

width  number(2) not null,

height number(2) not null);

alter table box add constraint ck_box_volume check

((length*width*height<100) and

(length >  0) and (length <= 10) and

(width  >  0) and (width  <= 10) and

(height >  0) and (height <= 10));

也可以以不同的名字定義多個check約束

alter table box add constraint ck_box_length check

((length > 0) and (length <= 10));

alter table box add constraint ck_box_width check

((width > 0) and (width <= 10));

alter table box add constraint ck_box_height check

((height > 0) and (height <= 10));

alter table box add constraint ck_box_dimension check

((length*width*height<100));

二、補充unique約束

check約束可以被用於多行非空約束,即同時為空或同時不為空。unique約束的兩個字段可能有乙個為null,而另乙個不為null,如果我們不想它出現這種情況,我們就可以用check約束:

(both columns are null) or (both columns are not null)

create table temp (pk number primary key, a number, b number);

alter table temp

add constraint uk_temp_a_b unique (a, b);

alter table temp add constraint ck_temp_a_b

check ((a is null and b is null) or

(a is not null and b is not null));

oracle 資料庫的約束

為了使我們的資料符合一定的規則 約束有五種型別,主鍵約束,外來鍵約束,非空約束,唯一性約束,檢查約束 約束有兩種定義方法 第一種是在定義列的時候定義約束,叫做列級定義。第二種是所有列全部定義完後,在定義約束,該約束叫做表級定義 注意 not null只能在列級中定義 對於多個屬性構成的碼只能使用表級...

oracle資料庫之約束

一 非空約束 1 在建立表時設定非空約束 在資料型別後面加上 not null create table tablename username varchar2 20 not null,2 在修改表時新增非空約束 其實也就是修改欄位的定義,但是需要表中沒有資料 確切的說是要新增非空約束的列沒有非空資...

Oracle資料庫之約束

約束 資料的完整性用於確保資料庫資料遵從一定的商業和邏輯規則。在oracle中,資料完整性可以使用約束 觸發器 應用程式 過程 函式 三種實現。而約束易於維護並且效能最好,所以作為維護資料完整性的首選。約束包括五種 not null 不為空 unique 唯一 primary key 主鍵 fore...