oracle 儲存過程的基本語法 及注意事項

2021-04-23 08:43:01 字數 2159 閱讀 7252

oracle 儲存過程的基本語法 及注意事項

oracle 儲存過程的基本語法

1.基本結構

create or replace procedure 儲存過程名字

(引數1 in number,

引數2 in number

) is

變數1 integer :=0;

變數2 date;

begin

end 儲存過程名字

2.select into statement

將select查詢的結果存入到變數中,可以同時將多個列儲存多個變數中,必須有一條

記錄,否則丟擲異常(如果沒有記錄丟擲no_data_found)

例子:

begin

select col1,col2 into 變數1,變數2 from typestruct where ***;

exception

when no_data_found then

***x;

end;

...3.if 判斷

if v_test=1 then

begin

do something

end;

end if;

4.while 迴圈

while v_test=1 loop

begin

***x

end;

end loop;

5.變數賦值

v_test := 123;

6.用for in 使用cursor

...is

cursor cur is select * from ***;

begin

for cur_result in cur loop

begin

v_sum :=cur_result.列名1+cur_result.列名2

end;

end loop;

end;

7.帶引數的cursor

cursor c_user(c_id number) is select name from user where typeid=c_id;

open c_user(變數值);

loop

fetch c_user into v_name;

exit fetch c_user%notfound;

do something

end loop;

close c_user;

8.用pl/sql developer debug

連線資料庫後建立乙個test window

在視窗輸入呼叫sp的**,f9開始debug,ctrl+n單步除錯

關於oracle儲存過程的若干問題備忘

1.在oracle中,資料表別名不能加as,如:

2.在儲存過程中,select某一字段時,後面必須緊跟into,如果select整個記錄,利用游標的話就另當別論了。

3.在利用select...into...語法時,必須先確保資料庫中有該條記錄,否則會報出"no data found"異常。

可以在該語法之前,先利用select count(*) from 檢視資料庫中是否存在該記錄,如果存在,再利用select...into...

4.在儲存過程中,別名不能和欄位名稱相同,否則雖然編譯可以通過,但在執行階段會報錯

假設有乙個表a,定義如下:

create table a(

id varchar2(50) primary key not null,

vcount number(8) not null,

bid varchar2(50) not null -- 外來鍵

);如果在儲存過程中,使用如下語句:

select sum(vcount) into fcount from a where bid='******';如果a表中不存在bid="******"的記錄,則fcount=null(即使fcount定義時設定了預設值,如:fcount number(8):=0依然無效,fcount還是會變成null),這樣以後使用fcount時就可能有問題,所以在這裡最好先判斷一下:

if fcount is null then

fcount:=0;

end if;這樣就一切ok了。

6.hibernate呼叫oracle儲存過程

oracle 儲存過程基本語法

1.基本結構 create or replace procedure 儲存過程名字 引數1 in number,引數2 in number is 變數1 integer 0 變數2 date begin end 儲存過程名字 2.select into statement 將select查詢的結果存...

oracle儲存過程基本語法

1.基本結構 create or replace procedure 儲存過程名字 引數1 in number,引數2 in number is 變數1 integer 0 變數2 date begin end 儲存過程名字 2.select into statement 將select查詢的結果存...

oracle儲存過程基本語法

oracle儲存過程基本語法 2 is 3 begin 4 null 5 end 行1 create or replace procedure 是乙個sql語句通知oracle資料庫去建立乙個叫做skeleton儲存過程,如果存在就覆蓋它 行2 行3 行4 null pl sql語句表明什麼事都不做...