用 CREATE PROCEDURE命令来建立存储过程和存储函数

语法:

  create [or replace] PROCEDURE 过程名(参数列表)

  AS

  PLSQL子程序体;

  as后面跟说明变量,光标。。。。

存储过程只能创建或者替换 不能修改

 

create or replace procedure sayhelloworld

as

--说明部分

begin

  dbms_output.put_line('Hello World'); --打印

end;

/

调用存储过程

1.execute可以缩写成exec

  exec sayhelloworld();

2.放在另一个存储过程里执行

 begin

  sayhelloworld();

  sayhelloworld();

 end;

 /

=================================================================

带参存储过程

--as相当于declare

--in 指明时输入参数,out指明输出参数,into赋值

--给指定员工涨100块钱的工资,并且打印涨前和涨后的薪水

create or replace procedure raisesalary(eno in number)

as

--定义一个变量保存涨前的薪水

 psal emp.sal%type;--以员工薪水(emp.sal)的类型指定给psal

begin

  --得到员工涨前的薪水

  select sal into psal from emp where empno = eno;

  --给员工涨100

  update emp set sal=sal+100 where empno=eno;

  --需不需要commit?

  --注意:一般不在存储过程或者存储函数中,commit和rollback。

  --打印

  dbms_ouput.put_line('涨前:'||psal||'   涨后:'||(psal + 100)||);

end;

/

如何调用:

begin

  raisesalary(7839);

  raisesalary(7566);

  commit;--在同一个事务中处理

end;

/

===============================================================

存储函数

函数(Function)为一命名的存储程序,可带可不带参数,并返回一计算值。

函数和过程结构类似,但必须有一个RETURN子句,用于返回函数值。

create [or replace] FUNCTION 函数名(参数列表)

return 函数值类型

AS

PLSQL子程序体;

 

--存储函数:查询某个员工的年收入

create or replace function queryempincome(eno in number)

return number

as

  --定义变量保存员工的薪水和奖金

  psal emp.sal%type;

  pcomm emp.comm%type;

begin

  --得到该员工的月薪和奖金

  select sal,comm into psal,pcomm from emp where empno=eno;

  --直接返回年收入

  retrun psal*12+nvl(pcomm,0);

  --如果E1为NULL,则函数返回E2,否则返回E1本身。

  --nvl2,NVL2(E1, E2, E3)的功能为:如果E1为NULL,则函数返回E3,若E1不为null,则返回E2。

end;

/

========================================================================

in 和out函数

一般情况下,如果只有一个返回值那么用存储函数,否则用存储过程

--out参数:查询某个员工姓名 月薪 和职位

create or replac procedure queryempinform(eno in number,

                       pename out varchar2,

                       psal       out number,

                       pjob       out varchar2)

as

begin

  --得到该员工的姓名 月薪和职位

  select ename,sal,empjob intopename,psal,pjob from emp where empno=eno;

end;

/

================================================================== 

 在应用程序中访问存储函数和存储过程类似jdbc

==================================================================

 案例:查询某个部门中所有员工的所有信息(结果是一个集合)

在程序包右击创建包头,输入包名自动创建

--包头

CREATE OR REPLACE

PACKAGE MYPACKAGE AS    --MYPACKAGE:包名称

  type empcursor is ref cursor;  --声明empcursor类型是光标(cursor)

  procedure queryEmpList(dno in number,empList out empcursor);--声明存储过程 

END MYPACKAGE;

右击包名上右击,选择创建主体,会自动创建包体

CREATE OR REPLACE

PACKAGE BODY MYPACKGE AS

procedure queryEmpList(dno in number,empList out empcursor) AS

BEGIN

  --打开光标

  open empcursor for select * from emp where deptno=dno;  --open 光标 for sql语句

 END queryEmpList;

END MYPACKAGE; 

==============由于这个存储过程在在包下面所以应用程序中访问的时候要带上包名=============

对于in参数需要赋值,对应out参数需要声明,在应用程序中访问。