---
title: "oracle实战2续"
author: "roway"
date: "2012-06-20T15:27:00Z"
tags: ["Oracle"]
categories: ["数据库"]
slug: "oracle-2"
draft: false
lastmod: "2012-11-13T13:46:26Z"
id: 1722909
url: "https://roway.iteye.com/blog/1722909"
---

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 &gt;=18 and age&lt;=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,'maliu@sohu.com');

启用约束 (当数据表中包含了违反约束的数据时，约束启用时就会报错！需要先处理违反  
约束的值，然后在启用约束。)

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;