1、預存程序的文法結構:
CREATE OR REPLACE PROCEDURE 過程名 AS
聲明語句段;
BEGIN
執行語句段;
EXCEPTION
異常處理語句段;
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;
建立預存程序執行個體
CREATE OR REPLACE PROCEDURE stu_proc as
--聲明語句段
v_name varchar2(20);
BEGIN
--執行語句段
SELECT o.sname INTO v_name FROM student o WHERE o.id=1;
DBMS_OUTPUT.put_line(v_name);
EXCEPTION
--異常處理語句段
WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.put_line('NO_DATA_FOUND');
END;
--調用預存程序
--CALL stu_proc();