在編寫PL/SQL中,有時需要程式中暫停幾秒鐘再繼續執行,查了一下,Oracle內建有這個功能dbms_lock.sleep(10);不過dbms_lock包需要使用者自己安裝,示範如下:
- C:\Documents and Settings\andyleng>sqlplus /nolog
-
- SQL*Plus: Release 11.2.0.1.0 Production on Thu Nov 10 10:04:56 2011
-
- Copyright (c) 1982, 2010, Oracle. All rights reserved.
-
- SQL> conn /as sysdba --以SYSDBA身份登陸
- Connected.
- SQL> @?/rdbms/admin/dbmslock.sql --安裝系統包
-
- Package created.
-
-
- Synonym created.
-
-
- Grant succeeded.
-
- SQL> grant execute on dbms_lock to public; --授權PUBLIC執行許可權
-
- Grant succeeded.
-
- SQL> create table test1(id number,name varchar2(40),time date); --建立test1暫存資料表
-
- Table created.
-
- SQL> select * from test1; --無資料
-
- no rows selected
-
-
- SQL> SET TIMING ON --開啟時間顯示
- SQL> begin --開始執行測試指令碼
- 2 insert into test1(id,name,time) values(1,'Andy',sysdate);
- 3 DBMS_LOCK.SLEEP(10); --讓程式暫時10秒鐘
- 4 insert into test1(id,name,time) values(2,'Shirley',sysdate);
- 5 commit;
- 6 end;
- 7 /
-
- PL/SQL procedure successfully completed.
-
- Elapsed: 00:00:10.04 --程式執行時間為10.04秒
-
-
- SQL> SELECT ID,NAME,TO_CHAR(TIME,'YYYY/MM/DD HH24:MI:SS') AS TIME FROM TEST1; --查詢執行結果
-
- ID NAME TIME
- ---------- ---------------------------------------- -------------------
- 1 Andy 2011/11/10 10:09:03 --第一條的插入時間是09:03
- 2 Shirley 2011/11/10 10:10:13 --第二條的插入時間是09:13,剛好比第一條晚了10秒鐘
-
-
- Elapsed: 00:00:00.00
-
-
- SQL> drop table test1;
-
- Table dropped.
自訂EXCEPTION 和GOTO的用法:
- -- Create the procedure to loop del users.
- CREATE OR REPLACE PROCEDURE QA2_ATGCORE_MF.delBigTab
- AS
- PRAGMA AUTONOMOUS_TRANSACTION;
- p_Count NUMBER := 1000;
- n_delete number:=0;
- start_time date:=sysdate;
- end_time date;
- var_usergroup number;
- e_nowait EXCEPTION;--自訂exception
- PRAGMA EXCEPTION_INIT(e_nowait,-00054);--初使化該exception到“ORA-00054”的錯誤碼
- BEGIN
- <<restart>>--程式標籤
- WHILE 1 = 1
- LOOP
- begin
- var_usergroup:=QA2_ATGCORE_MF.DEL_USERGROUP_SEQ.nextval;
- EXECUTE IMMEDIATE
- 'update QA2_ATGCORE_MF.DPS_USER_DEL_TEMP set usergroup_id=:usergroup,del_flag=''1'',del_time=sysdate where del_flag=''0'' and rownum <=:rn'
- USING var_usergroup,P_COUNT;
- IF (SQL%NOTFOUND)
- OR (TO_CHAR (SYSDATE, 'hh24mi') BETWEEN '0600' AND '1200')
- THEN
- EXIT;
- ELSE
- n_delete:=n_delete + SQL%ROWCOUNT;
- QA2_ATGCORE_MF.DEL_USERGROUP(var_usergroup);
- END IF;
- COMMIT;
- EXCEPTION
- WHEN e_nowait THEN
- DBMS_LOCK.SLEEP(2););--出現ORA-00054的錯誤時先等待2秒鐘
- DBMS_OUTPUT.PUT_LINE(TO_CHAR(SYSDATE,'YYYY/MM/DD HH24:MI:SS')||SQLCODE||':'||SQLERRM||' I am go to restart' );
- GOTO restart;--出現ORA-00054的錯誤時跳轉到restart處重新執行該程式
- WHEN OTHERS THEN
- ROLLBACK;
- RAISE;
- END;
-
- END LOOP;
- COMMIT;
- end_time:=sysdate;
- DBMS_OUTPUT.PUT_LINE('***************************************************************************');
- DBMS_OUTPUT.PUT_LINE('Totally delete '||to_char(n_delete)||' users! Used time:'||numtodsinterval (end_time-start_time,'DAY'));
- DBMS_OUTPUT.PUT_LINE('***************************************************************************');
- END;
- /