Tracking Deleted Rows with a PL/SQL Trigger
PL/SQL Trigger: Exercise-3 with Solution
Write a code in PL/SQL to implement a trigger that maintains a transaction history log whenever a row is deleted from a table.
Sample Solution:
PL/SQL Code:
Let's see how the trigger functions:
PL/SQL Code:
Output:
1 row(s) inserted. 1 row(s) inserted. ORA-01400: cannot insert NULL into ("SQL_XWPLBLJQVQMCLONNGGTSSIRWZ"."EMPLOYEE_HISTORY"."LOG_ID") ORA-06512: at "SQL_XWPLBLJQVQMCLONNGGTSSIRWZ.MAINTAIN_HISTORY_LOG", line 8 ORA-06512: at "SYS.DBMS_SQL", line 1721 no data found
Flowchart:


Explanation:
The said code in PL/SQL that demonstrates how to use a PL/SQL trigger to maintain an audit trail by capturing deletion history for rows in a table.
Assume that the code executes with the table employees with columns employee_id, first_name, and last_name and another table employee_history that maintain the transaction history log. This table stores log_id, employee_id, deleted_date, and deleted_by columns to record the details of each deletion.
The trigger maintain_history_log is created using the BEFORE DELETE ON that fires before a row is deleted from the employees table.
The trigger inserts a record into the employee_history table, capturing the employee_id of the deleted row, the deletion timestamp using SYSTIMESTAMP, and the deleted_by user.
When deleting a record the trigger maintain_history_log is invoked before the deletion, logging the deletion in the employee_history table.
The contents of the employee_history table are queried using SELECT * FROM employee_history; to view the log entries.
Previous:Restricting column updates during specific hours using PL/SQL triggers.
Next: Enforcing referential integrity in PL/SQL trigger.
What is the difficulty level of this exercise?