Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Java

1. Stored procedures allow SQL code to be stored in a database and invoked when needed. 2. They can accept input parameters and return output parameters or result sets. 3. The main components of stored procedures in MySQL are procedures, functions, and triggers.

Uploaded by

Kalpa De Silva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java

1. Stored procedures allow SQL code to be stored in a database and invoked when needed. 2. They can accept input parameters and return output parameters or result sets. 3. The main components of stored procedures in MySQL are procedures, functions, and triggers.

Uploaded by

Kalpa De Silva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

DBMS II – Stored Procedure version 1.

MySQL Stored Routines

The routines are stored on the Server

They belong to a database

They are based on standard SQL specification

Three main components are

Procedure -(IN,OUT,INOUT parameter) returns one or more data set as OUT parameters, possible to
use dynamic SQL

Function - has only input parameters, return one value of a given type, cannot use dynamic SQL, can
return data set

Trigger - special kind of stored procedure that automatically executes when an event occurs in the
database server

Stored Procedure

A stored procedure is a set of SQL code which is stored in the database server and can be invoked by
program or trigger or stored procedure itself. The stored procedure is a way to execute may task on
your database server directly, in other words stored procedure is a way to execute your business logic
directly into the database server.

Suppose you have a normal banking system where you want to update interest of a loan of any specific
user. What you will normally do from your program? You will fetch capital, the rate of interest and
duration and calculate interest and then you will go back to the database and save the data. In this
very small example we are going 2 time in database, but if we will use the stored procedure then we
need to write all operation within our stored procedure and we will call it through the program one
time. In this case you will fetch data like capital, rate of interest and duration within database(with
stored procedure) and you will save data after processing. In this case we are only interrupting
database server one time. Thanks to the stored procedure which reduced our server overhead.

Advantage of Mysql Stored Procedure

1. Multiple applications are running in multiple environment and need to use the same
database. By using stored procedure you can make your business logic independent of
programming language.
2. When security is main concern use of stored procedure is vital. By doing your operation
through the database you can log your all performed action. Banking site is the best
example.
3. If you are using stored procedure then you do not have table access directly which is one
more way to secure the data and transaction.
4. Stored procedure increases performance of your application sometime.

All rights reserved


DBMS II – Stored Procedure version 1.0

5. If your application is big or your database server on remote system then by using stored
procedure you can decrease the traffic between your database server and application
server.
6. Since stored procedure is written in your database server and application call it sepratly then
the degree of re-usability.

Disadvantages of using stored procedure

1. Sometime use of stored procedure is bit risky. Store procedure follow “define one use many
time” philosophy. Doing change in stored procedure directly affect your data so it should
always be use with very carefully.
2. Stored procedure are set of sql command form our logic so sometime programmer need to
debug the stored procedure. In mysql stored procedure it is very hard to debug.
3. Managing stored procedure is bit difficult because it does not have any object oriented
paradigm like things.
4. If you use a lot of stored procedures, the memory usage of every connection that is uing
those stored procedures will increase substantially. In addition, if you overuse a large
number of logical operations inside stored procedures, the CPU usage will also incrase
because database server is not well-designed for logical operations.
5. Developing and maintaining stored procedures are often required specialized skill.
Question 01
DROP PROCEDURE IF EXISTS p1;
CREATE
PROCEDURE p1()
Select 'hello test';

Quesion 02

DROP PROCEDURE IF EXISTS p2;


DELIMITER $$;
CREATE
PROCEDURE p2()
BEGIN
Select ‘hello test’;
END$$;
DELIMITER ;

Quesion 03

DROP PROCEDURE IF EXISTS p3;


DELIMITER $$;
CREATE
PROCEDURE p3()
BEGIN
Declare var1 varchar(100);
Set var1= ‘This is my test program’;
END$$;
DELIMITER ;

All rights reserved


DBMS II – Stored Procedure version 1.0

Assign values to variables can be used set command.

Define a variable var1 and assign a text called ‘this is my test


program’, when you run this program you would not see any output
because you havent print the output.

Quesion 04

DROP PROCEDURE IF EXISTS p4;


DELIMITER $$;
CREATE
PROCEDURE p4()
BEGIN
Declare var1 varchar(100);
Set var1= ‘This is my test program’;
Select var1;
END$$;
DELIMITER ;

Now you can see the output like ‘This is my test program’

Quesion 05

DROP PROCEDURE IF EXISTS p5;


DELIMITER $$;
CREATE
PROCEDURE p5()
BEGIN
Declare var1 varchar(100) default ‘This is my test program’;
Declare var2 int default 5;
Declare var3 int;
Select var1;
Select var2;
Select var3;
END$$;
DELIMITER ;

Initialize veriable
Var3 is null – define the reason and correct it

All rights reserved


DBMS II – Stored Procedure version 1.0

