---
title: "Oracle PL/SQL存储过程，函数，包，触发器的使用"
author: "rainyear"
date: "2012-12-26T03:04:19Z"
tags: []
categories: ["非技术"]
slug: "oracle-pl-sql"
draft: false
lastmod: "2012-12-26T03:04:19Z"
id: 1754135
url: "https://rainyear.iteye.com/blog/1754135"
---

### [Oracle PL/SQL存储过程，函数，包，触发器的使用](http://oma1989.iteye.com/blog/1468726)

- **博客分类：**
- [Oracle](http://oma1989.iteye.com/category/185658)

 

PL/SQL高级编程部分  
无名块不存储在数据库中，并且不能从其他的PL/SQL块中调用  
有名块存储在数据库数据字典中，可以在客户端与服务器端的任何工具和任何应用中运行  
(1).存储过程

(2).存储函数

(3).包

(4).触发器  
过程执行某一动作，函数计算一个值，包将相关的过程函数逻辑上捆绑在一起，触发器隐式执行某一动作  
存储过程和函数是把一个PL/SQL块编译后存进数据库数据字典中，以后可以重复使用的模式对象  
注意：在存储过程和函数中的形式参数及返回结果如果是字符型，不要指定指定长度

**1.存储过程**  
**(1).创建存储过程**

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create \[OR REPLACE] PROCEDURE 过程名\[(参数名\[IN|OUT|IN OUT]数据类型...)]
2. {IS | AS}
3. \[说明部分]
4. BEGIN
5. 语句系列
6. \[EXCEPTION 出错处理]
7. END\[过程名];

 

参数说明：

IN 输入参数：用来从调用环境中向存储过程传递值，即IN模式参数不能出现在赋值语句式边  
OUT输出参数：用来从存储过程中返回值给调用者，在过程体内，必须给OUT模式参数赋值，OUT模式参数  
可以出现在赋值语句的左边.没有值的OUT模式参数不能出现赋值语句的右边.  
IN OUT：输入参数，输出参数.即可从调用者向存储过程传递值，过程执行后又可返回改变后的值给调用者.   
eg:  
给某一指定的员工涨指定数量的工资，该存储过程有两个形式参数：emp\_id和v\_increase，没有指定参数  
的模式，默认是IN 模式.

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create procedure raise\_salary(emp\_id integer, v\_increase real) is
2. BEGIN
3. update emp set sal = sal + v\_increase where empno = emp\_id;
4. commit;
5. end raise\_salary;

   
根据给定的员工号(通过IN模式参数代入)，用OUT模式参数返回员工的姓名,工资和奖金信息.

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create or replace procedure query\_emp(v\_emp\_no   IN emp.empno%type,
2. v\_emp\_name out emp.ename%type,
3. v\_emp\_sal  out emp.sal%type v\_emp\_comm out emp.comm%type) is
4. BEGIN
5. select ename, sal, comm
6. into v\_emp\_name, v\_emp\_sal, v\_emp\_comm
7. from emp
8. where empno = v\_emp\_no;
9. end query\_emp;

 

**2.存储函数**  
(1).创建存储函数的语法如下：

 

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create \[or replace ]function 函数名\[(参数名\[in]数据类型...)] return 数据类型
2. {is|as}
3. \[说明部分]
4. BEGIN
5. 语句序列
6. return (表达式)
7. \[EXCEPTION 例外处理程序]
8. END 函数名;

   
编写一个函数，计算几个人的平均工资，并在函数体的循环过程中输出结果

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

01. create or replace function average\_sal(v\_n in number(3)) return number
02. is
03. cursor c\_emp is select empno,sal from emp;
04. v\_total\_sal emp.sal%type:=0;
05. v\_counter number;
06. v\_emp\_no emp.empno%type
07. BEGIN
08. FOR r\_emp in c\_emp loop exit when c\_emp% rowcount&gt;v\_n or c\_emp%notfound;
09. v\_total\_sal:=v\_total\_sal+r\_emp.sal;
10. v\_counter:=c\_emp%rowcount;
11. v\_emp\_no:=r\_emp.empno;
12. dbms\_output.put\_line('loop='||v\_counter||';empno='||v\_emp\_no);
13. end loop;
14. return (v\_total\_sal/v\_counter);
15. end average\_sal;

 

**注意存储过程与函数的区别**

1...返回值不同:存储函数有零个或多个参数，函数可以有IN参数，但不能有OUT参数。函数只返回一个值，函数值的返回是靠return 子句返回的  
2...存储过程有零个或多个参数，地程可以有IN参数，在调用过程时通过参数列表接受IN参数的输入。过程不返回值，其返回值是靠OUT参数带出来的  
过程可以有零个或多个OUT参数返回结果  
调用过程的语句可以作为单独的可执行语句在PL/SQL块中单独出现  
过程名(实际参数1，实际参数2....)  
函数可以在任何表达式能够出现的地方被调用，调用函数的语句不能作为可执行语句单独出现在PL/SQL块中  
变量名：函数名(实际参数1，实际参数2....);

 

存储过程的调用  
(1).在PL/SQL块中的调用  
eg:

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. DECLARE
2. V\_empno emp.empno%type := 7777;
3. v\_ename emp.ename%type;
4. v\_sal   emp.sal%type;
5. v\_comm  emp.comm%type;
6. BEGIN
7. query\_emp(v\_empno, v\_ename, v\_sal, v\_comm);
8. dbms\_output.put\_line(v\_ename || ' ' || v\_sal || ' ' || v\_comm);
9. END;

 

 

函数的调用

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. DELCARE
2. v\_empno number:=111;
3. v\_sal nubmer;
4. BEGIN
5. v\_sal:=get\_sal(v\_empno);
6. dbms\_output.put\_line(v\_sal);
7. end;

 

(2).在SQL\*PLUS中的调用  
过程的调用  
eg:

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. set serveroutput on/\*激活DBMS\_OUTPUT系统包\*/
2. ACCEPT p\_emp\_no prompt 'please enter the employee number:';/\*接受员工号\*/
3. variable v\_emp\_name varchar2(14);/\*定义存放OUT参数输出结果的变量 \*/
4. variable v\_emp\_sal number;
5. variable v\_emp\_comm number;
6. execute query\_emp(&p\_emp\_no,:v\_emp\_name,:v\_emp\_sal,:v\_emp\_comm);

 

注意在SQL\*PLUS中，用variable定义的变量在引用时，必须前面加昌号(:),用accept接收的变量在引用时，必须前面加& 符号  
函数的调用  
函数不能作为一条语句单独出现，只能出现在别的过程中作为别的过程的参数  
SQL&gt;EXECUTE dbms\_output.put\_line(get\_sal(0000));  
或者  
SQL&gt;SELECT get\_sal(0000) from dual;

 

**3.包**  
**(1).创建包的说明：**

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create \[or replace] package 包名
2. {is|as}
3. 公共变量的定义
4. 公共类型的定义
5. 公共出错处理的定义
6. 公共游标的定义
7. 函数说明
8. 过程说明
9. end;

 

eg:制作一个包的说明，生成一个管理雇员薪水的包sal\_package,其中包括一个为雇员加薪的过程和降薪的过程  
并且在包中还有两个记录所有雇员薪水增加和减少的全局变量

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create package sal\_package is
2. procedure raise\_sal(v\_empno emp.empno%type), v\_sal\_increment emp.sal%type);
3. procedure reduce\_sal(v\_empno emp.empno%type, v\_sal\_reduce emp.sal%type);
4. v\_raise\_sal  emp.sal%type := 0;
5. v\_reduce\_sal emp.sal%type := 0;
6. end;

 

 

