Oracle

觸發器:僅當從現在到上週日之間未創建相關記錄時才引發錯誤

  • September 2, 2020

我有一個觸發器可以防止在某些條件下插入到 DELETES 表中:

CREATE OR REPLACE TRIGGER D202574_custom
BEFORE INSERT ON D202574
FOR EACH ROW
DECLARE 
   v_upd_row NUMBER;
BEGIN
   SELECT COUNT(1) INTO v_upd_row 
   FROM A202574
   WHERE objectid = :new.sde_deletes_row_id
   AND sde_state_id = :new.deleted_at;

   IF v_upd_row = 0 THEN
        raise_application_error(-20001, 'Deleting has been disabled via a custom trigger.');
   END IF;
END ;

我想增強觸發器,以便僅在從現在到上週日晚上 11:59之間未創建基表中的相關記錄時才引發錯誤。

  • 該關係將基於 OBJECTID 列。

這是基表的樣子:

CREATE TABLE A_TEST_BASE_TABLE
(
 OBJECTID          INTEGER NOT NULL,
 SHAPE             SDE.ST_GEOMETRY,
 CREATED_USER      NVARCHAR2(255),
 CREATED_DATE      TIMESTAMP(6),   --<<-- the relevant field
 LAST_EDITED_USER  NVARCHAR2(255),
 LAST_EDITED_DATE  TIMESTAMP(6)
)

這樣做需要什麼?

如果我理解正確,那麼看看這是否有幫助:

  • created_date從該表中選擇

  • 檢查它是否低於上週日的 23:59

    • 為什麼?因為我推測未來無法創建

如何及時找到那個時刻?一種選擇是使用NEXT_DAY返回“下一個”星期天的函式,但是 - 如果你7從中減去(天),你會得到你想要的*前一個星期天。*然後將 23:59 添加到截斷的日期值,就是這樣。

字成程式碼:

SQL> select to_char(sysdate, 'dd.mm.yyyy hh24:mi, day') right_now,
 2    trunc(next_day(sysdate, 'sunday') - 7) + 23/24 + 59/(24*60) previous_sunday_2359
 3  from dual;

RIGHT_NOW                                              PREVIOUS_SUNDAY_235
------------------------------------------------------ -------------------
29.08.2020 22:39, saturday                             23.08.2020 23:59:00

SQL>

放入觸發器:

CREATE OR REPLACE TRIGGER D202574_custom
BEFORE INSERT ON D202574
FOR EACH ROW
DECLARE 
   v_upd_row  NUMBER;
   v_cre_date date;
BEGIN
   SELECT COUNT(1) INTO v_upd_row 
   FROM A202574
   WHERE objectid = :new.sde_deletes_row_id
     AND sde_state_id = :new.deleted_at;
     
   SELECT MIN(a.created_date) INTO v_cre_date
   FROM a_test_base_table a
   WHERE a.objectid = :new.sde_deletes_row_id;
     
   IF v_upd_row = 0 AND
      v_cre_date < trunc(next_day(sysdate, 'sunday') - 7) + 23/24 + 59/(24*60)
   THEN
      raise_application_error(-20001, 'Deleting has been disabled via a custom trigger.');
   END IF;
END;

引用自:https://dba.stackexchange.com/questions/274620