以下emp表是orcl資料庫執行個體內建的表。
執行預存程序前,必須先執行 SET serveroutput ON;
show error; 可以顯示具體的執行錯誤資訊。
1. 不帶參數
A. 建立語句:
create or replace PROCEDURE EMP_COUNTASV_TOTAL NUMBER(10);BEGIN SELECT COUNT(*) INTO V_TOTAL FROM emp; DBMS_OUTPUT.PUT_LINE('僱員總人數為:'||V_TOTAL);END;
B. 執行語句:
不帶參數時,EMP_COUNT() 可簡寫成EMP_COUNT
(1)
EXECUTE EMP_COUNT(); --或者: EXEC EMP_COUNT();
(2)
BEGIN EMP_COUNT();END;
(3)
DECLAREBEGIN EMP_COUNT();END;
C. 執行結果
運行指令碼(F5),結果如下:
anonymous block completed僱員總人數為:14
其他執行個體:
create or replace procedure proc_userAS icount number;begin select count(*) into icount from tb_user; dbms_output.put_line('icount'||icount);EXCEPTION when too_many_rows then dbms_output.put_line('傳回值多於1行'); when others then dbms_output.put_line('在proc_user過程中出錯'); DBMS_OUTPUT.PUT_LINE(SQLCODE||'---'||SQLERRM); end;
2. 帶參數
create or replace procedure runbyparmeters_1 ( isal in emp.sal%type, sjob in varchar) as icount number; begin select count(*) into icount from emp where sal>isal and job=sjob; DBMS_OUTPUT.PUT_LINE('合格記錄有 '|| icount || '條'); exception when too_many_rows then DBMS_OUTPUT.PUT_LINE('傳回值多於1行'); when others then DBMS_OUTPUT.PUT_LINE('在RUNBYPARMETERS過程中出錯。'); end;
EXECUTE runbyparmeters_1(1100,'CLERK')
或者
declare realsal emp.sal%type; realjob varchar(40); begin realsal:=1100; realjob:='CLERK'; runbyparmeters_1(realsal,realjob); -- runbyparmeters_1(sjob=>realjob,isal=>realsal); END;
輸出結果:
anonymous block completed合格記錄有 1條