**创建包的主体**

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create \[or replace] package BODY 包名
2. {is|as}
3. 公共变量的定义
4. 公共类型的定义
5. 公共出错处理的定义
6. 公共游标的定义
7. 函数说明
8. 过程说明
9. end;

 制作sal\_package包的包主体

 

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

01. create or replace package body sal\_package is
02. procedure raise\_sal(v\_empno emp.empno%type, v\_sal\_increment emp.sal%type) is
03. BEGIN
04. UPDATE emp set sal = sal + v\_sal\_increment where empno = v\_empno;
05. commit work;
06. v\_raise\_sal := v\_raise\_sal + v\_sal\_increment;
07. end;
08. procedure reduce\_sal(v\_empno emp.empno%type, v\_sal\_reduce emp.sal%type) is
09. BEGIN
10. update emp set sal = sal - v\_sal\_reduce where empno = v\_empno;
11. commit work;
12. v\_reduce\_sal := v\_reduce\_sal + v\_sal + reduce;
13. end;
14. end;

 

包的调用:包名.过程名  
SQL&gt;EXECUTE sal\_package.raise\_sal(111,23423);

 

**4.触发器**  
eg:  
制作一个数据库触发器,将那些超过其工种工资范围的员工信息记录到audit\_message表中,在sal\_guide记录  
了每一工种的工资范围

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

