How to use cursor in SQL?
2199
03-Oct-2016
Updated on 20-Sep-2020
Abhishek Srivasatava
03-Oct-2016Cursor in SQL
Cursor can be defined as the table’s object which is used to retrieve the data from the result set one row at a time. We use it when there is a need to update records in a table row by row.
Declare cursor:
It is declared by defining the SQL statement that returns a result set.
Open:
It is opened and populated by executing the SQL statement defined by the cursor.
Fetch:
When it is opened, rows can be fetched from the cursor one by one or in a block to do data manipulation.
Example :
Close:
It is used to close by releasing the current result set and freeing any cursor locks held on the rows on which the cursor is positioned
De-allocate:
It is used to removes a cursor reference and released all recourses.
How to use Cursor in SQL for mass update?
Let’s take an example to update the salary for all ACTIVE employee of a company by 1000Rs.
Step 1: Creating a table:
Step 2 : inserting the record:
Step 3 :Here, I am explaining about the cursor program with help of small example:
We are using cursor to update the record row by row which is very useful when we
connect SQL to console, form application or web application.