You are on page 1of 19

STORED

PROCEDURES
Introduction, Structure & Applications
Introduction
• Stored procedures perform the following functions:
• Enable multiple database operations to be conducted at the same
time.

• Enable advanced queries that depend on a number of data


sources to generate the desired results.

• Provide a secure platform for accessing tables and other database


objects without using basic SQL statements like SELECT, DELETE
etc
Structure
DELIMITER $$
CREATE PROCEDURE procedureName(parameter list)
BEGIN

#Procedure body

END $$
Example
• A procedure that logs all insertions of data into the
customer table:
• The procedure captures all the details needed for the customer
data insertion and the username that calls the procedure.

• Add two insert statements: one for the customer data, the
second for the logging data
Create the Logtable
• LogID (PK – Auto Increment),
• userName,
• activity,
• details,
• transactionTime
Consider the log table to have the following structure:
LOGTABLE(logID (PK), userName,activity,details,transactionTime)

DELIMITER $$
CREATE PROCEDURE customerEditor (customerID INT,customerName
CHAR(45), birthDate DATE,customerMobile CHAR(25), userNm CHAR(25))
BEGIN
INSERT INTO
customer(customerID,customerName,birthDatecustomerMobile)
VALUES (customerID,customerName,birthdate,customerMobile);

INSERT INTO logtable(NULL,userName,activity,details,transactionTime)


VALUES (userNm,’Added Customer’,
CONCAT(‘ID=’,customerID,’Name=’,customerName), SYSDATE());

END $$
DELIMITER;
TO RUN the Stored Procedure (in the Resultset tab):

CALL customerEditor(’Hakim Kassim’,’1999-02-06’,’0701-


338112’,’admin’);
Task
Create the following tables:
accountholder(accountNo[PK],accountName,CurrentBalance
)
Deposit(depositID[PK],accountNo,depositDate,depositAmo
unt)

Insert these records into accountholder:


AC001,Nambi Nusra,500000
AC002,Janat Hafswa,100000
AC003,Musa Ahmed,20000

Create a procedure that enables inserting a new deposit


record and also updates the current balance in accountholder
by the following formula:
NEW BALANCE = currentBalance + depositAmount
Solution
DELIMITER $$
CREATE PROCEDURE depositManager(accNo CHAR(25), depDate
DATE, depAmount BIGINT)
BEGIN
INSERT INTO Deposit(accountNo,depositDate,depositAmount)
VALUES(accNo,depDate,depAmount);
UPDATE accountholder SET
currentBalance=currentBalance+depAmount WHERE
accountNo=accNo;
END $$
DELMITER;
Running the Procedure
CALL depositManager(‘AC001’,’2013-03-02’,500000);
Task
• Create a table for withdrawal
• Create a procedure to manage withdrawals.
• adda control to prevent a customer from withdrawing more
than their current balance.
(hint:use a cursor to find the current balance)
Error Handling
• A number of possible errors can arise during database operations.
These are each numbered to enable easy identification.

• These may include – invalid data types, primary and foreign key
violations etc.

• Error handling enables such errors to be dealt with without causing


the database to report them in its own language.

• Examples of MySQL Error Numbers

1062 SQLSTATE: 23000 (ER_DUP_ENTRY) Duplicate entry '%s' for key %d

1216 SQLSTATE: 23000 (ER_NO_REFERENCED_ROW) Cannot add or update


a child row: a foreign key constraint fails

• There are 2 error handling mechanisms:

• EXIT Handlers
• Handle errors by allowing an exit of the procedure without the database
reporting any errors by itself.

• CONTINUE Handlers:
• Enable the procedure to continue execution by side stepping the error
Continue Handlers: Example
• Consider handling the error of duplicate entry in the
member table by informing the user that the account
number used already exists.
• MEMBER
• (accountNo,
• memberName,
• phoneNo,
• currentBalance)

• We shall create a stored procedure to return Account


Created or Account Number already used depending on
a duplicate account No error error handled
delimiter $$
CREATE PROCEDURE memberData(accountNo

CHAR(25),memberName CHAR(35),phoneNo CHAR(35))
BEGIN
DECLARE comm VARCHAR(45);
DECLARE CONTINUE HANDLER FOR SQLSTATE '23000'
BEGIN
SET comm='Account No Already Used';
END;
SET comm='Account Created';
INSERT INTO member VALUES
(accountNo,memberName,phoneNo,0);
SELECT comm FROM DUAL;
END $$
delimiter ;

CALL memberData(‘AC001’,’Madam Massy’,’0705-552285’);



delimiter $$
CREATE PROCEDURE memberDataManager(accountNo
CHAR(25),memberName CHAR(35),phoneNo CHAR(35))
BEGIN
DECLARE comm VARCHAR(45);
DECLARE CONTINUE HANDLER FOR 1062
BEGIN
SET comm=CONCAT('Account No ',accountNo,' is lready Used');
END;
SET comm='Account Created';
INSERT INTO member VALUES
(accountNo,memberName,phoneNo,0);
SELECT comm AS DBReply FROM DUAL;
END $$
delimiter ;
Exit Handlers: Examples
delimiter $$
CREATE PROCEDURE memberDataExit(accountNo
CHAR(25),memberName CHAR(35),phoneNo CHAR(35))
BEGIN
DECLARE comm VARCHAR(45);
DECLARE EXIT HANDLER FOR SQLSTATE '23000'
BEGIN
SET comm='Account No Already Used';
SELECT comm FROM DUAL;
END;
INSERT INTO member VALUES
(accountNo,memberName,phoneNo,0);
END $$
delimiter ;

delimiter $$
CREATE PROCEDURE memberDataManager(accountNo
CHAR(25),memberName CHAR(35),phoneNo CHAR(35))
BEGIN
DECLARE comm VARCHAR(45);
DECLARE EXIT HANDLER FOR 1062
BEGIN
SET comm='Error';
END;
INSERT INTO member VALUES
(accountNo,memberName,phoneNo,0);
END $$
delimiter ;

You might also like