0% found this document useful (0 votes)
7 views19 pages

Stored Routines

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

Stored Routines

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

STORED ROUTINES

Functions, Stored Procedures, Triggers


Functions
• Are used to perform calculations and return ONLY one value.

• They are helpful in performing common computation tasks like


determining tax values from basic pay, grading for student marks
etc.
..
 General Syntax:
CREATE FUNCTION functionName(parameterName Datatype)
RETURNS dataType
BEGIN

//Function body

END;
….
 Example:
 A function to compute the total mark based on a coursework mark
and exam mark: Coursework=30% and Exam =70%

DELIMITER $$
CREATE FUNCTION totalMark(courseWorkMark INT, examMark INT)
RETURNS INT
BEGIN
RETURN courseWorkMark*0.3 + examMark*0.7;
END $$

 To use the function:


 SELECT totalMark(25,55) AS total FROM DUAL;

 Example 2:
 A function to compute the age based on the birthdate (dob) provided:

DELIMITER $$
DROP FUNCTION IF EXISTS ageFinder $$
CREATE FUNCTION ageFinder (dob DATE) RETURNS INT
BEGIN
RETURN TRUNCATE((DATEDIFF(SYSDATE(), dob)/365),0);
END $$

 To use the function:


 SELECT ageFinder (‘1980-02-03’) AS age FROM DUAL;
 SELECT RegNo, firstName, lastName, ageFinder(dateOfBirth) as age
From Student;
Task
 Create the following tables and enter at least 3 data records into each
of them:
 BUS(busID,busModel,RegNO,currentMilleage)
 TRIP(TripID,busID,DriverID,tripDate,TripDuration,totalRevenue)
 DRIVER(DriverID,DriverName,DriverContact)
 Create queries and display:
 busName,tripDate,TripDuration,totalRevenue
 busName,driverName,tripdate,tripDuration
 All buses and any trips they have done
 All drivers and any trips they have undertaken
 Create a function to compute the commission for each driver based on
the trip totalRevenue as follows:
Commission=(0.5*totalrevenue+25000)/60
Conditional Statements
• The main conditional statement is the IF statement.

• It has a minimum of 2 possible out comes but can be expanded to


many more.

• IF statements can also be nested



Example1: 2 Outcomes
Attaching a comment to student marks based on the condition:
 Above 50% --- Excellent; Less than 50% -- Improvement Needed

DELIMITER $$
CREATE FUNCTION commentGenerator(mark INT) RETURNS CHAR(45)
BEGIN
IF mark>=50 THEN
RETURN ‘Excelllent’;
ELSE
RETURN ‘Improvement Needed’;
END IF;
END $$

TESTING: SELECT commentGenerator(35) AS comment FROM DUAL;



Write a function that takes Marks scored as a parameter to
determine the GRADE
Where:
 80 - 100 -A
 75 – 79 - B+
 70 – 74 -B
 65 – 69 - B-
 60 – 64 - C+
 55 – 59 -C
 50 – 54 - C-
 45 – 49 -D
 0 – 44 -F
DELIMITER $$
CREATE FUNCTION GradeGenerator(mark INT) RETURNS CHAR(5)
BEGIN

IF mark>=80 THEN
RETURN ‘A’;
ELSEIF mark>=75 THEN
RETURN ‘B+’;
ELSEIF mark>=70 THEN
RETURN ‘B’;
ELSEIF mark>=60 THEN
RETURN ‘C+’;
ELSEIF mark>=55 THEN
RETURN ‘C’;
ELSEIF mark>=50 THEN
RETURN ‘C-’;
ELSE
RETURN ‘D’;
END IF;

END $$
Example 3: Calculations:
Computing the PAYE based on the conditions:
 IF GrossPay<235,000 – Paye = 0
 IF GrossPay between 235,000 and 410,000, Paye = 10%
 IF GrossPay is above 410,000, Paye = 30%