Quesion 06

DROP PROCEDURE IF EXISTS p6;


DELIMITER $$;
CREATE
PROCEDURE p6()
BEGIN
BEGIN
declare var1 varchar(50);
set var1='This is my private data';
END;
select var1='Error of accessing var1 because var1 is out of scope';
END$$;
DELIMITER ;

Quesion 07

create database ijse;


create table employee(empid varchar(10),name varchar(100));
insert into employee values(‘1’,’Nimal Perera’);
insert into employee values(‘2’,’Mohan Dias’);

DROP PROCEDURE IF EXISTS p7;


DELIMITER $$
CREATE
PROCEDURE p7()
BEGIN
SELECT * FROM `employee`;
END$$
DELIMITER ;

NOTE

There are three type of parameter you can define.


1. IN parameter – input of the stored procedure
2. OUT parameter - output parameter
3. INOUT parameter – shared parameter , it can be use either as input or output parameter

Quesion 08

DROP PROCEDURE IF EXISTS p8;


DELIMITER $$
CREATE
PROCEDURE p8(IN employee_name VARCHAR(255))
BEGIN
SELECT * FROM `employee` WHERE `employee`.`name` like employee_name;
END$$
DELIMITER ;

All rights reserved


DBMS II – Stored Procedure version 1.0

Why use delimiter ‘$$’ ?

The delimiter is the character or string of characters that you'll use to tell the mySQL client that
you've finished typing in an SQL statement. For ages, the delimiter has always been a semicolon .
That, however, causes problems, because, in a stored procedure, one can have many statements, and
each must end with a semicolon.
Quesion 09
create table item(
id varchar(10),
name varchar(100),
price decimal(10,2),
constraint primary key(id)
);

create table order_detail(


oid varchar(10),
id varchar(10),
orderQty int,
constraint primary key(oid,id),
constraint foreign key(id) references item(id)
);

insert into item values('i001','LED TV 15',25000.00);


insert into item values('i002','LED TV 16',27000.00);
insert into item values('i003','Grinder',2800.00);
insert into item values('i004','Bulbs',25.00);

insert into order_detail values('2345','i001',1);


insert into order_detail values('2345','i002',1);
insert into order_detail values('2345','i003',1);

DROP PROCEDURE IF EXISTS p9;


DELIMITER $$
CREATE
PROCEDURE p9(OUT minP double, OUT maxP double, OUT avgP double)
BEGIN
select min(price)
into minP
from item;
select max(price)
into maxP
from item;
select avg(price)
into avgP
from item;
END$$
DELIMITER ;

All rights reserved


DBMS II – Stored Procedure version 1.0

INTO can be used to return the sql value to the procedure variable,
remember one value can be retured to the procedure variable.

Quesion 10
See the different in Q3 and Q4
DROP PROCEDURE IF EXISTS p10;
DELIMITER $$
CREATE
PROCEDURE p10()
BEGIN
select min(price)from item;
select max(price)from item;
select avg(price)from item;
END$$
DELIMITER ;

Quesion 11

DROP PROCEDURE IF EXISTS p11;


DELIMITER $$
CREATE
PROCEDURE p11(IN OrderID int, OUT total double)
BEGIN
select sum(i.price * od.orderQty) from item i,order_detail od where
i.id=od.id and oid=OrderID;
END$$
DELIMITER ;

Quesion 12

DROP PROCEDURE IF EXISTS p12;


DELIMITER $$
CREATE
PROCEDURE p12(IN OrderID int, OUT total double)
BEGIN
declare tot double;
declare user varchar(100);
select sum(i.price * od.orderQty) from item i,order_detail od where
i.id=od.id and oid=OrderID;
select sum(i.price * od.orderQty) from item i,order_detail od where
i.id=od.id and oid=OrderID into tot;
insert into abc value(tot);
select user() into user;
insert into howview value(OrderID,user);
END$$
DELIMITER ;

All rights reserved


DBMS II – Stored Procedure version 1.0

Quesion 13

DROP PROCEDURE IF EXISTS p13;


DELIMITER $$
CREATE
PROCEDURE p13(IN param int)
BEGIN
declare variable1 int;
set variable1 =param;
if variable1 < 0 then
select variable1;
end if;
if param = 0 then
select 'Parameter value is 0';
else
select 'Parameter value <> l to 0';
end if;
END$$
DELIMITER ;

Quesion 14

DROP PROCEDURE IF EXISTS p14;


DELIMITER $$
CREATE
PROCEDURE p14(IN a int,IN b int, IN c int)
BEGIN
................ PRINT THE BIGGEST NUMBER ..............
END$$
DELIMITER ;

Quesion 15

DROP PROCEDURE IF EXISTS p15;


