oracle存储过程--入门与调试
例子如下:
create or replace procedure pro_one(p_one in number,
p_two out varchar2,
p_three in out varchar2) is
--as
--变量声明部分
v_str1 varchar2(32) := '初始值方式1';
v_str2 varchar2(32) default '初始值方式2';
v_str3 varchar2(32); --空值
v_num4 number default 0;
--代码块部分
/*代码块至少要有一句可执行的代码,否则报错,如果什么也不做,可以写NULL;*/
begin
dbms_output.put_line('传参:' || 'p_one:' || p_one);
dbms_output.put_line('变量:' || v_str1 || ' , ' || v_str2 || ' , ' ||
v_str3 || ' , ' || v_num4);
p_three := p_three || 'changed';
select count(*) into v_num4 from lsy_codebook where id = p_one;
if v_num4 <= 0 then
begin
p_two := '';
p_three := '数据库无此记录!';
dbms_output.put_line('数据库无此记录!');
end;
elsif v_num4 > 1 then
raise too_many_rows; --抛出异常
else
begin
update lsy_codebook set description = p_three where id = p_one;
commit;
p_two := p_three;
p_three := p_one || ' update success';
end;
end if;
--异常捕获
exception
when no_data_found then
begin
dbms_output.put_line('not found ,update failed.');
p_three := 'Exception Info:' || p_one || ' not found ,update failed.';
end;
when too_many_rows then
begin
dbms_output.put_line('too_many_rows ,update failed.');
p_three := 'Exception Info:' || p_one ||
' too_many_rows ,update failed.';
end;
when others then
begin
rollback;
p_three := 'Exception Info:' || p_one ||
' others exception ,update failed.';
end;
end pro_one;
从上可以看出,存储过程的定义结构分3部分。一是声明部分,这里初次简历存储过程是最好使用create procedure xxx,因为一旦你起的名字在库中已经存在,你就把存在的覆盖掉了。这个概率很小,但是错误很低级。建立后再改成create or replace procedure xxx。二是变量声明部分,这个部分可以没有,如果你不用到变量的话。对比java的类,这个部分像声明全局变量。三就是代码块部分。在begin end存储过程名之间。在存储过程中我们使用begin 和 end 来代替我们习惯的{}。个人感觉{}更好,但是甲骨文的那帮人有自己的想法。
需要注意的有:存储过程方法可以没有任何参数,例create or replace procedure pro_one is。参数的输入输出类型有3种,in,out,in out。简单说就是in类型的参数在参进来的时候就有值,它只能被读取,不能被赋值;out类型只能被赋值,不能把值付给别的变量。In out类型包含以上两种功能。为什么会这样设计呢?对比java,存储过程有参数,所以像方法。而存储过程的返回值是没有的,不能像java方法中用等号来获取结果,所以它的返回值只能赋给参数变量,来保存结果。在参数列表中参数的类型不能有长度定义,在变量的声明块中,变量必须有长度定义。
语法很简单,这篇主要讲怎么使用pl/sql调试。
建立存储过程可以世界用sql window。最好用program window。或者在对象面板中找到Procedures右键new。建立后用program window打开才会有错误提示信息(右键edit)。
F8执行后,如果有错误或警告,就会提示。
存储过程的调试步骤:
右键Add debug infomation。右键test。就会打开测试窗口。
左上方的齿轮或者F9即使开始执行。
在下方会把变量列出来,我们可以在下方输入变量的值,看代码中的=>指向下方变量名。
这是plsql提供的一个方便的功能,我们可以不用它,在代码部分自己生命变量,再传入。
断点设置;
在需要的地方,在代码行的左边可以点击就可以添加断点(红色的是断点,绿色的是书签)。
或者右键选择set breakpoint。
对上面的输入我们可以看看打印和变量结果。
现在我们不用plsql的变量关联输入,我们在代码中自定义变量,来测试。
Declare
p_one number :=501;
p_two varchar2(32) :='';
p_three varchar2(32) :='new value 333';
begin
-- Call the procedure
--null;
dbms_output.put_line('调用前:p_one:'||p_one||',p_two:'||p_two||',p_three:'||p_three);
pro_one(p_one,p_two, p_three);
dbms_output.put_line('调用后:p_one:'||p_one||',p_two:'||p_two||',p_three:'||p_three);
end;
结果的查看和下面的变量列表就没关系了,我们从打印看信息: