初探Oracle当中的存储过程

一、网络上关于Oracle存储过程的一般教程:

存储过程(Procedure)
create [or replace] procedure pro_name
[(parameter1 [mode] datatype,parameter2 [mode] datatype, ...)]
is/as
.....//声明部分
begin
....//函数主题
exception
....//异常处理
end;

从上面的代码段可以看见,存储过程是支持参数传递的,而且参数还不止一个 ,下面是几种参数类型的解释。

1、in 传入(形参)默认,可以有默认值(就行编程中的函数参数一样,in代表的是进行输入的参数);

2、out(实参)先将初始值传入经过处理后在传出,必须定义名称(out参数就像编程函数中的输出,也可以理解为return的数据);

3、in out 类型参数(既可以作为参数输入,也可以作为参数输出),可以直接赋予默认值;

二、自己学着编写的存储过程:

create or replace procedure procedure1 (id in integer,age out Date)
as
begin
select Sage into age from Student where Sid = id;
DBMS_OUTPUT.put_line('年龄:'|| age);
end procedure1;
这是我编写的一个包含输入、输出参数的简单的存储过程。这个简单的存储过程相信大家看一下基本概念就能使用了,然后注意一下,在输出填充的时候需要用到into关键字。(

定义多参数输出时参数类型中的类型SIZE问题。问题属于入参类型错误:plsql中procedure的入参类型,如果是number或varchar2的话不需要定义长度。否则编译不能通过。

三、需要返回多个结果得存储过程

  下面,是自己写的一个示例,我们先看代码:

create or replace procedure test60(cnumber in integer)

   is

  cursor student_cursor is select distinct S.* from Student S,sc where S.sid = sc.sid and sc.score < 60 and sc.cid = cnumber;

  T_Student student_cursor%ROWTYPE;

//定义的是结果集中的每一行的数据类型,在后续的结果提取当中,这个会成提取出来的对象。

  begin

     open student_cursor;

  loop

    fetch student_cursor into T_Student;

    exit when student_cursor%notfound;

    dbms_output.put(T_Student.Sid);

    dbms_output.put(T_Student.Sname);

    dbms_output.put(T_Student.Sage);

    dbms_output.put_line(T_Student.Ssex);

  end loop;

  close student_cursor;

  end test60;

  首先,基本的语法大家是没有问题的了。主要的问题就是集中在Cursor的定义当中。游标定义还是有几种方法的,这里我就使用自己学习了的一种定义方式。

cursor student_cursor is select distinct S.* from Student S,sc where S.sid = sc.sid and sc.score < 60 and sc.cid = cnumber;

(需要注意的是,在你定义游标的时候,需要使用的是IS关键字)。在我的理解中,cursor就有些类似于Android数据库开发中的结果集。

  然后,需要理解的是,cursor返回的是一行一行的数据(因为我的数据库是这样设计的),所以,你还需要定义出每行返回的数据的类型,也就是给它一个名分。(具体过程数据库将会为你执行)。

T_Student student_cursor%ROWTYPE;定义行返回类型。

最后,就是需要打开游标,将其中的数据一个个输出出来。

  begin

     open student_cursor;

  loop

    fetch student_cursor into T_Student;

    exit when student_cursor%notfound;

    dbms_output.put(T_Student.Sid);

    dbms_output.put(T_Student.Sname);

    dbms_output.put(T_Student.Sage);

    dbms_output.put_line(T_Student.Ssex);

  end loop;

  close student_cursor;

  end test60;

其中比较重要的一点是,你需要为你的循环设定跳出事件。最后,将你的cursor关闭。(fetch的作用是循环从cursor当中取出结果,填充到定义的数据类型当中。我理解的是内部就是一个循环,通过的exit的判断,不断的提取出结果。(类似Java当中的rs.next,不断地取出结果。))

好了,今天的学习就到这里,以后遇到问题再来进行补充。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值