DELIMITER $$
CREATE
PROCEDURE p15(IN credit int)
BEGIN
declare creditlimit int;
set creditlimit =credit;
if creditlimit < 5000 then
select 'Silver';
elseif (creditlimit >= 5000 and creditlimit <= 10000) then
select 'Gold';
elseif (creditlimit >= 10000 and creditlimit <= 15000) then
select 'Platinum';
else
select 'Diamond';
end if;
END$$
DELIMITER ;

All rights reserved


DBMS II – Stored Procedure version 1.0

Quesion 16

Create table table1(


Id int
);
DROP PROCEDURE IF EXISTS p16;
DELIMITER $$
CREATE
PROCEDURE p16(IN param1 int)
BEGIN
declare variable1 int;
set variable1=param1 +1;
case variable1
when 0 then
insert into table1 values(param1);
when 1 then
insert into table1 values(variable1);
else
insert into table1 values(99);
end case;
END$$
DELIMITER ;
Or
case
when variable1 = 0 then
INSERT INTO table1 VALUES (param1);
when variable1 = 1 then
INSERT INTO table1 VALUES (variable1);
else
INSERT INTO table1 VALUES (99);
end case;

All rights reserved


DBMS II – Stored Procedure version 1.0

Quesion 17

We must have to declare exit handler in stored procedure to perform


the rollback and there are
two type of handler in mysql stored procedure
1. sqlexception - occures during the query execution
2. sqlwarning - when any warining occurs in mysql

create table errorTest(


id int primary key,
name varchar(20)
);

DROP PROCEDURE IF EXISTS p17;


DELIMITER $$;
CREATE
PROCEDURE p17()
BEGIN

DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error


encountered';
DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException
encountered';

insert into errorTest values(2,'sss');


END$$;
DELIMITER ;
Quesion 18
DROP PROCEDURE IF EXISTS p18;
DROP PROCEDURE test;
DELIMITER $$;
CREATE
PROCEDURE p18()
BEGIN
declare duplicate_key int default 0; /* line A */
BEGIN /* -- Line B */
DECLARE EXIT HANDLER FOR 1062 /*duplicate key*/ set
duplicate_key=1;

insert into errortest values(3,'ddd'); -- Line D

END; /* -- Line C */

if(duplicate_key =1) then /* -- Line E */


select 'failed to insert duplicate key';
end if;
END$$;
DELIMITER ;

[The logic behind above procedure]

All rights reserved


DBMS II – Stored Procedure version 1.0

Line A: Declare a stuats variable that will record the status of our
insert attempt

Line B to C: This BEGIN-END block encloses the insert statement that


will attempt to create the 'errortest' record.The block includes the
EXIT handler that will terminate the block if a 1062 error occurs.

Line D: Attempt to insert our row - if we get a duplicate key error,


the handler will set the variable and terminate the block

Line E: Execution will then continue on this line, where we check the
value of the variable and - if the handler has fired - advise the user
that the insert was unsucessful.

Quesion 19
Create table t1(
Id int
);
Create table t2(
Id int
);
Create table t3(
Id int
);

Explain why transaction need

DROP PROCEDURE IF EXISTS p19;


DELIMITER $$
CREATE
PROCEDURE p19()
BEGIN
insert into t1 values(10);
insert into t2 values(20);
insert into t3 values(abc); /* abc can not be stored in integer */
END$$
DELIMITER ;

All rights reserved


DBMS II – Stored Procedure version 1.0

Quesion 20

Solution

Transaction in MySQL stored procedure

DROP PROCEDURE IF EXISTS p20;


DELIMITER $$
CREATE
PROCEDURE `ijse`.`p9`()
BEGIN
declare exit handler for SQLEXCEPTION
BEGIN
ROLLBACK;
END;
START TRANSACTION;
insert into t1 values(10);
insert into t2 values(20);
insert into t3 values(abc);
COMMIT;
END$$
DELIMITER ;

All rights reserved


DBMS II – Stored Procedure version 1.0

Exam Questions
Question 01

Consider following relational tables

Student(sid:varchar(10),name:varchar(100),contact:int)
PK-sid

Course(cid:int, cname:varchar(100),fee:decimal(10,2))

Registration(rid:int,rdate:date,fee:decimal(10,2),cid:int,sid:
varchar(100))

Commision(comid:int,rid:int,commission:decimal(10,2))

a. Implement student,course and registration tables with all table


constraints using mysql.[2 marks]
b. Write a mysql procedures to add new course. [2 marks]
addNewCourse(cname,fee)
c. Write a mysql procedure to register a new student to a course
in the institute. In this process, student and registration
tables need to be filled at the same time. And also a commission
need to be calculated and send to the commission table. The
person who does the registration process will be received the
commission at the end of the month.
Commission = (course fee * 2.5%)
doNewRegistration(sid,cid) [10 marks]

All rights reserved

You might also like