DEV Community

Cover image for ๐Ÿ–ฅ๏ธ Using Cursors & Triggers in SQL: Step-by-Step Guide ๐Ÿš€
PRIAN S S 24CB042
PRIAN S S 24CB042

Posted on

๐Ÿ–ฅ๏ธ Using Cursors & Triggers in SQL: Step-by-Step Guide ๐Ÿš€

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;
Enter fullscreen mode Exit fullscreen mode

โœ… 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)