Вы находитесь на странице: 1из 8

MySQL: Cursors

To handle a result set inside a stored procedure, you use a cursor. A cursor allows you to iterate a set of rows returned by
a query and process each row accordingly.

MySQL cursor is read-only, non-scrollable and asensitive.

Read only: you cannot update data in the underlying table through the cursor.

Non-scrollable: you can only fetch rows in the order determined by the SELECT statement. You cannot fetch
rows in the reversed order. In addition, you cannot skip rows or jump to a specific row in the result set.

Asensitive: there are two kinds of cursors: asensitive cursor and insensitive cursor. An asensitive cursor points
to the actual data, whereas an insensitive cursor uses a temporary copy of the data. An asensitive cursor
performs faster than an insensitive cursor because it does not have to make a temporary copy of data. However,
any change that made to the data from other connections will affect the data that is being used by an asensitive
cursor, therefore, it is safer if you don’t update the data that is being used by an asensitive cursor. MySQL cursor
is asensitive.

A database cursor is a control structure that enables traversal over the records in a database. Cursors are used by
database programmers to process individual rows returned by database system queries. Cursors enable manipulation of
whole result sets at once. In this scenario, a cursor enables the rows in a result set to be processed sequentially. In SQL
procedures, a cursor makes it possible to define a result set (a set of data rows) and perform complex logic on a row by
row basis. By using the same mechanics, an SQL procedure can also define a result set and return it directly to the caller
of the SQL procedure or to a client application.

MySQL supports cursors inside stored programs.

To use cursors in MySQL procedures, you need to do the following :


- Declare a cursor.
- Open a cursor.
- Fetch the data into variables.
- Close the cursor when done.

The procedure starts with three variable declarations. Incidentally, the order is important. First, declare variables. Then
declare conditions. Then declare cursors. Then, declare handlers. If you put them in the wrong order, you will get an
error message.

DELIMITER $$
CREATE PROCEDURE my_procedure_cursors(INOUT return_val INT)
BEGIN
DECLARE a,b INT;
DECLARE cur_1 CURSOR FOR
SELECT max_salary FROM jobs;
DECLARE CONTINUE HANDLER FOR NOT FOUNDSET b = 1;
OPEN cur_1;
REPEAT FETCH cur_1 INTO a;
UNTIL b = 1
END
REPEAT;
CLOSE cur_1;
SET return_val = a;
END;
$$

Now execute the procedure:

mysql>
CALL my_procedure_cursors(@R);
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @R;


+-------+
| @R |
+-------+
| 10500 |
+-------+

This MySQL tutorial explains how to declare a cursor in MySQL with syntax and examples.

Description

A cursor is a SELECT statement that is defined within the declaration section of your stored program in MySQL.

Syntax

The syntax to declare a cursor in MySQL is:

DECLARE cursor_name CURSOR FOR


select_statement;
Parameters or Arguments

cursor_name
The name to assign to the cursor.
select_statement
The SELECT statement associated with the cursor.
Example

Let's look at how to declare a cursor in MySQL.

For example:

DECLARE c1 CURSOR FOR


SELECT site_id
FROM sites
WHERE site_name = name_in;
The result set of this cursor is all site_id values where the site_name matches the name_in variable.

Below is a function that uses this cursor.

DELIMITER //

CREATE FUNCTION FindSiteID ( name_in VARCHAR(50) )


RETURNS INT

BEGIN

DECLARE done INT DEFAULT FALSE;


DECLARE siteID INT DEFAULT 0;

DECLARE c1 CURSOR FOR


SELECT site_id
FROM sites
WHERE site_name = name_in;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN c1;
FETCH c1 INTO siteID;

CLOSE c1;

RETURN siteID;

END; //

DELIMITER ;
You could then call your new function (that contains the cursor) as follows:

SELECT FindSiteID ('TechOnTheNet.com');

MySQL: OPEN Statement


This MySQL tutorial explains how to use the OPEN statement to open a cursor in MySQL with syntax and examples.

Description

Once you've declared your cursor in MySQL, the next step is to use the OPEN statement to open the cursor.

Syntax

The syntax to open a cursor using the OPEN statement in MySQL is:

OPEN cursor_name;

MySQL: FETCH Statement


This MySQL tutorial explains how to use the FETCH statement to fetch the next row for a cursor in MySQL with
syntax and examples.

Description

The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so that some type of operation can
be performed on the data. After declaring and opening your cursor, the next step is to use the FETCH statement to fetch
rows from your cursor.

Syntax

The syntax for the FETCH statement in MySQL is:

FETCH [ NEXT [ FROM ] ] cursor_name INTO variable_list;


Parameters or Arguments

cursor_name
The name of the cursor that you wish to fetch rows.
variable_list
The list of variables, comma separated, that you wish to store the cursor result set in.

MySQL: Set up a Handler for Cursor's NOT FOUND condition


This MySQL tutorial explains how to set up a handler for the NOT FOUND condition for a cursor in MySQL with
syntax and examples.

Description

If you try to fetch data from a cursor and there are no rows, MySQL will raise a NO DATA error. You can set up a
handler for the NOT FOUND condition so that your stored program does not terminate with an error.

