1.基本結構
CREATE OR REPLACE PROCEDURE 存儲過程名字
(
參數1 IN NUMBER,
參數2 IN NUMBER
) IS
變量1 INTEGER :=0;
變量2 DATE;
BEGINnode
END 存儲過程名字
2.SELECT INTO STATEMENT
將select查詢的結果存入到變量中,能夠同時將多個列存儲多個變量中,必須有一條
記錄,不然拋出異常(若是沒有記錄拋出NO_DATA_FOUND)
例子:
BEGIN
SELECT col1,col2 into 變量1,變量2 FROM typestruct where xxx;
EXCEPTION
WHEN NO_DATA_FOUND THEN
xxxx;
END;
...
3.IF 判斷
IF V_TEST=1 THEN
BEGIN
do something
END;
END IF;
4.while 循環
WHILE V_TEST=1 LOOP
BEGIN
XXXX
END;
END LOOP;
5.變量賦值
V_TEST := 123;
6.用for in 使用cursor
...
IS
CURSOR cur IS SELECT * FROM xxx;
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單步調試
sql
關於oracle存儲過程的若干問題備忘
1.在oracle中,數據表別名不能加as,如:
select a.appname
from appinfo a;
--
正確
select a.appname
from appinfo
as a;
--
錯誤
也許,是怕和oracle中的存儲過程當中的關鍵字as衝突的問題吧
2.在存儲過程當中,select某一字段時,後面必須緊跟into,若是select整個記錄,利用遊標的話就另當別論了。
select af.keynode
into kn
from APPFOUNDATION af
where af.appid
=aid
and af.foundationid
=fid;
--
有into,正確編譯
select af.keynode
from APPFOUNDATION af
where af.appid
=aid
and af.foundationid
=fid;
--
沒有into,編譯報錯,提示:Compilation
![](http://static.javashuo.com/static/loading.gif)
Error: PLS
-
00428: an
INTO clause
is expected
in this
SELECT statement
3.在利用select...into...語法時,必須先確保數據庫中有該條記錄,不然會報出"no data found"異常。
能夠在該語法以前,先利用
select count(*) from 查看數據庫中是否存在該記錄,若是存在,再利用select...into...
4.在存儲過程當中,別名不能和字段名稱相同,不然雖然編譯能夠經過,但在運行階段會報錯
select keynode
into kn
from APPFOUNDATION
where appid
=aid
and foundationid
=fid;
--
正確運行
select af.keynode
into kn
from APPFOUNDATION af
where
af.appid
=
appid
and
af.foundationid
=
foundationid;
--
運行階段報錯,提示
![](http://static.javashuo.com/static/loading.gif)
ORA
-
01422:exact
fetch
returns more than requested
number
of rows
5.在存儲過程當中,關於出現null的問題
假設有一個表A,定義以下:
create
table A(
![](http://static.javashuo.com/static/loading.gif)
id
varchar2(
50)
primary
key
not
null,
![](http://static.javashuo.com/static/loading.gif)
vcount
number(
8)
not
null,
![](http://static.javashuo.com/static/loading.gif)
bid
varchar2(
50)
not
null
--
外鍵
![](http://static.javashuo.com/static/loading.gif)
);
若是在存儲過程當中,使用以下語句:
![](http://static.javashuo.com/static/loading.gif)
select sum(vcount) into fcount from A
where bid='xxxxxx';
若是A表中不存在bid="xxxxxx"的記錄,則fcount=null(即便fcount定義時設置了默認值,如:fcount number(8):=0依然無效,fcount仍是會變成null),這樣之後使用fcount時就可能有問題,因此在這裏最好先判斷一下:
if fcount
is
null then
![](http://static.javashuo.com/static/loading.gif)
fcount:=0;
![](http://static.javashuo.com/static/loading.gif)
end
if;
這樣就一切ok了。
6.Hibernate調用oracle存儲過程