Oracle約束的定義及管理

2021-09-26 08:23:09 字數 2525 閱讀 4615

非空約束:not null

唯一性約束:unique

主鍵約束:primary key

外來鍵約束:foreign key

檢查性約束:check

clazz表:cid、cname

create table clazz(

cid number(4) constraint clazz_cid_pk primary key,

cname varchar(10)

);

student表:sid、scard、sname、sgender、cid

列級約束(沒有指定約束名):

create table student(

sid number(4) primary key ,

scard varchar2(10) unique,

sname varchar2(10) not null,

sgender varchar2(6) check (sgender in ('male','female')),

cid number(4) references clazz(cid)

);

列級約束(指定約束名):

create table student(

sid number(4) constraint stu_sid_pk primary key,

scard varchar2(10) constraint stu_scard_uk unique,

sname varchar2(10) constraint stu_sname_nn not null,

sgender varchar2(6) constraint stu_sgender_ck check (sgender in ('male','female')),

cid number(4) constraint stu_cid_fk references clazz(cid)

);

表級約束:

(not null只能用於列級約束)

create table student(

sid number(4),

scard varchar2(10),

sname varchar2(10) constraint stu_sname_nn not null,

sgender varchar2(6),

cid number(4),

constraint stu_sid_pk primary key(sid),

constraint stu_scard_uk unique(scard),

constraint stu_sgender_ck check (sgender in ('male','female')),

constraint stu_cid_fk foreign key(cid) references clazz(cid)

);

alter table student modify (sname not null);

alter table student add constraint stu_sid_pk primary key(sid);

alter table student add constraint stu_scard_uk unique(scard);

alter table student add constraint stu_sgender_ck check (sgender in ('male','female'));

alter table student add constraint stu_cid_fk foreign key(cid) references clazz(cid);

alter table student modify (sname null);

drop constraint stu_sid_pk;

drop constraint stu_scard_uk;

drop constraint stu_sgender_ck;

drop constraint stu_cid_fk;

alter table student disable constraint stu_sid_pk;

alter table student enable constraint stu_sid_pk;

通過資料字典user_constraints、user_cons_columns可查詢約束

select constraint_name, constraint_type, status 

from user_constraints where table_name = 'student';

select constraint_name, column_name

from user_cons_columns where table_name = 'student';

Oracle學習日記 約束的建立與管理

約束的建立與管理 非空約束 name varchar2 20 notnull 唯一約束 資料列的內容不允許重複 emaile varchat2 30 unique 空值不會收到唯一約束的限制 null 在oracle中,約束也是物件,使用資料字典檢視 select from user constra...

oracle 索引的定義及使用

2 索引 目標是為了提高查詢的速度,當使用者對查詢速度不滿意而需要對資料庫的效能進行調校時,優先考慮建立索引。資料庫中索引的概念與書索引的概念非常類似,不同之處在於資料庫索引用來在表中查詢特定的行。索引缺點 向表中 新增 刪除 行時,必須花費額外的時間來更新該行的索引。建立索引的時機 當需要從大表中...

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

看下面的例子 create table temp age number 3 alter table temp add constraint ck temp age check age 0 and age 125 現在我們能夠插入age表的集合是或null,這和我們實際的現實生活是符合的。為限制age...