create table department(
deptno number(2) not null,
dname varchar2(30) not null,
location varchar2(30)
)
--设置部门表的主键
alter table department
add constraint dept_deptno_pk primary key(deptno);
create table employee(
empno number(4) not null,
ename varchar2(30) not null,
age number(3) null,
salary number(7,2),
deptno number(2)
)
alter table employee
add constraint employee_eno_pk primary key(empno);
--需要为员工表设置外键
alter table employee
add constraint employee_deptno_fk foreign key (deptno) references department(deptno);
--主外键约束对于INSERT、UPDATE、DELETE动作的影响????
插值的影响:
需要向包含主键的表中先插入数据,然后再向包含有外键的表中插入数据。
insert into department values(10,'市场部','一号办公楼');
insert into department values(20,'财务部','三号办公楼');
insert into department values(30,'行政部','一号办公楼');
insert into employee values(1057,'张三',35,3500,10);
insert into employee values(1048,'李四',27,3000,30);
更新数据:
遇到能够去更新主键的情况几乎不存在。
如果遇到确实这样的情况
update department set deptno=40 where deptno=30;
修改主外键的约束。说是修改,其实是将原来的主外键约束删除,然后再重建。
alter table employee
drop constraint employee_deptno_fk;
alter table employee
add constraint employee_deptno_fk foreign key (deptno) references department(deptno)
on delete set null;
级联删除的情况:
当删除了主表中的某一项记录时,所有子表中的子记录也同时被删除。
alter table employee
drop constraint employee_deptno_fk;
alter table employee
add constraint employee_deptno_fk foreign key (deptno) references department(deptno)
on delete cascade;
使用条件约束
alter table employee
add constraint emp_age_ck check (age >=18 and age<=60);
insert into employee values(1047,'王五',60,3000,30);
alter table employee
add email varchar2(30);
--使用唯一性约束,限制列的取值不能够重复
alter table employee
add constraint emp_email_UK UNIQUE (email);
--启用约束和禁用约束
在某些情况下,当我们需要暂时停用约束,处理表中的一些数据以后,再启用约束。
禁用约束: alter table employee disable constraint emp_age_ck ;
insert into employee values(1652,'马六',65,3000,30,'[email protected]');
启用约束 (当数据表中包含了违反约束的数据时,约束启用时就会报错!需要先处理违反
约束的值,然后在启用约束。)
alter table employee enable constraint emp_age_ck ;
//需要建立一个序列
//通过触发器结合序列产生自动增长的列
create or replace trigger userinfo_trig
before insert on userinfo
for each row
begin
Select userinfo_seq.Nextval Into :New.userid From dual;
end userinfo_trig;