语句触发器PL / SQL

时间:2018-03-11 11:59:08

标签: oracle plsql triggers

我需要创建一个语句触发器,只允许在办公时间内在PurchaseStock表中更新数据。 PurchaseStock表格是: PurchaseStock(StockID,ProductID,QuantityIn,Date) 请注意,productId是一个外键。

我知道如何为更新创建触发器,但我如何迎合时间? 任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

在这里,我居住的地方,非工作时间也是周六和周六。星期天(即周末),所以 - 我建议这样的事情:

SQL> create table purchase_stock (stock_id number, quantity number);

Table created.

SQL> create or replace trigger trg_biu_pursto
  2    before insert or update on purchase_stock
  3  declare
  4    -- day number (1 = Monday, 2 = Tuesday, ..., 7 = Sunday)
  5    l_day  number := to_number(to_char(sysdate, 'd'));
  6    -- current hour (e.g. now is 13:45 -> l_hour = 13)
  7    l_hour number := to_number(to_char(sysdate, 'hh24'));
  8  begin
  9    if l_day in (6, 7) or
 10       l_hour not between 9 and 17
 11    then
 12       raise_application_error(-20000, 'Non-working time; table not available');
 13    end if;
 14  end;
 15  /

Trigger created.

SQL> insert into purchase_stock values (1, 2);
insert into purchase_stock values (1, 2)
            *
ERROR at line 1:
ORA-20000: Non-working time; table not available
ORA-06512: at "SCOTT.TRG_BIU_PURSTO", line 10
ORA-04088: error during execution of trigger 'SCOTT.TRG_BIU_PURSTO'


SQL>

答案 1 :(得分:0)

假设您的办公时间在08:00到17:00之间,您可以在下面创建这样的触发器,以防止在办公时间之外更新数据,您可以使用raise_application_error声明:

CREATE OR REPLACE TRIGGER trg_upd_PrcStock
BEFORE UPDATE ON PurchaseStock 
FOR EACH ROW

DECLARE
   v_hour pls_integer;    
BEGIN
  select into v_hour extract(hour from cast(sysdate as timestamp)) from dual;

  IF v_hour between 8 and 16 THEN 
   -- trigger code    
  ELSE
   raise_application_error('-20333','You can not perform update out of office hours!');
  END IF;
END;