oracle存储过程粗解

存储过程创建的语法:

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_outputPut_line(‘打印信息’);

    Elsif (判断条件) then

       Dbms_outputPut_line(‘打印信息’);

    Else

       Raise 异常名(NO_DATA_FOUND;

    End if;

Exception

    When others then

       Rollback;

End;

这个语法结构基本就这样吧,但是它比较灵活。存储过程其实用熟练了之后在实际开发过程中的意义个人觉得还是很大的,很方便,最基础的就是会减少程序和数据库交互的次数。

上个例子更理解一下吧。

 1 create or replace procedure test_1(username_1 VARCHAR2,userid_1  NUMBER) is
 2   --用到的参数
 3   countNum number;
 4   lineno_2 number;
 5  begin
 6    lineno_2:=0;
 7  --根据in的参数userid_1查询用户表中是否有数据存在
 8  select nvl(count(1),0) into countNum from user_info where user_code=userid_1 and user_role='SYS_ROLE';
 9 
10 
11    loop--十次循环后跳出
12      exit when lineno_2 > 10;
13        if countNum>0 then
14 
15           insert into user_info_copy(user_no,user_name) values (userid_1,username_1);--表数据复制十次
16           lineno_2:=lineno_2+1;
17 
18        end if;
19   end loop;
20     update user_status set status=0,modtime=sysdate where lngrsOid=userid_1;--更新用户状态
21     commit;
22   end;

这个小例子循环可以换种方式会更简单,用游标就好,这里只是想尽量直观一点,好理解,编码的时候部分的逻辑判断可以一起挪到存储过程里,而不用查询count调一次数据库,再逻辑处理调一次数据库,这样效率会有很大不同。

原文地址:https://www.cnblogs.com/qiujiababy/p/8206095.html