DBMS Ex No 8
DBMS Ex No 8
Cursor Creation
AIM:
To create a database and apply cursor.
Query:
Create an Employee table with an attributes { empid, empname, department
designation, Gross_salary . Using cursor, select the five highest paid employees
from the Employee table.
Introduction to MySQL cursor:
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 individually.
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: An asensitive cursor points to the actual data. An asensitive
cursor performs faster. 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 do not update the data that is being used
by an asensitive cursor.
You can use MySQL cursors in stored procedures, stored functions, and triggers.
Working with MySQL cursor:
I. Declare a cursor by using the DECLARE statement:
Syntax:
DECLARE cursor_name CURSOR FOR SELECT_statement;
The cursor declaration must be after any variable declaration.
II. Open the cursor by using the OPEN statement. The OPEN statement
initializes the result set for the cursor, therefore, you must call
the OPEN statement before fetching rows from the result set.
Syntax:
OPEN cursor_name;
III. FETCH statement to retrieve the next row pointed by the cursor and move
the cursor to the next row in the result set.
Syntax:
FETCH cursor_name INTO variables list;
IV. Deactivate the cursor and release the memory associated with it using
the CLOSE statement:
Syntax:
CLOSE cursor_name;
When working with MySQL cursor, you must also declare a NOT FOUND handler
to handle the situation when the cursor could not find any row.
To declare a NOT FOUND handler, you use the following syntax:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
The following diagram illustrates how MySQL cursor works.
List of Queries:
1. Create table employee_details with fields employee id, name, department,
designation, salary.
2. Insert 6 records for the table.
3. Create stored procedure highest_salary() using explicit cursor to get 5
highest salary.
4. Call procedure to display the result.
Result:
Thus the database was created and cursor was applied successfully.
4-50000
5-40000
8-35000
3-25000
2-17000