一.在plsql中创建一个存储过程
打开plsql,右键procedures,新建。
如果新建毫无反应
直接文件-新建-程序窗口-空白,新建一个程序窗口
存储过程创建语法:
create [or replace] procedure 存储过程名(param1 in type,param2 out type)
as
变量1 类型(值范围);
变量2 类型(值范围);
begin
select count(*) into 变量1 from 表a where列名=param1;
if (判断条件) then
select 列名 into 变量2 from 表a where列名=param1;
dbms_output。put_line(‘打印信息’);
elsif (判断条件) then
dbms_output。put_line(‘打印信息’);
else
raise 异常名(no_data_found);
end if;
exception
when others then
rollback;
end;
二:实例:写存储过程(例子)
--创建一个名为p_contract_purchase_import的存储过程
create or replace procedure p_contract_purchase_import(
--以下写存储过程的外部参数(传入的参数)
--格式为:参数名 in 参数类型
--注意,这里的varchar不标注大小
v_in_subcompanyid in varchar2, --专业分公司
v_in_purcontractmoney in number, --采购合同金额
v_in_partybname in varchar2, --供应商名称
--设置一个返回值
v_o_ret out number --返回结果0:成功;1:失败; 4:查不到供应商; 5:添加关联失败;6:新增采购合同失败
)
--以下写内部参数
--格式为:参数名称 参数类型
--注意,这里的varchar需要标注大小
as
v_supplierid integer; --供应商编号
v_partybaccount varchar2(100);--收款账号
v_sqlerrm varchar2(4000);--错误详情
--存储过程开始
begin
--为某些变量赋初值
--格式为 变量名 := 值
v_o_ret := 1;
v_supplierid := '';
v_partybaccount := '';
--写具体的操作语句(sql)
--if语句
if(v_in_partybname is not null) then
begin
select t.supplierid,t.partybaccount,t.partybbank ,t.partybname
into v_supplierid,v_partybaccount,v_partybbank,v_partybname
from t_supplier t where t.partybname=trim(v_in_partybname) and t.subcompanyid=trim(v_in_subcompanyid);
--抛异常
exception
when others then
v_o_ret := 4 ; --找不到该供应商
v_partybname := v_in_partybname;
-- 将异常原因写入存储过程日志表
v_sqlerrm := sqlerrm;
insert into t_log_dberr
(errtime, errmodel, errdesc)
values
(sysdate,
'procedures',
'p_contract_purchase_import:ret=' || v_o_ret ||','||
v_sqlerrm);
commit;
end ;
end if;
······
end ;
commit;
v_o_ret :=0 ;
return;
exception
when others then
rollback;
-- 插入异常原因
v_sqlerrm := sqlerrm;
insert into t_log_dberr
(errtime, errmodel, errdesc)
values
(sysdate,
'procedures',
'p_contract_purchase_import:ret=' || v_o_ret ||','||
v_sqlerrm);
commit;
--存储过程结束
end p_contract_purchase_import;
1.注意begin 和 end成对
2.务必将错误内容打印出来。否则,有的时候,就算调试看出来时哪一个语句的错误,也闹不明白错在哪里
三.存储过程调试
1.按f8或是菜单栏第三行第二个执行按键编译存储过程。此时,如果有语法上的明显错误,plsql会给予提示。
2.在procedures中找到要调试的存储过程,右键,选测试。注意,要记得勾选添加调试信息啊。
3.打开调试窗口,填写输入参数
4.点测试窗口的调试按键(如图中画圈的位置)开始调试
5.逐步调试
点击单步调试,主要就是使用这个来进行调试。执行到的代码会高亮显示,此外,注意图中4的位置,可以在这里输入变量的名字,来查看变量的当前值。
分别为跳出单步执行和全部执行,调试时不推荐使用。
单步调试过程中,如果执行到哪一步直接跳转到了exception结束,那么,就是这一步出来问题,可以记住这个位置,再次调试,通过查看这附近变量的值,以及查看错误日志记录的错误详情,来确认出错的具体原因并进行修改。
四.在java中调用
存储过程调试好之后,就可以在java中调用该存储过程。
logger.info("调用存储过程p_contract_purchase_import");
//存储过程名称。有多少个传入参数打几个问号(包括v_o_ret)
string procname="{call p_contract_purchase_import(,,,) }";
datasource ds = sessionfactoryutils.getdatasource(this.gethibernatetemplate().getsessionfactory());
connection conn = null;
callablestatement call = null;
//resultset rs =null;
try
{
//创建连接
conn = ds.getconnection();
call = conn.preparecall(procname);
//传入数据
call.setstring(1, (importlist.get(0)).trim());
if(ratio_amount==null) {
call.setstring(2,null);
} else {
call.setlong(2, ratio_amount);
}
call.setstring(3, (importlist.get(2)).trim());
//第四个参数是作为返回值存在的
call.registeroutparameter(4, types.bigint);
//执行存储过程
call.executeupdate();
//获取返回的结果
ret = call.getint(17) ;
logger.info("ret:"+ret); ;//call.getint(6));
try
{
//关闭连接
call.close();
call = null ;
conn.close();
conn = null ;
} catch (sqlexception e) {
// todo auto-generated catch block
}
}catch (sqlexception e){
logger.error("打开存储过程错误:",e);
}
finally{
try {
if (call != null) {
call.close();
}
if (conn != null) {
conn.close();
}
} catch (sqlexception e) {
// todo auto-generated catch block
conn = null;
}
}
需要注意的是,call.setlong()不可以传入空值。如果内容有可能为空的话,set之前需要判断是否为空,不为空才能使用setlong()方法,否则,要使用setstring方法。
五:注意事项:
存储过程参数不带取值范围,in表示传入,out表示输出
变量带取值范围,后面接分号
在判断语句前最好先用count(*)函数判断是否存在该条操作记录
用select … into … 给变量赋值
在代码中抛异常用 raise+异常名
已命名的异常:
| 命名的异常 | 产生原因 |
|---|---|
| access_into_null | 未定义对象 |
| case_not_found | case 中若未包含相应的 when ,并且没有设置else 时 |
| collection_is_null | 集合元素未初始化 |
| curser_already_open | 游标已经打开 |
| dup_val_on_index | 唯一索引对应的列上有重复的值 |
| invalid_cursor | 在不合法的游标上进行操作 |
| invalid_number | 内嵌的 sql 语句不能将字符转换为数字 |
| no_data_found | 使用 select into 未返回行,或应用索引表未初始化的 |
| too_many_rows | 执行 select into 时,结果集超过一行 |
| zero_divide | 除数为 0 |
| subscript_beyond_count | 元素下标超过嵌套表或 varray 的最大值 |
| subscript_outside_limit | 使用嵌套表或 varray 时,将下标指定为负数 |
| value_error | 赋值时,变量长度不足以容纳实际数据 |
| login_denied | pl/sql 应用程序连接到 oracle 时,提供了不正确的用户名或密码 |
| not_logged_on | pl/sql 应用程序在没有连接 oralce 数据库的情况下访问数据 |
| program_error | pl/sql 内部问题,可能需要重装数据字典& pl./sql系统包 |
| rowtype_mismatch | 宿主游标变量与 pl/sql 游标变量的返回类型不兼容 |
| self_is_null | 使用对象类型时,在 null 对象上调用对象方法 |
| storage_error | 运行 pl/sql 时,超出内存空间 |
| sys_invalid_id | 无效的 rowid 字符串 |
| timeout_on_resource | oracle 在等待资源时超时 |
六:基本语法
1. 基本结构
create or replace procedure 存储过程名字
(
参数1 in number,
参数2 in number
) is
变量1 integer :=0;
变量2 date;
begin
--执行体
end 存储过程名字;
2. select into statement
将select查询的结果存入到变量中,可以同时将多个列存储多个变量中,必须有一条记录,否则抛出异常(如果没有记录抛出no_data_found)
例子:
begin
select col1,col2 into 变量1,变量2 from typestruct where xxx;
exception
when no_data_found then
xxxx;
end;
3. if 判断
if v_test=1 then
begin
do something
end;
end if;
4. while 循环
while v_test=1 loop
begin
xxxx
end;
end loop;
5. 变量赋值
v_test := 123;
6. 用for in 使用cursor
is cursor cur is select * from xxx; begin for cur_result in cur loop begin v_sum :=cur_result.列名1+cur_result.列名2 end; end loop; end;
7. 带参数的cursor
cursor c_user(c_id number) is select name from user where typeid=c_id;
open c_user(变量值);
loop
fetch c_user into v_name;
exit fetch c_user%notfound;
do something
end loop;
close c_user;
8. 用pl/sql developer debug
连接数据库后建立一个test window,在窗口输入调用sp的代码,f9开始debug,ctrl+n单步调试
八:关于oracle存储过程的若干问题备忘
1.在oracle中,数据表别名不能加as,如:
select a.appname from appinfo a;-- 正确 select a.appname from appinfo as a;-- 错误
也许,是怕和oracle中的存储过程中的关键字as冲突的问题吧
2.在存储过程中,select某一字段时,后面必须紧跟into,如果select整个记录,利用游标的话就另当别论了。
select af.keynode into kn from appfoundation af where af.appid=aid and af.foundationid=fid;-- 有into,正确编译 select af.keynode from appfoundation af where af.appid=aid and af.foundationid=fid;-- 没有into,编译报错,提示:compilation error: pls-00428: an into clause is expected in this select statement
3.在利用select…into…语法时,必须先确保数据库中有该条记录,否则会报出”no data found”异常。
可以在该语法之前,先利用select count(*) from 查看数据库中是否存在该记录,如果存在,再利用select…into…
4.在存储过程中,别名不能和字段名称相同,否则虽然编译可以通过,但在运行阶段会报错
--正确 select keynode into kn from appfoundation where appid=aid and foundationid=fid; --错误 select af.keynode into kn from appfoundation af where af.appid=appid and af.foundationid=foundationid; -- 运行阶段报错,提示ora-01422:exact fetch returns more than requested number of rows
5.在存储过程中,关于出现null的问题
假设有一个表a,定义如下:
create table a( id varchar2(50) primary key not null, vcount number(8) not null, bid varchar2(50) not null -- 外键 );
如果在存储过程中,使用如下语句:
select sum(vcount) into fcount from a where bid='xxxxxx';
如果a表中不存在bid=”xxxxxx”的记录,则fcount=null(即使fcount定义时设置了默认值,如:fcount number(8):=0依然无效,fcount还是会变成null),这样以后使用fcount时就可能有问题,所以在这里最好先判断一下:
if fcount is null then
fcount:=0;
end if;
这样就一切ok了。