定义:在Oracle中,可以在数据库中定义子程序,这种程序块称为存储过程(procedure)。它存放在数据字典中,可以在不同用户和应用程序之间共享,并可实现程序的优化和重用。
参数:in参数是向存储过程里传入的值,out参数是存储过程向外传出的值。
其模板为:
CREATE OR REPLACE PROCEDURE 存储过程名称
( 变量名 变量参数模式 变量类型,
变量名 变量参数模式 变量类型)
AS|IS
/*声明部分*/
BEGIN
/*执行部分*/
EXCEPTION
/*异常处理部分*/
END 存储过程名称;
例题:
1.创建一个存储过程,以部门号为参数,返回该部门的人数和平均工资。
存储过程部分如下:
create or replace procedure test1(v_deptno in number,members out number,salary out number)
as
begin
select count(*),avg(money) into members,salary from scott.emp where deptno=v_deptno;
end test1;
调用部分如下:
set serveroutput on;
declare
members out number;
salary out number;
begin
test1('财务部',members,salary);
dbms_output.put_line('财务部的人数为'||members||'平均工资为'||salary);
end;
2.创建一个存储过程,以部门号为该存储过程的in类型参数,查询该部门的平均工资,并输出该部门中比平均工资高的员工号、员工名。(for 循环遍历 游标)
存储过程如下:
create or replace procedure test2(v_deptno in number)
as
money number;
begin
select avg(salary) into money from scott.emp where deptno=v_deptno;
dbms_output.put_line('平均工资为'||money);
for v_emp in (select * from scott.emp where deptno=v_deptno and salary>money)
loop
dbms_output.put_line('员工号为'||v_emp.empno||'员工名为'||v_emp.ename);
end loop;
end;
调用部分如下:
declare
begin
test2('财务部');
end;