DBMS Ex No 9
DBMS Ex No 9
Cursor Creation
AIM:
To create a database and apply cursor.
Query:
Write a program in PL/SQL to create a cursor displays the name and salary of each
employee in the Employees table whose salary is less than that specified by a passed-in
parameter value.
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 display_salary() using explicit cursor to get salary less than that
specified by a passed-in parameter value.
4. Call procedure to display the result.
Result:
Thus the database was created and cursor was applied successfully.
Left side content:
1.
create table employee_details
(
eid int primary key,
emp_name varchar(20),
1
dept_name varchar(10),
designation varchar(30),
salary int
);
2.
insert into employee_details values(5,'sweety','cse','tester',40000);
insert into employee_details values(4,'sai','cse','programmer',50000);
insert into employee_details values(1,'mala','ece','trainer',10000);
insert into employee_details values(2,'saratha','eee','liner',17000);
insert into employee_details values(3,'mathi','cse','designer',25000);
insert into employee_details values(8,'chitra','civil','supervisor',35000);
3.
delimiter $$
create procedure display_salary(in max_sal integer)
begin
declare ename_var varchar(20);
declare salary_var integer;
declare v_finished integer default 0;
declare cursor2 cursor for select emp_name,salary from employee_details where
salary<max_sal;
declare continue handler for NOT FOUND set v_finished=1;
open cursor2;
get_sal:loop
fetch cursor2 into ename_var,salary_var;
select concat(ename_var,concat('-',salary_var));
if v_finished=1 then
leave get_sal;
end if;
end loop get_sal;
close cursor2;
end $$
4.
call display_salary(30000);4.
concat(ename_var,concat('-',salary_var))
mala-10000
saratha-17000
mathi-25000