Oracle 存储过程使用示例

2014-11-24 18:00:15 · 作者: · 浏览: 1

因为工作的需要,最近一直在写存储过程。 工作了 3 年,一直都是做管理,也没有正儿八经的去写过存储过程, 这次正好可以好好练习一下。


在这里说一条使用存储过程很重要的理由: 存储过程只在创造时进行编译,以后每次执行存储过程都不需再重新编译,而一般 SQL 语句每执行一次就编译一次 , 所以使用存储过程可提高数据库执行速度。


-----------------------


1. 存储过程格式


* Formatted on 2011/1/17 13:20:44 (QP5 v5.115.810.9015) */


CREATE OR REPLACE procedure proc_trade (


v_tradeid in number , -- 交易 id


v_third_ip in varchar2 , -- 第三方 ip


v_third_time in date , -- 第三方完成时间


v_thire_state in number , -- 第三方状态


o_result out number , -- 返回值


o_detail out varchar2 -- 详细描述


)


as


-- 定义变量


v_error varchar2 ( 500 );


begin


-- 对变量赋值


o_result := 0 ;


o_detail := ' 验证失败 ' ;



-- 业务逻辑处理


if v_tradeid > 100 then


insert into table_name (...) values(...);


commit;


elsif v_tradeid < 100 and v_tradeid > 50 then


insert into table_name (...) values(...);


commit;


else


goto log;


end if;


-- 跳转标志符,名称自己指定


<>


o_result := 1 ;


-- 捕获异常


exception


when no_data_found


then


result := 2 ;


when dup_val_on_index


then


result := 3 ;


when others


then


result := - 1 ;


end proc_trade ;



在上面这个存储过程中使用了输入参数,并返回输出参数,这里的参数类型是我们自己指定的。 这种写法可行,但是最好使用 %type 来获取参数的类型 (table_name.column_name%TYPE) 。 这样就不会出现参数类型的错误。



如:


CREATE OR REPLACE PROCEDURE spdispsms (


aempid IN otherinfo . empid% TYPE,


amsg IN otherinfo . msg% TYPE,


abillno IN otherinfo . billno% TYPE,


ainfotype IN otherinfo . infotype% TYPE,


aopid IN otherinfo .OPERATOR % TYPE,


ainfoid OUT otherinfo . infoid% TYPE,


RESULT OUT INTEGER


)