Professional Documents
Culture Documents
Triggers and Active Data Bases in DBMS
Triggers and Active Data Bases in DBMS
Triggers and active databases are closely related concepts in the domain of DBMS. Let's
delve into what each of them means and how they are interconnected.
Triggers
A trigger is a predefined action that the database automatically executes in response to
certain events on a particular table or view. Triggers are typically used to maintain the
integrity of the data, automate data-related tasks, and extend the database functionalities.
There are various types of triggers based on when they are executed:
BEFORE: Trigger is executed before the triggering event.
AFTER: Trigger is executed after the triggering event.
INSTEAD OF: Trigger is used to override the triggering event, primarily for views.
Here's the basic syntax for creating a trigger in SQL, using MySQL as an
Syntax
Example of a Trigger
Suppose we have an `Employees` table and we want to maintain an `AuditLog` table that
keeps a record of salary changes for employees.
Employees Table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(255),
Salary DECIMAL(10, 2)
);
AuditLog Table
CREATE TABLE AuditLog (
LogID INT AUTO_INCREMENT PRIMARY KEY,
EmployeeID INT,
OldSalary DECIMAL(10, 2),
NewSalary DECIMAL(10, 2),
ChangeDate DATETIME
);
Now, let's create a trigger that automatically inserts a record into the `AuditLog` table
whenever there's an update to the `Salary` column in the `Employees` table.
Trigger
mysql> DELIMITER //
mysql> CREATE TRIGGER AfterSalaryUpdate
AFTER UPDATE ON Employees
FOR EACH ROW
BEGIN
IF OLD.Salary != NEW.Salary THEN
INSERT INTO AuditLog (EmployeeID, OldSalary, NewSalary,
ChangeDate)
VALUES (OLD.EmployeeID, OLD.Salary, NEW.Salary, NOW());
END IF;
END;
//
mysql> DELIMITER ;
Active Databases
An active database is a database that uses triggers and other event-driven functionalities.
The term "active" signifies that the DBMS reacts automatically to changes in data and
predefined events. Triggers are a primary mechanism that makes a database "active."