0% found this document useful (0 votes)
26 views

DBMS 6 Exp

DBMS 6 exp

Uploaded by

abinayadev04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

DBMS 6 Exp

DBMS 6 exp

Uploaded by

abinayadev04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Exp.

No: 6 USER DEFINED FUNCTIONS AND STORED


Date: PROCEDURES

Aim:
To implement user defined functions and stored procedures using MySQL.

Functions:
It is the sub program that returns a single value. Define and declare the
function before invoking it. Here both define and declare can be done at the
same time.
Syntax:
Create or replace function <function_name> ([parameter datatype, parameter
datatype])
returns datatype
begin
< declaration section >
< executable statements >
end;

Checking whether the given number is odd or even using function.


use samp;
delimiter $$
create function iseven(num int)
returns int
deterministic
begin
if (mod(num,2) = 0) then
return 1;
else
return 0;
end if;
end$$
Calling the function:
select iseven(200);
Output:

Find the factorial of a given number using function.


delimiter $$
create function factorial(num int)
returns bigint
deterministic
begin
declare result bigint default 1;
declare i int default 1;
if num < 0 then
return null;
end if;
while i <= num do
set result = result * i;
set i = i + 1;
end while;
return result;
end$$
delimiter;
Calling the function:
Select factorial (5);
Output:
Create a function in MySQL which return the cube of a given value.
delimiter $$
create function fun_cube(num int)
returns int
deterministic
begin
declare totalcube int;
set totalcube = num*num*num;
return totalcube;
end$$
Calling the function:
Select fun_cube(4);
Output:

Function to concatenation of strings:


use test;
create table employee1 (
employee_id int primary key,
department_id int,
employee varchar(50) );
insert into employee1 (employee_id, department_id, employee) values
(1, 1, 'karthika'), (2, 1, 'madhumitha'), (3, 2, 'abinaya'),
(4, 2, 'sangamithra'), (5, 3, 'pavani');
delimiter $$
create function getemployeessid(dept_id int)
returns varchar(50)
deterministic
begin
declare employeeid varchar(50) default '';
declare continue handler for not found set employeeid = null;
select concat(department_id, ' ', employee)
into employeeid
from employee1
where department_id = dept_id
limit 1;
return employeeid;
end$$
delimiter;
select getemployeessid(1);
Output:

Using IF statement:
delimiter $$
create function demoavg(item int) returns int
deterministic
begin
declare myitem int default 0;
if item<10000 then
set myitem=item+(item*0.01);
else
set myitem=item+(item*0.05);
end if;
return (myitem);
end $$
delimiter;
select employee_id, employee, demoavg(department_id) from employee1;
Output:

Update using CASE:


To find the incentives of each employee based on the salary:
create table empsal (
id int,
name varchar(40),
salary float,
incentives float );
insert into empsal (id, name, salary, incentives) values
(1, 'karthika', 500, null), (2, 'abinaya', 600, null),
(3, 'sangamithra', 3000, null),
(4, 'madhumitha', 4000, null),
(5, 'pavani', 5000, null);
select * from empsal;
update empsal
set incentives = case
when salary < 1000 then salary * 0.05
when salary < 5000 and salary >= 1000 then salary * 0.07
else salary * 0.10
end;
select * from empsal;
Output:

Age calculation using function:


create table employee2 (
employeeid int primary key,
name varchar(50),
salary int,
dob date );
insert into employee2(employeeid, name, salary, dob) values(1001, 'karthika',
10000, '1996-07-24');
insert into employee2(employeeid, name, salary, dob) values(1002, 'abinaya',
20000, '1992-06-22');
insert into employee2(employeeid, name, salary, dob) values(1003,
'sangamithra', 30000, '1978-04-12');
insert into employee2(employeeid, name, salary, dob) values(1004,
'madhumitha', 30000, '1988-04-12');
insert into employee2(employeeid, name, salary, dob) values(1005, 'pavani',
30000, '1978-05-12');
delimiter $$
create function func_calculate_age (
age date
)
returns int deterministic
begin
declare todaydate date;
select current_date() into todaydate;
return year(todaydate) - year(age);
end$$
delimiter;
select employeeid, name, salary, dob, func_calculate_age(dob) as age from
employee2;
Output:

Stored Procedures:
A procedure (often called a stored procedure) is a subroutine like a
subprogram in a regular computing language stored in database. A procedure
has a name, a parameter list, and SQL statement(s). All most all relational
database system supports stored procedure, MySQL also supports stored
procedure. Procedures are made up of:
 Declarative part
 Executable part
 Optional exception handling part.
Stored procedures can accept parameter parameter when they are executed.
Procedures has a name, it can take parameters and can return values. It can be
stored in the data dictionary and can be called by many users.

Creating a Procedure:
A procedure is created using create or replace procedure statement. The
following syntax is used for creating a stored procedure in MySQL. It can return
one or more value through parameters or sometimes may not return at all. By
default, a procedure is associated with the current database.
Syntax:
DELIMITER &&
CREATE PROCEDURE procedure_name [[IN | OUT | INOUT]
parameter_name datatype, [parameter datatype])]
BEGIN
Declaration_section
Executable_section
END &&
DELIMITER;

Where,
 Procedure_name specifies the name of the procedure.
 [or replace] -option allows modifying an existing procedure.
 The optional parameter list contains name, mode and types of the
