Cursor in SQL Server
Cursor in SQL Server
A cursor in SQL Server is a database object used to retrieve data row by row from a result
set. Cursors are useful when you need to perform operations on each row individually
rather than operating on the entire set at once, which is typical of SQL operations.
Here’s how a cursor works, explained with an example and dummy data.
Step-by-Step Example
1. Create Dummy Data Let’s assume we have a table named Employees with the
following data:
CREATE TABLE Employees (
EmployeeID INT,
EmployeeName VARCHAR(100),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);
Employees Table
Employees Table
Cursor Syntax
Let’s create a cursor that loops through the Employees table and increases the
salary of employees in the HR department by 10%. Here’s how we define and use a
cursor in SQL Server: