orcle数据库存储过程和存储函数初学总结

来源:互联网 发布:淘宝产品ps调色 编辑:程序博客网 时间:2024/05/19 13:21
先看一个简单的存储过程,不带参数
create or replace Procedure sayhelloworldasbegin   dbms_output.put_line('hello world');end;

调用存储过程的俩个方法:

1.命令行方法:execute sayhelloworld();

2.PL/SQL方法

begin   --dbms_output.put_line('hello world');   sayhelloworld();   sayhelloworld();end;


带参数的存储过程(in表示输入参数)

create or replace procedure raisesalary(eno in number)aspsal emp.sal%type;begin  select sal into psal from emp where empno=eno;    update emp set sal=sal+100 where empno=eno;    dbms_output.put_line('before:'||psal||'after:'||(psal+100));end;
这里在存储过程中也可以用commit和rollback,但是一般不建议使用。因为不好判断当前事务。谁使用谁提交谁回滚。

set serveroutput onbegin   raisesalary(7839);   raisesalary(7566);   commit;end;/


存储函数

这里要注意的是下面return表达式中只要有一项为空,这个表达式的返回值就为空

这里要使用一个虑空函数将空过滤成0

create or replace function queryempincome(eno in number)return numberas  psal emp.sal%type;  pcomm emp.comm%type;begin  select sal,comm into psal,pcomm from emp where empno = eno; --缕空函数nvl  return psal*12+nvl(pcomm,0);end;


存储过程和存储函数的区别就是有没有return返回语句

  存储过程和存储函数都可以有out参数

  存储函数和存储过程都可以有多个out参数

  存储过程可以通过out参数实现返回值

通常我们有一个原则:如果只有一个返回值用存储函数,有多个返回值用存储过程。


如何在java应用程序中调用存储过程和存储函数,这个jdk api中查找statement类中,有

CallableStatement接口

{?= call <procedure-name>[(<arg1>,<arg2>, ...)]}   {call <procedure-name>[(<arg1>,<arg2>, ...)]}
分别是调用存储函数和存储过程

思考:out参数太多怎么整?
           如何使用out处理一个集合类型的返回值呢?
       当然是使用游标了
这里要用到包这个新内容

右键点击新建会自动生成包头,包体
练习小实例
包头
CREATE OR REPLACE PACKAGE MYPACKAGE AS   type empcursor is ref cursor;  procedure queryEmpList(dno in number,empList out empcursor);  /* TODO enter package declarations (types, exceptions, methods etc) here */ END MYPACKAGE;
包体
CREATE OR REPLACEPACKAGE BODY MYPACKAGE AS  procedure queryEmpList(dno in number,empList out empcursor) AS  BEGIN    --打开光标    open empList for select * from emp where deptno=dno;  END queryEmpList;END MYPACKAGE;






  







原创粉丝点击