parameter.
 Here IN represents that values will be passed from outside and OUT
represents that this parameter will be used to return a value outside of the
procedure.
 Here, the declaration section represents the declaration of all variables.
 The executable section represents the code for the function execution.
Calling a stored procedure:
Use the CALL statement to call a stored procedure. This statement returns the
values to its caller through its parameters (IN, OUT, or INOUT). The following
syntax is used to call the stored procedure in MySQL.
CALL procedure_name (parameter (s))

Creating a table ‘Branch’ and inserting values into it:


create table branch(
bid int,
bname varchar(20),
addr varchar(30)
);
insert into branch values(1,'branch1','ABC');
insert into branch values(2,'branch2','PQR');
insert into branch values(1,'branch1','XYZ');

Creating a table ‘Employee2’ and inserting values into it:


create table employee2
(empid int,ename varchar(20),jobdesc varchar(20),salary int,bid int);
insert into employee2 values (456,'Karthika',"Software Developer",100000,1);
insert into employee2 values (486,'Abinaya',"Software Developer",240000,2);
insert into employee2 values (487,'Madhumitha',"Software
Developer",400000,1);
insert into employee2 values (488,'Sangamithra',"Software
Developer",450000,1);
insert into employee2 values (489,'Pavani',"Software Developer",480000,1);

Code 1: without parameter:


delimiter $$
create procedure branchesCount()
begin
declare total int default 0;
select count(bid) into total from branch;
select total;
end $$
delimiter;
call branchesCount;
Output:
Code 2: with IN parameter:
delimiter $$
create procedure jobcount(IN jdesc varchar(20))
begin
select count(empid) from employee2 where jobdesc=jdesc;
end $$
delimiter;
call jobcount('Software Developer');
Output:

Code 3: with OUT Parameter:


delimiter $$
create procedure jobcount2(IN jdesc varchar(20),OUT total int)
begin
select count(empid) into total from employee2 where jobdesc=jdesc;
end $$
delimiter;
call jobcount2('Software Developer', @total);
select @total;
Output:

Code 4: Procedure with both IN and OUT parameter:


delimiter $$
create procedure counterProcedure(inout counter int, in c int)
begin
set counter=counter+c;
end $$
delimiter ;
set @counter=10;
call counterProcedure(@counter,5);
select @counter;
call counterProcedure(@counter,10);
select @counter;
Output:

Procedure using If else statement:


delimiter $$
create procedure state(in bid int)
begin
if bid=1 then select "Tamil Nadu" as "State";
else select "Kerala" as "State";
end if;
end $$
delimiter;
call state(1);
Output:

Procedure Using Case statement:


delimiter $$
create procedure state2(in bid int)
begin
case bid
when 1 then select "Tamil Nadu" as "State";
when 2 then select "Kerala" as "State";
end case;
end $$
delimiter;
call state2(2);
Output:

Using LOOP statement:


delimiter $$
create procedure loop1(out c int)
begin
declare i int;
set i=0;
set c=0;
label1:loop
set c=c+1;
if i>10 then leave label1;
end if;
set i=i+1;
end loop;
end $$
delimiter;
call loop1(@c1);
select @c1;
Output:

Using WHILE statement:


delimiter $$
create procedure while1(out c int)
begin
declare i int;
set i=0;
set c=0;
while i<10 do
set c=c+1;
set i=i+1;
end while;
end $$
delimiter;
call while1(@c);
select @c;
Output:

Procedure using Select Query:


delimiter $$
create procedure ViewingEmployee()
begin
select ename from employee2 where ename='Karthika';
end $$
delimiter;
call ViewingEmployee;
Output:

Procedure to insert a new record into a table:


delimiter $$
create procedure insertingEmployee(
in empid int,
in ename varchar(255),
in jobdesc varchar(255),
in salary decimal(10,2),
in bid int
)
begin
insert into employee2 (empid, ename, jobdesc, salary, bid)
values (empid, ename, jobdesc, salary, bid);
end $$
delimiter;
call insertingEmployee(6,'Employee6','EEE',200000,3);
Output:
Procedure to update the record of a table:
delimiter $$
create procedure updateSalary(IN salary int)
begin
if salary>100000 then
update employee2 set salary=salary+1000;
else
update employee2 set salary=salary+20000;
end if;
end $$
delimiter;
call updateSalary(4800000);
Output:

Procedure to delete a record:


delimiter $$
create procedure deleteEmployee(in emp_id int)
begin
delete from employee2 where empid=emp_id;
end $$
delimiter;
call deleteEmployee(1);
Output:
Procedure using update with If else statement:
delimiter $$
create procedure updateSalary(IN salary int)
begin
if salary>100000 then
update employee2 set salary=salary+1000;
else
update employee2 set salary=salary+20000;
end if;
end $$
delimiter;
call updateSalary(4800000);
Output:

Using loop to update the record in the table:


delimiter $$
create procedure loopingUpdate()
begin
declare counter int default 0;
declare sub int default 1;
select count(*) into counter from employee2;
select counter;
while counter > 0 do
update employee2 set salary = salary - sub;
set counter = counter - 1;
end while;
end $$
delimiter;
call loopingUpdate();
Output:

Result:
Thus, the implementation of user defined functions and stored procedures using
MySQL was completed and verified successfully.

You might also like