Simple Cursor Tutorial with Syntax example in SQL Server
Here i am provide for you a simple cursor with syntax
What are Cursors in SQL Server?
Cursor is a Database object which allows us to process each row and manipulate its data. A Cursor is always associated with a Select Query and it will process each row returned by the Select Query one by one.
Using Cursor we can verify each row data, modify it or perform calculations which are not possible when we get all records at once.
A simple example would be a case where you have records of Employees and you need to calculate Salary of each employee after deducting Taxes and Leaves.
What is the syntax for writing Cursors in SQL Server?
Below is the syntax for writing a Cursor.
The very first thing is to declare some variables based on the columns you are fetching in your Select Query.
Then you need to declare the Cursor by giving it a name and setting its type as READ_ONLY and along with the FOR keyword you need to write the Select Query which will return the records you need to process.
Once the Cursor is setup, we need to open it using the OPEN command and then the first record is fetched and saved into the variable.
Whenever a record is fetched the @@FETCH_STATUS has value 0 and as soon as all the records returned by the Select Query are fetched, its value changes to -1.
A Cursor is associated with a WHILE LOOP which executes until the @@FETCH_STATUS has value 0.
Inside the WHILE LOOP, the processing is done for the current record and then again the next record is fetched and this process continues until @@FETCH_STATUS is 0.
Finally the Cursor is closed and deallocated using CLOSE and DEALLOCATE commands respectively.
Here we create a table with table name:Customers
How to write and use Cursors in SQL Server Stored Procedure?
Following is an example of simple Cursor in SQL Server Stored Procedure which prints all the records of Customers table