Oracle存储过程总结和使用

建一个存储过程

create or replace procedure findclass --创建或修改存储过程,存储过程名为findclass
is/as  //声明  
totalClass number(1); --创建一个数字类型的变量,totalClass
begin // 执行  
select count(*) into totalClass from class; --把count计数出来的数量 通过into赋值给totalClass变量
exception//存储过程异常  
	when  ...
	then   ... 
end;

其中IS关键字替换为AS关键字结果不会出现任何变化,大多认为他们是等同的,但也有一种说法解释为:一般package或者单独的function, procedure 都用AS,package中的function, procedure 用IS。

执行存储过程,这里我用的是PLSQL这个工具,所以有三种执行方法,其中有两种是代码执行,一直是工具执行

--执行存储过程方法1::call
call findclass();

--执行存储过程方法2:begin end
begin
findclass();
end;

执行存储过程的第三种方法,也是开发过程中最常用的方法,就是PLSQL工具自带的test方法执行存储过程,该方法可以对存储过程进行断点调试 

在Navicat中存储过程在函数里面。
在PLSQL中所有的存储过程都可以在Procedures文件夹中找到

这里写图片描述

找到需要执行的存储过程右键出现选择菜单

这里写图片描述

点击test出现如下界面

这里写图片描述

这里写图片描述

以上就是我们执行的一个最简单的存储过程,但是在实际开发过程中,我们是会带有参数条件的存储过程。

存储过程的参数有三种 
1. in 输入参数,作为存储过程中的sql的查询条件使用 
2. out输出参数,作为存储过程查询结果输出 
3. in out输入输出参数,当一个变量既要作为条件输入,也要作为结果输出的时候,可以用此类型参数 
使用语法

create or replace procedure 存储过程名(param1 in type,param2 out type)
is/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;
--param 表示参数名,in表示参数类型为输入,type表示参数类型
--param in type
--创建或修改存储过程,存储过程名为findclass,输入参数为classId,输出className
create or replace procedure findclass(classId in int,className out varchar2)
as 
--存储过程开始
begin 
--把查询出来的class_name 赋值给输出变量className,查询条件为classId
select class_name into className from class where id = classId;
--数据库输出数量,这句输出只是方便测试,真正输出的值是out的值
DBMS_OUTPUT.put_line('班级名:'||className);
--存储过程结束
end findclass;

如果查询中有多个变需要into赋值,只需要写一个into就可以了

select student_name,class_name into studentName,className from class;

如果一个存储过程执行两条SQL语句只需要中间用分号隔开即可。

create or replace procedure findclass
is/as 
begin 
      select count(*) into totalClass from class;
      delete from vhcl where vhcl_no='10010';
exception
    When others then
       Rollback;
end;

猜你喜欢

转载自blog.csdn.net/qq_36135335/article/details/82184500