2014-01-28 55 views
1

我怎樣才能正確地寫一個觸發此任務:觸發禁用插入表中特定日期在Oracle

create or replace trigger M_t2 
after insert on emp 

begin 

if (to_char(sysdate,'DY') = 'TUE') then 
    dbms_output.put_line('cannot insert into emp on tuesday'); 
end if; 

end; 
/

,因爲我仍然能夠插入這樣這不起作用:

insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values('7935','BOLT','ANALYST',7698,sysdate,900,100,10); 
+0

觸發:'TO_CHAR(SYSDATE, 'DY')='TUE''如果插入是從我的電腦啓動的,將不會有任何影響。 –

回答

4

dbms_output不會阻止您做任何事情,如果您的客戶端未設置爲顯示輸出,您甚至不會看到該消息。

爲了防止你需要拋出異常的動作:

if (to_char(sysdate,'DY') = 'TUE') then 
    raise_application_error(-20001, 'cannot insert into emp on tuesday'); 
end if; 

DY值是NLS-依賴所以這可能因與不同的語言會話被規避,所以你應該採取考慮到使用optional third parameter to to_char()。它也可能是之前,INSERT觸發器太:

create or replace trigger M_t2 
before insert on emp 
begin 
    if (to_char(sysdate, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH') = 'TUE') then 
    raise_application_error(-20001, 'cannot insert into emp on tuesday'); 
    end if; 
end; 
/

insert into emp ... 

ERROR at line 1: 
ORA-20001: cannot insert into emp on tuesday 
ORA-06512: at "<schema>.N_T2", line 3 
ORA-04088: error during execution of trigger '<schema>.M_T2'