01. create or replace trigger check\_sal
02. before insert or update of sal, job on emp
03. for each row
04. when (new.job &lt;&gt; 'persident')
05. DECLARE
06. v\_minsal sal\_guide.minsal%type;
07. v\_maxsal sal\_guide.maxsal%type;
08. e\_sal\_out\_of\_range exception;
09. BEGIN
10. select minsal, maxsal
11. into v\_minsal, v\_maxsal
12. from sal\_guide
13. where job = :new.job;
14. if :new.sal &lt; v\_minsal or :new :sal &gt; v\_maxsal then
15. raise e\_sal\_out\_of range;
16. end if;
17. exception
18. when e\_sal\_out\_of\_range then
19. insert into audit\_message
20. (line\_nr, line)
21. values
22. (1,
23. 'Salary' || TO\_CHAR(:new.sal) || 'is out of range for employee' ||
24. TO\_CHAR(:new.empno));
25. END;

 

(1).触发器的组成  
触发时间：before after  
触发事件：insert update delete  
触发器类型：statement,row (语句级，行级)  
触发器体(完整的PL/SQL块)  
触发器可分语句级触发器，行级触发器  
(2).语句级触发器  
创建语法如下：

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create \[or replace] trigger trigger\_name
2. {before|after} event1\[or event2] on table\_name

 

eg:  
创建一个before 型语句级触发器，限制一周内向emp表插入数据的时间，如果是周六，周日  
或晚上6点到第二天早上8点之间插入，则中断操作，并提示用户不允许在此时间向emp表插入

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create or replace trigger secure\_emp
2. before insert on emp
3. BEGIN
4. IF (TO\_CHAR(sysdate, 'DY') IN ('SAT', 'SUN')) or
5. (TO\_CHAR(sysdate, 'HH24') NOT BETWEEN '8' and '18') then
6. raise\_application\_error(-20500,
7. 'you may only insert into emp during normal hours.');
8. END IF;
9. END;

 

(3).使用触发器谓词(inserting,updating,deleting)  
通过谓词可以创建一个包含多个触发事件的触发器  
对上例进行扩展不但限制插入数据的时间，还限制进行数据修改和删除的时间

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

01. create or replace trigger secure\_emp
02. before delete or insert or update on emp
03. BEGIN
04. if (TO\_CHAR(sysdate,'DY' IN('SAT','SUN'))  OR (TO\_NUMBER(sysdate,'HH24')NOT BETWEEN 8 AND 18 )THEN
05. if deleting then
06. raise\_application\_error(-20502,'You may only deletefrom emp during normal hours. ');
07. elsif inserting then
08. raise\_application\_error(-20500,'You may only insert into emp during mormal hours');
09. else
10. RAISE\_APPLICATION\_ERROR(-20504,'You may only update emp table during normal hours.');
11. end if ;
12. end if ;
13. end;

 

(4).行级触发器  
创建语法

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create \[or replace]trigger trigger\_name
2. {before|after} event1\[or event2....] on table\_name
3. for each row \[when restricting\_condition]

   
PL/SQL  
eg:创建一个行级触发器，将每个用户对数据库emp表进行数据库操纵(插入，更新，删除)的次数记录到  
audit\_table表中

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

01. create or replace trigger audit\_emp
02. after delete or insert or update on emp
03. for each row
04. BEGIN
05. IF DELETING THEN
06. update audit\_table
07. set del = del + 1
08. where user\_name = user
09. and table\_name = 'emp'
10. and column\_name is null;
11. elsif inserting then
12. update audit\_table
13. set ins = ins + 1
14. where user\_name = user
15. and table\_name = 'emp'
16. and column\_name is null;
17. else
18. update audit\_table
19. set upd = upd + 1
20. where user\_name = user
21. and table\_name = 'emp'
22. and column\_name is null;
23. end if;
24. end;

   
使用行级触发器的标识符(:OLD和:NEW)  
在列名前加上：OLD标识符表示该列变化前的值，加上：NEW标识符表示变化后的值  
eg:  
在行级触发器加WHEN限制条件，根据销售员工资的改变自动计算销售员的奖金

Sql代码  [![收藏代码](http://oma1989.iteye.com/images/icon_star.png)](http://oma1989.iteye.com/blog/1468726 "收藏这段代码")

1. create or replace trigger derive\_comm
2. before update of sal on emp
3. for each row
4. when (new.job = 'SALESMAN')
5. BEGIN
6. :new.comm := :old.comm * (:new.sal / :old.sal);
7. end;