DELIMITER $$
CREATE FUNCTION payeCalculator(GrossPay INT) RETURNS INT
BEGIN
IF GrossPay<235000 THEN
RETURN 0;
ELSEIF GrossPay BETWEEN 235000 AND 410000 THEN
RETURN 0.1 * GrossPay;
ELSE
RETURN 0.3 * GrossPay;
END IF;
END $$

Nested IF statements:
These involve multiple layers of IF statements.

Example:
If a resident is from Kampala:
 Taxes are computed as follows: If income<130,000 no tax else 20% tax;
If resident is from Northern Uganda
 Taxes are computed as follows: If income<100,000 no tax else 15% tax;
All other areas:
 Taxes are computed as follows: If income<150,000 no tax else 25% tax;
DELIMITER $$
CREATE FUNCTION taxByRegion(region CHAR(35), income INT) RETURNS INT
BEGIN
If region=‘Kampala’ THEN
If income < 130,000 THEN
RETURN 0;
ELSE
RETURN 0.2 * income;
END IF;
ELSEIF region=‘Northen’ THEN
If income < 100,000 THEN
RETURN 0;
ELSE
RETURN 0.1 * income;
END IF;
ELSE
If income < 150,000 THEN
RETURN 0;
ELSE
RETURN 0.25 * income;
END IF;
END IF;
END $$

DELIMITER $$
CREATE FUNCTION hallAssigner(gender CHAR(10), age INT) RETURNS CHAR(25)
BEGIN
IF gender=‘M’ THEN
IF age > 21 THEN
RETURN ‘ABUBAKAR’;
ELSE
RETURN ‘UTHMAN’;
END IF;
ELSE
IF age > 21 THEN
RETURN ‘SUMAYYAH’;
ELSE
RETURN ‘KASWAMPA’;
END IF;
END IF;
END $$
DELIMITER;

Using CURSORS:
Cursors are important when the function needs to obtain data to be used
in the calculation from an existing table.

There are 2 types of cursors:


 Implicit – Which is not directly declared
 Explicit which is directly declared and managed by the user.
Implicit Cursors
Implicit cursors make use of the SELECT .. INTO .. Statement

EXAMPLE
To Create a function that gives a comment based on the total purchases
done so far:
 IF purchases are less than 3 million – “Sustainable” else “Unsustainble”
The total value of purchases must be obtained from the purchases table
before being used in making the comment.
TASK
To Create a function that gives a comment based on the total purchases
done so far:
 purchases are LESS than average purchases – “Low”
 purchases are EQUAL to average purchases – “Average”
 purchases are MORE than average purchases – “High”

The total value of purchases must be obtained from the purchases table
before being used in making the comment.

Include the function in a Select statement to determine the status of each


purchase.
Solution – Implicit cursor
DELIMITER $$
CREATE FUNCTION purchasesAssessment() RETURNS CHAR(45)
BEGIN
DECLARE totalPurchases INT;
SELECT SUM(amount) INTO totalPurchases FROM
purchases;
IF totalPurchases < 3000000 THEN
RETURN CONCAT(totalPurchases, ‘ is Sustainable’);
ELSE
RETURN CONCAT(totalPurchases, ‘ is Unsustainable’);
END IF;
END $$

SELECT purchaseassessment() AS Comment FROM DUAL;


Solution – Explicit cursor
DELIMITER $$
CREATE FUNCTION purchasesAssessmentExplicit() RETURNS CHAR(45)
BEGIN
DECLARE totalPurchases INT;
DECLARE purchaseCursor CURSOR FOR
SELECT SUM(amount) FROM purchases;
OPEN purchaseCursor;
FETCH purchaseCursor INTO totalPurchases;
CLOSE purchaseCursor;
IF totalPurchases < 3000000 THEN
RETURN CONCAT(totalPurchases, ‘ is Sustainable’);
ELSE
RETURN CONCAT(totalPurchases, ‘ is Unsustainable’);
END IF;
END $$
SELECT purchaseassessmentExplicit() AS Comment FROM DUAL;

You might also like