Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger to prevent Any Deleting from Table

a trigger for this new rental history table that prevents deletions from the table.

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
like image 911
Azmina Hashim Avatar asked Jan 31 '17 18:01

Azmina Hashim


People also ask

What is instead of delete trigger?

INSTEAD OF DELETE triggers are used to delete records from a View that is based on multiple tables. Description. An INSTEAD OF DELETE trigger gets executed in place of the DELETE event on a table or a View.

How do I create a trigger for delete?

To delete a DML triggerIn Object Explorer, connect to an instance of Database Engine and then expand that instance. Expand the database that you want, expand Tables, and then expand the table that contains the trigger that you want to delete. Expand Triggers, right-click the trigger to delete, and then click Delete.

What is a before delete trigger?

A BEFORE DELETE Trigger means that Oracle will fire this trigger before the DELETE operation is executed.

How does trigger help to ensure the constraints satisfied?

In a trigger, we first specify when the trigger is to be executed and then the action to be performed when the trigger executes. Triggers are used to specify certain integrity constraints and referential constraints that cannot be specified using the constraint mechanism of SQL.


2 Answers

dbms_output.put_line( 'Records can not be deleted');

The above just prints the text and trigger completes successfully and then delete happens anyway. What you wanna do instead is to raise an error to prevent the program from completing.

Use standard procedure raise_application_error to stop the program and raise error:

CREATE OR REPLACE  TRIGGER RENTALHIS_DEL
BEFORE DELETE ON RENTALHISTORY
BEGIN
    raise_application_error(-20001,'Records can not be deleted');
END;
/
like image 75
Gurwinder Singh Avatar answered Sep 29 '22 00:09

Gurwinder Singh


You want to raise an error, not print a message. The delete happens anyway:

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

Alternatively, you could use an instead of trigger to prevent the delete from taking place:

CREATE OR REPLACE TRIGGER RENTALHIS_DEL
INSTEAD OF DELETE ON RENTALHISTORY
BEGIN
   dbms_output.put_line( 'Records cannot be deleted');
END;
like image 45
Gordon Linoff Avatar answered Sep 28 '22 23:09

Gordon Linoff