DBMS 6 Exp
DBMS 6 Exp
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;
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:
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))
Result:
Thus, the implementation of user defined functions and stored procedures using
MySQL was completed and verified successfully.