Lesson 1
Creating a Trigger in Oracle PL/SQL
This module covers a tool that designers sometimes overlook when creating a database system: the database trigger. The database trigger can add functionality to the database that might otherwise need to be handled by specialized coding.
By the end of this module, you will know how to:
- Distinguish between a trigger and a procedure
- Describe the syntax and use of special record variables
- Create an insert, update, or delete trigger
- Build and execute a trigger that covers insert, update, and delete
You will get lots of practice coding PL/SQL in this module.
Oracle Database Triggers can be used to notify users of anomalies in the system
Oracle database triggers can be effectively used to notify users of anomalies in the system by automating the detection of abnormal conditions and executing predefined actions to alert stakeholders. Here's a step-by-step explanation of how this can be implemented:
- Identify the Anomalies
- Define the conditions that constitute an anomaly in your database. Examples include:
- Unauthorized updates to sensitive data.
- Exceeding a predefined threshold (e.g., unusually high transaction amounts).
- Insertion of invalid or suspicious data.
- Choose the Trigger Event
- Decide which database event should activate the trigger. This can be:
- INSERT: Triggered when a new record is added.
- UPDATE: Triggered when an existing record is modified.
- DELETE: Triggered when a record is removed.
- Optionally, you can use BEFORE or AFTER timing:
- BEFORE: To validate or modify data before the operation.
- AFTER: To audit or notify after the operation is complete.
- Write the Trigger Code
- The trigger's body should include logic to detect anomalies and initiate notifications. A typical approach involves:
- Using PL/SQL to check for abnormal conditions.
- Logging anomalies to a table for further analysis.
- Sending notifications via email or other communication channels.
- Use UTL_MAIL or UTL_SMTP for Notifications
- Oracle's
UTL_MAIL
or UTL_SMTP
packages can send email alerts. Here's a basic example:
CREATE OR REPLACE TRIGGER notify_anomaly
AFTER INSERT OR UPDATE ON transactions
FOR EACH ROW
BEGIN
IF :NEW.transaction_amount > 100000 THEN
-- Log anomaly
INSERT INTO anomaly_log (transaction_id, message, logged_at)
VALUES (:NEW.transaction_id, 'Transaction exceeds threshold', SYSDATE);
-- Send email notification
UTL_MAIL.SEND(
sender => 'alerts@yourcompany.com',
recipients => 'admin@yourcompany.com',
subject => 'Anomaly Detected',
message => 'Transaction ' || :NEW.transaction_id ||
' exceeds the threshold amount.'
);
END IF;
END;
/
- Leverage DBMS_ALERT or DBMS_PIPE for Real-Time Notifications
- If real-time notifications are required for connected users:
- Use the
DBMS_ALERT
package to notify users of specific events.
- Use the
DBMS_PIPE
package to communicate between database sessions.
- Example:
CREATE OR REPLACE TRIGGER alert_anomaly
AFTER INSERT ON transactions
FOR EACH ROW
BEGIN
IF :NEW.transaction_amount > 100000 THEN
DBMS_ALERT.SIGNAL('HIGH_TRANSACTION', 'Anomaly detected: High transaction amount.');
END IF;
END;
/
- Clients or application layers can listen for these alerts and act upon them.
- Monitor and Maintain the Trigger
- Test the trigger thoroughly to ensure it works as intended without negatively impacting performance.
- Regularly review logs and notifications to verify the accuracy and effectiveness of the anomaly detection.
By using Oracle database triggers in combination with these tools, you can create a robust system to detect and notify users of anomalies in real time.
Trigger defines Database Action
A trigger defines an action the database should take when some database-related event occurs. Triggers may be used to supplement declarative referential integrity, to enforce complex business rules, or to audit changes to data.
The code within a trigger, called the trigger body, is made up of PL/SQL blocks. The execution of triggers is transparent to the user. Triggers are executed by the database when specific types of data manipulation commands are performed on specific tables.
Such commands may include inserts, updates, and deletes. Updates of specific columns may also be used as triggering events. Triggering events may also include DDL commands and database events such as shutdowns and logins.
Because of their flexibility, triggers may supplement referential integrity; they should not be used to replace it. When enforcing the business rules in an application, you should first rely on the declarative referential integrity available with Oracle; use triggers to enforce rules that cannot be coded through referential integrity.
- Triggers
A trigger is a named PL/SQL unit that is stored in the database and run in response to an event that occurs in the database.
You can specify the event, whether the trigger fires before or after the event, and whether the trigger runs for each event or for each row affected by the event. For example, you can create a trigger that runs every time an INSERT statement affects the EMPLOYEES table.
- SQL Query and Processing:
Running a SQL query and processing the result set is as easy in PL/SQL as opening a text file and processing each line in popular scripting languages. Using PL/SQL to access metadata about database objects and handle database error conditions,
you can write utility programs for database administration that are reliable and produce
readable output about the success of each operation. Many database features, such as triggers and object types, make use of PL/SQL. You can write the bodies of triggers and methods for object types in PL/SQL.
Higher Productivity
PL/SQL lets you write very compact code for manipulating data. In the same way that scripting languages such as Perl can read, transform, and write data from files, PL/SQL can query, transform, and update data in a database.
PL/SQL saves time on design and debugging by offering a full range of software-engineering features, such as exception handling, encapsulation, data hiding, and object-oriented datatypes. PL/SQL extends tools such as Oracle Forms. With PL/SQL in these tools, you can use familiar language constructs to build applications. For example, you can use an entire PL/SQL block in an Oracle Forms trigger, instead of multiple trigger steps, macros, or user exits. PL/SQL is the same in all environments. After you learn PL/SQL with one Oracle tool, you can transfer your knowledge to other tools.
The next lesson defines the trigger.