1.创建存储
create or replace procedure test(var_name_1 in type,var_name_2 out type) as--声明变量(变量名 变量类型)begin--存储过程的执行体end test;打印出输入的时间信息E.g:create or replace procedure test(workDate in Date) isbegindbms_output.putline(The input date is:||to_date(workDate, yyyy-mm-dd));end test;
2.变量赋值
变量名 := 值;E.g:create or replace procedure test(workDate in Date) isx number(4,2);beginx := 1;end test;
3.判断语句
if 比较式 then begin end; end if;E.gcreate or replace procedure test(x in number) isbeginif x >0 thenx := 0 - x;elsif =0 thenx:=x;else x:=x+1;end if;if x = 0 thenbeginx: = 1;end;end if;end test;
4.FOR
For ... in ... LOOP-- 执行语句end LOOP;(1) 循环遍历游标create or replace procedure test() asCursor cursor is select name from student;name varchar(20);beginfor name in cursor LOOPbegindbms_output.putline(name);end;end LOOP;end test;2)循环遍历数组create or replace procedure test(varArray in myPackage.TestArray) as--(输入参数 varArray 是自定义的数组类型,定义方式见标题 6)i number;begini := 1; --存储过程数组是起始位置是从 1 开始的,与 java、C、C++等语言不同。因为在 Oracle 中本是没有数组的概念的,数组其实就是一张--表(Table),每个数组元素就是表中的一个记录,所以遍历数组时就相当于从表中的第一条记录开始遍历for i in 1..varArray.count LOOPdbms_output.putline(The No. || i ||record in varArray is: ||varArray(i));end LOOP;end test;
5.while循环
while 条件语句 LOOPbeginend;end LOOP;E.gcreate or replace procedure test(i in number) asbeginwhile i < 10 LOOPbegini:= i + 1;end;end LOOP;end test;
6.数组
首先明确一个概念:Oracle 中本是没有数组的概念的,数组其实就是一张表(Table),每个数组元素就是表中的一个记录。使用数组时,用户可以使用 Oracle 已经定义好的数组类型,或可根据自己的需要定义数组类型。(1)使用 Oracle 自带的数组类型x array; --使用时需要需要进行初始化e.g:create or replace procedure test(y out array) isx array;beginx := new array();y := x;end test;(2)自定义的数组类型 (自定义数据类型时,建议通过创建 Package 的方式实现 ,以便于管理)E.g (自定义使用参见标题 4.2) create or replace package myPackage is-- Public type declarations type info is record( name varchar(20), y number);type TestArray is table of info index by binary_integer; --此处声明了一个 TestArray 的类型数据,其实其为一张存储 Info 数据类型的 Table而已,及 TestArray 就是一张表,有两个字段,一个是name,一个是 y。需要注意的是此处使用了 Index by binary_integer 编制该 Table 的索引项,也可以不写,直接写成:type TestArray istable of info,如果不写的话使用数组时就需要进行初始化:varArray myPackage.TestArray; varArray := new myPackage.TestArray();end TestArray;
7.游标的使用
游标的使用 Oracle 中 Cursor 是非常有用的,用于遍历临时表中的查询结果 。其相关方法和属性也很多,现仅就常用的用法做一二介绍:(1)Cursor 型游标(不能用于参数传递)create or replace procedure test() iscusor_1 Cursor is select std_name from student where ...; --Cursor 的使用方式 1 cursor_2 Cursor;beginselect class_name into cursor_2 from class where ...; --Cursor 的使用方式 2可使用 For x in cursor LOOP .... end LOOP; 来实现对 Cursor 的遍历end test;(2)SYS_REFCURSOR 型游标,该游标是 Oracle 以预先定义的游标,可作出参数进行传递create or replace procedure test(rsCursor out SYS_REFCURSOR) iscursor SYS_REFCURSOR; name varhcar(20);beginOPEN cursor FOR select name from student where ... --SYS_REFCURSOR 只能通过 OPEN 方法来打开和赋值LOOPfetch cursor into name --SYS_REFCURSOR 只能通过 fetch into 来打开和遍历 exit when cursor%NOTFOUND; --SYS_REFCURSOR 中可使用三个状态属性:---%NOTFOUND(未找到记录信息) %FOUND(找到记录信息)---%ROWCOUNT(然后当前游标所指向的行位置)dbms_output.putline(name);end LOOP;rsCursor := cursor;end test;