一.知识点
1.表主键,外键,unique约束,check约束
(1)主键
a.使主键失效:alter table 表名 disable primary key cascade;
b.使主键恢复:alter table 表名 enable primary key;
(主键恢复前,要先把插入的违反主键约束的数据删除)
c.删除主键: alter table 表名drop primary key;
(2)外键:用的是外键约束名
a.使外键失效:alter table 表名 disable constraint 外键约束名;
b.使外键恢复:alter table 表名 enable constraint 外键约束名;
(外键恢复前,要先把插入的违反外键约束的数据删除)
c.删除外键: alter table 表名drop constraint 外键约束名;
d.建立一个外键(如果后面没有加cascade,则默认是No action):
1>建表时建立
create table 从引用关系表名
(
foreign key(从引用关系列) references 被引用关系表名(被引用关系列)
on delete cascade --对关系做级联删除
on update cascade --对关系做级联更新
on delete set null/default, --将参照要删除数据的子表对应数据置空/置缺省值
)
例如:
create table instructor
(
foreign key(dept_name) references department(dept_name)
)
2>运行过程中需要建立外键
alter table 从引用关系表名
add foreign key(从引用关系列) references 被引用关系表名(被引用关系列)
例如:
alter table instructor
add foreign key(dept_name) references department(dept_name)
(3)unique(A1,A2,...,An): A1,A2,...,An形成了一个超码。
(为UNIQUE 约束命名:constraint 约束名 unique(A1,A2,...,An))
a.建立unique约束:
1>建表时建立
1)不需要为 UNIQUE 约束命名
create table unique_test//在 "unique_test" 表创建时在 "Id_P" 列创建 unique 约束: (id number, ...... unique(Id_P) )
2)需要为 UNIQUE 约束命名
create table unique_test//在 "unique_test" 表创建时在 "Id_P" 列创建 unique 约束: (id number, ...... constraint uc_PersonID unique(Id_P) )
2>表已被创建后:
1)需要为 UNIQUE 约束命名
alter table 表名
add constraints 约束名 unique(A1,A2,...,An)
2)不需要为 UNIQUE 约束命名
alter table 表名
add unique(A1,A2,...,An)
2.使unique约束无效
1>建立时有约束名
alter table 表名
diasble constraints 约束名
2>建立时无约束名
alter table 表名
disable unique(A1,A2,...,An)
3.删除unique约束(与2.使外键无效相同,将disable改为drop)
(4)check约束:几乎类似于unique约束
区别:check的用法形式不同
a.建表时的check用法
1>
create table history_student
(
......
tot_cred number(3,0) check(tot_cred>=0),
......
)
2>
create table history_student
(
......
semester varchar(8),
......
check(semester in ('Fall','Winter','Spring','Summer'))
)