Syntax
The syntax to set up a handler for the NOT FOUND condition for a cursor in MySQL is:

DECLARE CONTINUE HANDLER FOR NOT FOUND [ set_condition ];


Parameters or Arguments

set_condition
The condition to set when the NOT FOUND condition is encountered by the cursor.
Example

Let's look at how to set up a handler for the NOT FOUND condition for a cursor in MySQL.

First, we need to declare a variable that will be set when the NO DATA error occurs.

DECLARE done INT DEFAULT FALSE;


MySQL Cursors are used for rows repetition returned by a query on a row-by-row process. SQL commands will
function on all the rows at one time in the program. Cursors can be created inside the Triggers, Functions and Stored
Procedures.

MySQL Cursors contain 3-properties:


 Asensitive
 Read only
 One directional
Conceptual
figure

Description

MySQL Cursors can be classified into the following types:

 Asensitive cursors
 Insensitive cursors.
 Asensitive cursor focus on genuine data.
 Asensitive cursor work faster than the insensitive cursor.
 Asensitive cursor doesn’t need any duplicate copy of data.
 Any alteration done in the data through dead end should effect the data contain in asensitive cursors.
 An insensitive cursor uses duplicate copy data.
 Insensitive cursors work very slower.
 Insensitive cursors contain duplicate data.
Description

In read only data, there is only permission to read the data. And it does not contain any permissions to update the data or
alter the data.
Description

MySQL cursor moves only in one direction. Data fetching can be done in only one direction, and cannot fetch data in
opposite direction.
Description

Creating MySQL Cursors is done by creating cursor with all the specifications.
Syntax

Declare <cursor_name>cursor for<select statement>


open <cursor_name>;
fetch<cursor_name>into<variable1>,<variable2>;
close<cursor_name>;
cursor_name => The name assigned to a cursor.
variables => variables are the column values.
Examples

By viewing the below example, the concept of create cursors can be easily understood.

mysql> select * from student;


+--------+----------+-----------+
| stu_id | stu_name | stu_class |
+--------+----------+-----------+
| 1 | david | 10 |
| 2 | shah | 20 |
| 3 | mike | 30 |
| 4 | maze | 40 |
+--------+----------+-----------+
4 rows in set (0.00 sec)

mysql> delimiter $$
mysql> create procedure curdemo(id int)
-> begin
-> declare name varchar(255);
-> declare cur1 cursor for select stu_name from student where stu_id=id;
-> open cur1;
-> fetch cur1 into name;
-> select name;
-> close cur1;
-> end $$
Query OK, 0 rows affected (0.13 sec)

mysql> delimiter ;
mysql> call curdemo(2);
+------+
| name |
+------+
| shah |
+------+
1 row in set (0.39 sec)
In the above example, curdemo is a input parameter which accept input values. cur1 is the attribute used in the cursor.
open() is used to open the cursor, fetch is used to fetch the row values into names and close cursor will remove the open
cursor for same minutes. Then the call cursor will execute the curdemo and return the records(i.e, call cursor will call
the stu_id(2) and it will return the name(shah)).
Description

Close Cursor is used to close the Cursor upto some extent, when the open cursor is not required. The keyword close in
the cursor will discharge the present records to close and then open the open cursor.
Conceptual
figure

 Declare – Is a variable length value.


 Open – Opens a cursor variable that is associate with a query.
 Fetch – Retrieve a specific row and columns.
 Empty – Which contain an empty set.
 Close – Closing of a cursor.
Syntax

Declare <cursor_name>cursor for<select statement>


open <cursor_name>;
fetch<cursor_name>into<variable1>,<variable2>;
close<cursor_name>;
Cursor_name => The name assigned to a cursor.
variables => variables are the column values.
Examples

By viewing the below example, the concept of close cursors can be easily understood.

mysql> select * from student;


+--------+----------+-----------+
| stu_id | stu_name | stu_class |
+--------+----------+-----------+
| 1 | david | 10 |
| 2 | shah | 20 |
| 3 | mike | 30 |
| 4 | maze | 40 |
+--------+----------+-----------+
4 rows in set (0.00 sec)

mysql> delimiter $$
mysql> create procedure close_cursor(id int)
-> begin
-> declare name varchar(255);
-> declare cur1 cursor for select stu_name from student where stu_id=id;
open cur1;
-> fetch cur1 into name;
-> select name;
-> close cur1;
-> end $$
Query OK, 0 rows affected (0.02 sec)

mysql> delimiter ;
mysql> call close_cursor(4);
+------+
| name |
+------+
| maze |
+------+
1 row in set (0.39 sec)
In the above example, close_cursor is a input parameter which accept input values. cur1 is the attribute used in the
cursor. open() is used to open the cursor, fetch is used to fetch the record values from cursor, select name will return the
name of the record and close cursor is used to close the cur1. Then the call cursor will execute the cur1 and return the
records(i.e, call cursor will call the stu_id(4) and it will return the name(maze)).
Key Points

 MySQL Cursors are database objects used in the database application used to manipulate the data.
 Read only will only read the data.
 Asensitive cursor focuses to genuine information.
 Insensitive cursor utilizes duplicate information.

Вам также может понравиться