Lab Manual 09
Lab Manual 09
Lab Manual 09
Session: Fall-2024
Instructor: SHEZA SHABIR
Understand what triggers are and why they are used in SQL.
Learn how to create, modify, and delete triggers.
Explore practical applications of triggers through examples.
What is a Trigger?
A trigger is a special type of stored procedure in a database that automatically executes when a
specified event occurs in the database. It is used to enforce business rules, maintain audit trails,
and automate repetitive tasks.
Types of Triggers:
1. DDL Triggers: A DDL trigger executes when schema-level events occur, such as CREATE,
ALTER, or DROP.
Example:
Scenario: Prevent any table from being dropped in the database.
-- Create the DDL trigger
CREATE TRIGGER PreventTableDrop
ON DATABASE
FOR DROP_TABLE
AS
BEGIN
PRINT 'Dropping tables is not allowed.';
ROLLBACK;
END;
How to check?
DROP TABLE Employees; -- Error: Dropping tables is not allowed
2. DML Triggers: A DML trigger executes when a INSERT, UPDATE, or DELETE operation
occurs on a table.
Example:
Scenario: When an employee's salary is updated, print a message indicating the salary
change.
-- Step 1: Create the Employees table
How to check?
--Step 01: Insert a record
INSERT INTO Employees (EmpID, Name, Salary)
VALUES (1, 'Alice', 50000);
--Step 02: Update the salary (this triggers the message)
UPDATE Employees
SET Salary = 55000
WHERE EmpID = 1;
How to check?
-- Test with an invalid salary
INSERT INTO Employees (EmpID, Name, Salary)
VALUES (1, 'Bob', 4000); -- This will fail
-- Test with a valid salary
INSERT INTO Employees (EmpID, Name, Salary)
VALUES (2, 'Alice', 6000); -- This will succeed
Lab Task
1. Create a DML Trigger to log a message when a student’s age is updated.
2. Create an INSTEAD OF Trigger to prevent courses with less than 1 credit from being
inserted.
3. Create a DDL Trigger to prevent any table from being dropped in the StudentsDB database.
4. Create a DML Trigger to prevent deleting students younger than 18.
5. Create a DML Trigger to log a message when a new student enrolls in a course.
6. Create a Trigger to count how many students are currently enrolled whenever a new
enrollment is added.
7. Create a Trigger to calculate the total credits of all courses whenever a new course is added.
8. Create a Trigger to calculate the average age of students whenever a student's age is
updated.
9. Create a Trigger to calculate how many students are enrolled in each course whenever a
new enrollment is added. Use JOIN to group results.
10. Create a Trigger to calculate the total number of students enrolled in all courses whenever
an enrollment is deleted.