Lab 4
Lab 4
NO : 4
Create a row level trigger for the customers table that would fire for INSERT or UPDATE or
DELETE operations performed on the CUSTOMERS table. This trigger will display the salary
difference between the old & new Salary.
CUSTOMERS(ID,NAME,AGE,ADDRESS,SALARY)
SOLUTION
--------------------------------------------------------------------------------------------------
Trigger : A trigger is a set of SQL statements that run every time a row is
inserted, updated, or deleted in a table.
Event: The trigger needs to respond to INSERT, UPDATE, and DELETE
operations.
Timing: The trigger should fire AFTER the event occurs, meaning it will execute
its actions after the row has been inserted, updated, or deleted.
Level: This will be a ROW level trigger, meaning it will fire once for each row
affected by the triggering statement.
Action: The action will be to calculate and display the difference between the
old and new salary values.
OLD: Represents the state of the row before the triggering event (available in
UPDATE and DELETE triggers).
NEW: Represents the state of the row after the triggering event (available in
INSERT and UPDATE triggers).
Trigger Body:
For INSERT operations, there will be no OLD value, so only the NEW value is
available.
For DELETE operations, there will be no NEW value, so only the OLD value is
available.
For UPDATE operations, both OLD and NEW values are available, and the
salary difference can be computed.
--------------------------------------------------------------------------------------------------
SOLUTION
create database db4;
use db4;
create table customer
(ID int primary key,
NAME varchar(20) not null,
AGE int not null,
ADDRESS varchar(20) not null,
SALARY decimal(10,2) not null);
--------------------------------------------------------------------------------------------------
DELIMITER ;
-------------------------------------------------
UPDATE TRIGGER
-------------------------------------------------
DELIMITER //
CREATE TRIGGER after_update_salary_difference
AFTER UPDATE ON CUSTOMER
FOR EACH ROW
BEGIN
DECLARE old_salary DECIMAL(10, 2);
DECLARE new_salary DECIMAL(10, 2);
DELIMITER;
-------------------------------------------------
DELETE TRIGGER
-------------------------------------------------
DELIMITER //
DELIMITER ;
-------------------------------------------------
TESTING OF EACH TRIGGER.
-------------------------------------------------
SELECT @my_sal_diff AS SAL_DIFF;
-------------------------------------------------
UPDATE CUSTOMER
SET SALARY = 55000.00
WHERE ID = 6;
-------------------------------------------------
SELECT @my_sal_diff AS SAL_DIFF;
-------------------------------------------------
DELETE FROM CUSTOMER
WHERE ID = 6;
-------------------------------------------------
SELECT @my_sal_diff AS SAL_DIFF;