weβll learn how to use cursors and triggers in SQL. These are powerful tools for:
πΉ Processing data row by row
πΉ Automating actions on database events
1οΈβ£ Cursor: Employees with Salary > 50,000 π°
STEP 1:Create Employee Table & Insert Data
`CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
EmployeeName VARCHAR(50),
Salary DECIMAL(10,2)
);
INSERT INTO Employee VALUES (1, 'Alice', 60000);
INSERT INTO Employee VALUES (2, 'Bob', 45000);
INSERT INTO Employee VALUES (3, 'Charlie', 75000);`

Step 2: Declare & Process the Cursor
`DECLARE @EmpName VARCHAR(50);
DECLARE employee_cursor CURSOR FOR
SELECT EmployeeName
FROM Employee
WHERE Salary > 50000;
OPEN employee_cursor;
FETCH NEXT FROM employee_cursor INTO @EmpName;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @EmpName; -- Display employee name
FETCH NEXT FROM employee_cursor INTO @EmpName;
END
CLOSE employee_cursor;
DEALLOCATE employee_cursor;`

2οΈβ£ Trigger: AFTER INSERT on Students Table π
A cursor allows you to iterate over query results one row at a time.
Step 1: Create Employee Table & Insert Data
`CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
EmployeeName VARCHAR(50),
Salary DECIMAL(10,2)
);
INSERT INTO Employee VALUES (1, 'Alice', 60000);
INSERT INTO Employee VALUES (2, 'Bob', 45000);
INSERT INTO Employee VALUES (3, 'Charlie', 75000);
`

Step 2: Create AFTER INSERT Trigger
CREATE TRIGGER trg_AfterStudentInsert
ON Students
AFTER INSERT
AS
BEGIN
INSERT INTO Student_Audit(StudentID, Action, ActionTime)
SELECT StudentID, 'Registered', GETDATE()
FROM inserted;
END;
Step 3: Insert Sample Data & Test Trigger
INSERT INTO Students VALUES (1, 'David', 'Computer Science');
INSERT INTO Students VALUES (2, 'Emma', 'Mathematics');
SELECT * FROM Student_Audit;
β Conclusion
Cursors π Process query results row by row
Triggers π Automatically perform actions on data events
π‘ Real-world Use:
Use cursors for complex row-level operations
Use triggers for audit logging, notifications, and data integrity
THANKY YOU @santhoshnc sir for guiduing us and encouraging us by giving this as assignment !!!!

Top comments (0)