Introduction
In this tutorial, I am going to explain MySQL Cursors with examples. This article covers the following topics.
- Introduction to the Cursors
- Working with MySQL Cursors
- MySQL Cursor Life Cycle
- MySQL Cursors Example
- Conclusion
What is Cursor in MySQL?
In MySQL, a cursor allows row-by-row processing of the result sets. A cursor is used for the result set and returned from a query. By using a cursor, you can iterate or step through the results of a query and perform certain operations on each row. The cursor allows you to iterate through the result set and then perform the additional processing only on the rows that require it.
A cursor contains the data in a loop. Cursors may be different from SQL commands that operate on all the rows returned by a query at one time. MySQL cursor has three types of properties.
1. Read Only
The data in the underlying table cannot be modified via a cursor.
2. Non_Scrollable
Only rows can be retrieved in the order specified by the SELECT statement. In the reverse order, users can not retrieve records. Additionally, in the result set, users cannot skip rows or jump to a particular row.
3. Asensitive
An insensitive cursor is used to point to the actual data, whereas a temporary copy of the data is used by an insensitive cursor used. An insensitive cursor performs faster than an insensitive cursor because it does not have to make a temporary copy of data.
Working with MySQL Cursors
There are some steps we have to follow while using MySQL Cursors. Let’s see.
- Declare a Cursor
- Open a Cursor
- Fetch the Cursor
- Close the Cursor
1. Declaration of a Cursor
To declare a cursor, you must use the DECLARE statement. With the help of the variables, we need conditions and handlers to declare a cursor before we can use it. First of all, we will give the cursor a name; this is how we will refer to it later in the procedure. We can have more than one cursor in a single procedure, so it's necessary to give it a name that will, in some way, tell us what it's doing. We then need to specify the select statement we want to associate with the cursor. The SQL statement can be any valid SQL statement, and it is possible to use a dynamic where clause using variables or parameters, as we have seen previously.
Syntax
DECLARE<cursor_name>CURSOR FOR<select_statement>;
2. Open a Cursor
For opening a cursor, we must use the open statement. If we want to fetch rows from it, then you must have to open the cursor.
Syntax
OPEN <cursor_name>;
3. Fetch the Cursor
When we have to retrieve the next row from the cursor and move the cursor to the next row, then you need to fetch the cursor. If any row exists, then the below statement fetches the next row, and the cursor pointer moves ahead to the next row.
Syntax
FETCH <cursor_name> INTO <variable_list>;


Gowtham RajamanickamPosted Apr 25, 2015, 6:39 AM
good