/*
注意:
1.如果某个约束只作用于单独的字段,即可以在字段级定义约束,也可以在表级定义约束,
但如果某个约束作用于多个字段,必须在表级定义约束
2.在定义约束时可以通过CONSTRAINT关键字为约束命名,
如果没有指定,ORACLE将自动为约束建立默认的名称
3.非空约束只能定义在字段级别
*/
-- 创建教师表
-- drop table teacher cascade constraint;
create table teacher(
id number(6),
name varchar2(20),
phone varchar2(20),
constraint pk_tea_id primary key (id)
);
-- 创建学生表
-- drop table student;
create table student(
id number(6) /*primary key */ ,
name varchar2(20) /*not null */ ,
cardno varchar2(20) /*unique check(length(cardno)>18) */ ,
tid number(6) /*references teacher(id) */
/*也可如下这样做,可以自定义约束名称
constraint pk_stu_id primary key (id),
constraint uk_stu_cardno unique (cardno),
constraint fk_tea_id foreign key (tid) references teacher (id),
constraint ck_stu_cardno check(length(cardno)>18)*/
/*还可如下这样做,但是约束名称是系统给的
primary key (id),
unique (cardno),
foreign key (tid) references teacher (id),
check (length(cardno)>18)*/
);
-- 如果建表的时候没有加上约束,也可以如下方式新添约束
-- 主键约束
alter table student add constraint pk_stu_id primary key(id);
-- 唯一约束
alter table student add constraint uk_stu_cardno unique(cardno);
-- 外键约束
alter table student add constraint fk_tea_id foreign key (tid) references teacher (id);
-- 检查约束
alter table student add constraint ck_stu_cardno check(length(cardno)>18);
-- 非空约束
alter table student modify(name not null);
-- 删除约束
-- 主键\唯一\检查\非空
alter table student drop primary key;
alter table student drop constraint pk_stu_id;
-- 外键
-- 方式一:先删除子表或者只删除子表的外键约束 然后使用drop table 表名删父表
-- 方式二:drop table 父表名 cascade constraints;
-- 禁用约束:
alter table 表名 disable constraint 约束名;
-- 启用约束
alter table 表名 enable constraint 约束名;