ORACLE 儲存過程語法歸納
1、建立儲存過程
create or replace procedure test(var_name_1 in type,var_name_2 out type) as --宣告變數(變數名變數型別)
begin
--儲存過程的執行體
打印出輸入的時間資訊
E.g:
create or replace procedure test(workDate in Date) is
begin
dbms_output.putline(The input date is:||to_date(workDate, yyyy-mm-dd));
endtest;
2、變數賦值
變數名:=值;
E.g:
create or replace procedure test(workDate in Date) is x number(4,2);
begin
x:=1;
end test;
3、判斷語句:
if 比較式 then begin end;end if;
E.g
create or replace procedure test(x in number) is
begin
if x >0 then
begin x := 0 - x;
end;
end if;
if x = 0 then
begin
x: = 1;
end;
end if ;
end test;
4、For 迴圈
--執行語句
end LOOP;
(1)迴圈遍歷遊標
create or replace procedure test() as
Cursor cursor is select name from student;
begin
for name in cursor LOOP
begin
dbms_output.putline(name);
end;
end LOOP;
end test;
(2)迴圈遍歷陣列
create or replace procedure test(varArray in myPackage.TestArray) as
--(輸入引數 varArray 是自定義的陣列型別,定義方式見標題 6)
i number;
begin
i := 1;
-- 儲存過程陣列是起始位置是從 1 開始的,與 java、C、C++等語言不同。因為在Oracle中本是沒有陣列的概念的,陣列其實就是一張
-- 表(Table),每個陣列元素就是表中的一個記錄,所以遍歷陣列時就相當於從表中的第一條記錄開始遍歷
for i in 1..varArray.count LOOP
dbms_output.putline(The No.|| i ||record in varArray is: ||varArray (i));
end LOOP;
5、While 迴圈
while 條件語句 LOOP
begin
end;
end LOOP;
E.g
create or replace procedure test(i in number) as
begin
while i < 10 LOOP
begin
i=i+i;
end ;
end LOOP;
end test;
6 陣列
首先明確一個概念:Oracle 中本是沒有陣列的概念的,陣列其實就是一張表(Table),每個陣列元素就是表中的一個記錄。使用陣列時,使用者可以使用Oracle已經定義好的陣列型別,或可根據自己的需要定義陣列型別。
(1)oracle 自帶陣列型別
X:array -- 使用oracle自帶型別初始化
EG :
create or replace procedure test(y out array) is
X:array ;
begin
x :=new Array();
y :=x ;
end test ;
(2)自定義型別(自定義資料型別時,建議通過建立Package的方式實現,以便於管理)
E.g(自定義使用參見標題4.2)
create or replace package myPackage is
type info is recode(name in varchar(20), y in number) ; -- public type declarations
type tetsArray is table of info index by binary_integer ; --此處聲明瞭一個testArray的資料型別,其實其位是一張儲存info資料型別的table而已,以及testArray就是一張表字分別
--是name和y,並且使用了Index by binary_integer 作為索引,可以不寫(type testArray is table of info),但是如果不
--寫的話使用陣列時就要進行初始化
-- varArray myPackage.testArray ;
-- varArray := new myPackage.testArray();
end testArray ;
7 遊標的使用
Oracle中Cursor是非常有用的,用於遍歷臨時表中的查詢結果。其相關方法和屬性也很多,現僅就常用的用法做一二介紹:
(1)Cursor 型別的遊標(不能用於引數傳遞)
create or replace procedure test() is
--使用方式一
cursor_1 Cursor is select std_name from student_table where ...
-- 使用方式二
cursor_2 Cursor
begin
select std_name into cursor_2 from student_table where ...
可使用For x in cursor LOOP ....end LOOP; 來實現對Cursor的遍歷
end;
(2)SYS_REFCURSOR型遊標,該遊標是Oracle以預先定義的遊標,可作出引數進行傳遞
create or replace procedure test (rscursor out SYS_REFCURSOR) as
cursor SYS_REFCURSOR , name varchar(20);
begin
open cursor for select name for table where ....
-- SYS_REFCURSOR 只能通過 open for的方式來開啟和賦值
LOOP
fetch cursor into name exit when cursor%NOTFOUND -- SYS_REFCURSOR 只能通過fetch into 來開啟和遍歷 ,SYS_REFCURSOR中可使用三個狀態屬性:
---%NOTFOUND(未找到記錄資訊) %FOUND(找到記錄資訊) ---%ROWCOUNT(然後當前遊標所指向的行位置)
dbm_output.putline(name);
end LOOP;
rscursor:=cursor;
end test;
下次寫列子: