尝试根据日期和时间创建触发器

时间:2017-05-21 10:17:46

标签: oracle plsql triggers

我正在尝试创建一个触发器,以防止在办公时间以外(即8-18小时或周日除外)进行插入,更新和删除。

这是我的代码:

CREATE OR REPLACE TRIGGER HOLIDAY
BEFORE DELETE OR INSERT OR UPDATE ON DEPT FOR EACH ROW
BEGIN
IF ((EXTRACT(DAY FROM SYSDATE)='SUNDAY') OR (EXTRACT(HOUR FROM LOCALTIMESTAMP) NOT BETWEEN 8 AND 18)) THEN
   RAISE_APPLICATION_ERROR(-20001,'ILLEGAL OPERATION - OUT OF OFFICE HOURS OR HOLIDAY!');
 END IF ;
END; 
/

触发器已创建。 今天是星期天,当我尝试插入一行时,应用程序错误没有提高,相反,我得到的是:

SQL> @/home/divya/A43.SQL

Trigger created.

SQL> DELETE FROM DEPT WHERE D_NO = 'D3' ;
DELETE FROM DEPT WHERE D_NO = 'D3'
            *
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at "DIVYA12345.HOLIDAY", line 2
ORA-04088: error during execution of trigger 'DIVYA12345.HOLIDAY'

有人可以告诉我究竟是什么错误?显示错误显示 - 输出没有错误。任何帮助都非常感谢。提前致谢。

1 个答案:

答案 0 :(得分:1)

您收到错误,因为EXTRACT(DAY FROM SYSDATE)会返回月份中的日期编号,而不是其名称。要检索名称,您可以使用TO_CHAR(SYSDATE, 'DAY')代替,或to_char(sysdate,'fmDY', 'nls_date_language = ENGLISH'),如评论中所示:

CREATE OR REPLACE TRIGGER HOLIDAY
BEFORE DELETE OR INSERT OR UPDATE ON DEPT FOR EACH ROW
BEGIN
IF (TO_CHAR(sysdate,'fmDY', 'nls_date_language = ENGLISH')='SUNDAY') OR (EXTRACT(HOUR FROM LOCALTIMESTAMP) NOT BETWEEN 8 AND 18)) THEN
   RAISE_APPLICATION_ERROR(-20001,'ILLEGAL OPERATION - OUT OF OFFICE HOURS OR HOLIDAY!');
END IF ;
END; 
/