Oracle存储过程和存储函数

来源:互联网 发布:药店进销存软件免费版 编辑:程序博客网 时间:2024/06/07 06:55

存储过程(Stored Procedure)是在大型数据库系统中,一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。存储过程是数据库中的一个重要对象,任何一个设计良好的数据库应用程序都应该用到存储过程。

 

创建存储过程语法:

create [or replace] PROCEDURE 过程名[(参数名 in/out数据类型)]  

AS

begin

        PLSQL子程序体;

End;

 

或者

 

create [or replace] PROCEDURE 过程名[(参数名 in/out数据类型)]  

is

begin

        PLSQL子程序体;

End  过程名;

 

范例1:给指定的员工涨100工资,并打印出涨前和涨后的工资

分析:我们需要使用带有参数的存储过程

create or replace procedure addSal1(enoin number)is

  pemp myemp%rowtype;

begin

  select *into pempfrom myempwhere empno = eno;

  update myempset sal = sal +100 where empno = eno;

  dbms_output.put_line('涨工资前' || pemp.sal ||'涨工资后' || (pemp.sal +100));

end addSal1;

 

调用

begin

  -- Call the procedure

  addsal1(eno => 7902);     

  commit;

end;

4.存储函数

create or replace function 函数名(Name in type, Name out type, ...) return数据类型 is

  结果变量 数据类型;

begin

  

  return(结果变量);

end[函数名];

 

存储过程和存储函数的区别

一般来讲,过程和函数的区别在于函数可以有一个返回值;而过程没有返回值。 

但过程和函数都可以通过out指定一个或多个输出参数。我们可以利用out参数,在过程和函数中实现返回多个值。

 

范例:使用存储函数来查询指定员工的年薪

create or replace function empincome(enoin emp.empno%type)return number is

  psal  emp.sal%type;

  pcomm emp.comm%type;

begin

  select t.salinto psalfrom emp twhere t.empno = eno;

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

end;

使用存储过程来替换上面的例子

create or replace procedure empincomep(enoin emp.empno%type, incomeout number)is

  psal emp.sal%type;

  pcomm emp.comm%type;

begin

  select t.sal, t.comminto psal, pcommfrom emp twhere t.empno = eno;

  income := psal*12+nvl(pcomm,0);

end empincomep;

 

调用:

declare

  income number;

begin

  empincomep(7369, income);

  dbms_output.put_line(income);

end;

原创粉丝点击