触发器以防止从表中删除任何内容



此新租赁历史记录表的触发器,用于防止从表中删除。

CREATE OR REPLACE  TRIGGER RENTALHIS_DEL
BEFORE DELETE ON RENTALHISTORY
BEGIN
dbms_output.put_line( 'Records can not be deleted');
END;
DELETE FROM RENTALHISTORY WHERE RENTALID = 1;

-- It is deleting before it says it can not delete
1 rows deleted.
Records can not be deleted
dbms_output.put_line( 'Records can not be deleted');

上面只是打印文本,触发器成功完成,然后删除仍然发生。相反,您要做的是引发错误以防止程序完成。

使用标准过程raise_application_error停止程序并引发错误:

CREATE OR REPLACE  TRIGGER RENTALHIS_DEL
BEFORE DELETE ON RENTALHISTORY
BEGIN
    raise_application_error(-20001,'Records can not be deleted');
END;
/

您希望引发错误,而不是打印消息。 无论如何都会发生删除:

CREATE OR REPLACE  TRIGGER RENTALHIS_DEL
BEFORE DELETE ON RENTALHISTORY
BEGIN
  RAISE_APPLICATION_ERROR (-20000, 'Deletion not supported on this table');
END;

或者,您可以使用instead of触发器来防止发生删除:

CREATE OR REPLACE TRIGGER RENTALHIS_DEL
INSTEAD OF DELETE ON RENTALHISTORY
BEGIN
   dbms_output.put_line( 'Records cannot be deleted');
END;
之后您可以使用

commit after your delete statement and rollback 通过 Pragma 到达前一阶段。

     CREATE OR REPLACE  TRIGGER 
     RENTALHIS_DEL
    AFTER DELETE ON RENTALHISTORY
       DECLARE
       PRAGMA 
          AUTONOMOUS_TRANSACTION;
      BEGIN
      RAISE_APPLICATION_ERROR 
     (-20000, 'Deletion getting rolled 
     back');
           ROLLBACK;
             END;

相关内容

  • 没有找到相关文章

最新更新