Exp No 5
Exp No 5
Create cursor for Employee table & extract the values from the table. Declare
the variables, Open the cursor & extract the values from the cursor. Close the cursor.
Employee (E_id, E_name, Age, Salary)
Solution:
mysql >CREATE DATABASE COMPANY05;
mysql>USE COMPANY05;
Database changed
E_name VARCHAR(255),
Age INT,
Salary DECIMAL(10, 2)
);
To create a cursor for the `Employee` table, extract values using the cursor, and then close the
cursor in MySQL, you’ll need to use stored procedures that support cursor operations.
DELIMITER $$
CREATE PROCEDURE fetch_employee_data()
BEGIN
#Declare variables to store cursor values
DECLARE emp_id INT;
DECLARE emp_name VARCHAR(255);
DECLARE emp_age INT;
DECLARE emp_salary DECIMAL(10, 2);
DECLARE finished INT DEFAULT 0;
#Declare a cursor for the Employee table
DECLARE emp_cursor CURSOR FOR
SELECT E_id, E_name, Age, Salary FROM Employee;
DELIMITER;
------------------------------------------------------------------------------------------------------------------
How to Execute & Test the Procedure:
1. Call the procedure to fetch employee data:
CALL fetch_employee_data();
Step Purpose
DELIMITER $$ Changes the delimiter to $$ to allow multi-line SQL statements.
CREATE PROCEDURE Defines a new stored procedure.
BEGIN Starts the procedure body.
DECLARE Variables Stores values retrieved from the Employee table.
DECLARE CURSOR Defines a cursor to iterate over the Employee table.
CONTINUE HANDLER Handles the "no more rows" condition gracefully.
OPEN Cursor Opens the cursor to fetch data.
LOOP Iterates over the rows retrieved by the cursor.
FETCH Retrieves the next row into variables.
IF Condition Stops the loop if no more rows exist.
SELECT Displays employee details in a readable format.
END LOOP Ends the cursor loop.
CLOSE Cursor Closes the cursor to free resources.
END $$ Ends the stored procedure definition.
DELIMITER ; Resets the delimiter to ; for normal queries.
CALL Procedure Executes the stored procedure.