Cursors in SQL

 Cursors in SQL


A cursor is a database object that allows you to process individual rows in a result set. Cursors can be used to iterate over a large result set and perform operations on each row. Here's an example:

sql


DECLARE @name VARCHAR(50), @salary INT;

DECLARE employee_cursor CURSOR FOR

SELECT name, salary

FROM employees;

OPEN employee_cursor;

FETCH NEXT FROM employee_cursor INTO @name, @salary;

WHILE @@FETCH_STATUS = 0

BEGIN

    PRINT 'Name: ' + @name + ', Salary: ' + CONVERT(VARCHAR, @salary);

    FETCH NEXT FROM employee_cursor INTO @name, @salary;

END;

CLOSE employee_cursor;

DEALLOCATE employee_cursor;

In this example, we're declaring a cursor called "employee_cursor" that retrieves the name and salary for all employees. The cursor is then opened, and each row is fetched and printed out using a WHILE loop. Finally, the cursor is closed and deallocated.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...