Oracle还是比较常用的,于是我研究了一下Oracle Unique约束,在这里拿出来和大家分享一下,希望对大家有用。如果某个约束只作用于单独的字段,即可以在字段级定义约束,也可以在表级定义约束,但如果某个约束作用于多个字段,必须在表级定义约束
◆在定义约束时可以通过CONSTRAINT关键字为约束命名,如果没有指定,Oracle将自动为约束建立默认的名称定义primary key约束(单个字段)create table employees (empno number(5) primary key,...)
指定约束名create table employees (empno number(5) constraint emp_pk primary key,...)
定义primary key约束(多个字段,在表级定义约束)create table employees
(empno number(5),
deptno number(3) not null,
constraint emp_pk primary key(empno,deptno)
using index tablespace indx
storage (initial 64K
next 64K
)
)
Oracle自动会为具有PRIMARY KEY约束的字段(主码字段)建立一个***索引和一个NOT NULL约束,定义PRIMARY KEY约束时可以为它的索引指定存储位置和存储参数alter table employees add primary key (empno)
alter table employees add constraint emp_pk primary key (empno)
alter table employees add constraint emp_pk primary key (empno,deptno)
not null约束(只能在字段级定义NOT NULL约束,在同一个表中可以定义多个NOT NULL约束)
alter table employees modify deptno not null/null
Unique约束create table employees
( empno number(5),
ename varchar2(15),
phone varchar2(15),
email varchar2(30) unique,
deptno number(3) not null,
constraint emp_ename_phone_uk unique (ename,phone)
)
alter table employees
add constraint emp_uk unique(ename,phone)
using index tablespace indx
定义了Oracle Unique约束的字段中不能包含重复值,可以为一个或多个字段定义Oracle Unique约束,因此,Unique即可以在字段级也可以在表级定义,在Oracle Unique约束的字段上可以包含空值.
foreign key约束
◆定义为FOREIGN KEY约束的字段中只能包含相应的其它表中的引用码字段的值或者NULL值
◆可以为一个或者多个字段的组合定义FOREIGN KEY约束
◆定义了FOREIGN KEY约束的外部码字段和相应的引用码字段可以存在于同一个表中,这种情况称为"自引用"
◆对同一个字段可以同时定义FOREIGN KEY约束和NOT NULL约束
【编辑推荐】
【责任编辑:志京 TEL:(010)68476606】
点赞 0