Using CURSOR to Process Employee Salaries
📖 Scenario: You work in the HR department of a company. You have a table of employees with their salaries. You want to give a 10% bonus to employees who earn less than 5000. To do this, you will use a CURSOR to go through each employee and update their salary if needed.
🎯 Goal: Create a SQL script that uses a CURSOR to iterate over employees, check their salary, and update it by adding a 10% bonus if the salary is less than 5000.
📋 What You'll Learn
Create a table called
Employees with columns EmployeeID (integer), Name (varchar), and Salary (decimal).Insert exactly three employees with these details: (1, 'Alice', 4500), (2, 'Bob', 5200), (3, 'Charlie', 4800).
Declare a
CURSOR to select EmployeeID and Salary from Employees.Use the
CURSOR to loop through each employee, and if their salary is less than 5000, update their salary by adding 10%.Close and deallocate the
CURSOR after processing.💡 Why This Matters
🌍 Real World
Cursors are useful when you need to process rows one at a time, for example, applying complex logic or calling external procedures for each row.
💼 Career
Understanding cursors helps in database administration and writing procedural SQL scripts for business logic that cannot be done easily with simple queries.
Progress0 / 4 steps