Professional Documents
Culture Documents
My SQLPLSQL Final
My SQLPLSQL Final
My SQLPLSQL Final
3. PL/SQL
MySQL Stored Procedure
and User- Defined Function
PL/SQL 12-May-22
2 Stored Procedure
PL/SQL 12-May-22
3 Three Ways to CreateA
Procedure
1. Save the procedure commands in a text
file.
2. Use the phpMyAdmin or other utility to
enter commands.
PL/SQL 12-May-22
4 Example of a command file
DELIMITER //
With client:
Routines/select the procedure and click execute
With the command prompt:
CALL stored_procedure_name
(param1, param2, ....);
PL/SQL 12-May-22
7 CREATE PROCEDURE
ProcName()
Stored procedure names are case
insensitive
A procedure may have parameters
PL/SQL 12-May-22
Define parameters within a stored procedure
8 Parameter list isempty
CREATE PROCEDURE proc1 ():
Define input parameter with key word IN:
CREATE PROCEDURE proc1 (IN varnameDATA-
TYPE)
The word IN is optional because parameters are
IN (input) by default.
Define output parameterwith OUT:
CREATE PROCEDURE proc1 (OUT varnameDATA-
TYPE)
A procedure may have input and output
paramters:
CREATE PROCEDURE proc1 (INOUT varname
PL/SQL
DATA-TYPE) 12-May-22
9 Executable Section
BEGIN
Statements
END
PL/SQL 12-May-22
Examples of parameters
10
CREATE PROCEDURE proc_IN (IN var1 INT)
BEGIN
SELECT var1 + 2 AS result;
END;
CURRENT_DATE;
FROM products;
PL/SQL 12-May-22
14 SELECT … INTO
PL/SQL 12-May-22
15 Arithmetic and string
operators
Arithmetic operators:
+, -, *,/
Modulo operator:
% or mod
Other math calculations use math functions:
Pow(x,y)
Concatenation uses CONCAT function:
SELECT CONCAT('New ', 'York ', 'City');
PL/SQL 12-May-22
16 MySQL Comparison
Operators
EQUAL(=)
LESS THAN(<)
LESS THAN OR EQUAL(<=)
GREATER THAN(>)
GREATER THAN OR EQUAL(>=)
NOT EQUAL(<>,!=)
PL/SQL 12-May-22
Logical Operators
17
Logical AND:
AND, &&
PL/SQL 12-May-22
IFstatement: The IFstatement can have
18 THEN, ELSE, and ELSEIFclauses, and it is
terminated with ENDIF.
IF variable1 = 0 THEN
SELECT variable1;
END IF;
IF param1 = 0 THEN
SELECT 'Parameter value = 0';
ELSE
SELECT 'Parameter value <> 0';
END IF;
PL/SQL 12-May-22
19
CASE Statement
PL/SQL 12-May-22
21 Comment Syntax
PL/SQL 12-May-22
A Procedure to compute tax that takes sidIN and
22 taxRate as inputs and return taxOut as output
DELIMITER //
CREATE PROCEDURE Caltax(sidIN char(5), taxRate double, out taxOut
double)
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
COMMENT 'Aprocedure'
BEGIN
DECLARE tax DOUBLE;
DECLARE empSalary DOUBLE;
select Salary into empSalary from salesreps where sid = sidIN;
set taxOut=taxRate*empSalary;
END
// PL/SQL 12-May-22
23
PL/SQL 12-May-22
User-Defined
24 Temporary Variables
• User variables are written as @var_name.
PL/SQL 12-May-22
Example ofrunning the procedure
25
from the command prompt
mysql> delimiter ;
mysql> set @tax=0;
Query OK, 0 rows affected (0.00 sec)
mysql> call
PL/SQL
addOrder('O8','C12','S1','2013-06-10'); 12-May-22
Query OK, 0 rows affected, 1 warning (0.00 sec) because C12 not exist!
Example:Procedure
27
showCustomers
DELIMITER //
DROP PROCEDURE IF EXISTS showCustomers;
CREATE PROCEDURE showCustomers ()
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
COMMENT 'A procedure'
BEGIN
Select * from Customers;
END
//
DELIMITER ;
PL/SQL 12-May-22
28 Calling a procedure with
OUT parameter
Must use MySQL temporary @variable to receive the
output value.
Because a stored procedure does not return to PHP
anything, it returns the value into the MySQL variable
(@return) (scope is in MySQL), so you need to query
this variable in a separate call.
PL/SQL 12-May-22
Triggers
29
PL/SQL 12-May-22
31 OLD and NEW
PL/SQL 12-May-22
32 Example: Customer Rating
Change Log
Table name: CustomerLog
Fields: CID, Cname, OldRating,NewRating
PL/SQL 12-May-22
Demo :New and :Old
33
delimiter //
DROP TRIGGER IF EXISTS ratingChanged;
CREATE TRIGGER ratingChanged AFTER UPDATE ON
customers FOR EACH ROW
BEGIN
insert into customerlog
values(old.cid,old.cname,old.rating,new.rating);
END
//
PL/SQL 12-May-22
delimiter ;
34 Example
mysql> update customers set rating='c' where cid='C1';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
PL/SQL 12-May-22
Updating the onhand quantity after a new detail line is added:
35
delimiter //
DROP TRIGGER IF EXISTS adddetail;
CREATE TRIGGER adddetail AFTER INSERT ON odetails
FOR EACH ROW
BEGIN
DECLARE stocks decimal(5,1);
select onhand into stocks from products where pid=new.pid;
update products set onhand=onhand - new.qty where pid=new.pid;
END
//
delimiter ;
PL/SQL 12-May-22
User Defined Functions
36
Stored functions differ from stored procedures in that stored
functions actually return a value.
Stored functions have only input parameters (if any
parameters at all), so the IN , OUT , and INOUT keywords aren’t
used.
Stored functions have no output parameters; instead, you use
a RETURN statement to return a value whose type is
determined by the RETURNS type statement, which precedes
the body of the function.
PL/SQL 12-May-22
Example
37 DELIMITER //
DROP FUNCTION IF EXISTSempTax;
CREATE FUNCTION empTax(Salary Decimal(10,2)) RETURNS
Decimal(10,2)
BEGIN
Declare tax decimal(10,2);
if salary <3000.00 then
set tax=salary*0.1;
elseif Salary <5000.00then
set tax=Salary*0.2;
else
set tax=Salary*0.3;
end if;
return tax;
END
//
PL/SQL 12-May-22
38 Using the User-defined
Function with SQL
mysql> delimiter ;
mysql> select sname, emptax(Salary) as tax from salesreps;
+-------+---------+
| sname | tax |
+-------+---------+
| PETER | 1950.00 |
| PAUL | 2160.00 |
| MARY | 2250.00 |
+-------+---------+
3 rows in set (0.00 sec)
PL/SQL 12-May-22
39 Cursors
PL/SQL 12-May-22
40 Cursor has three important
properties
The cursor will not reflect changes in its source tables.
Read Only :Cursors are not updatable.
Not Scrollable :Cursors can be traversed only in one
direction, forward, and you can't skip records from
fetching.
PL/SQL 12-May-22
Defining and Using Cursors
41
Declare cursor:
DECLARE cursor-name CURSOR FOR SELECT
...;
DECLARE CONTINUE HANDLER FOR NOT FOUND:
Specify what to do when no more records found
DECLARE b INT;
DECLARE CONTINUE HANDLER FOR NOT FOUND SETb =1;
Open cursor:
OPEN cursor-name;
CLOSE cursor:
PL/SQL 12-May-22
CLOSE cursor-name;
Cursor Example
42 DELIMITER //
DROP Procedure IF EXISTS maleSum;
CREATE Procedure maleSum(OUT sumSalary Decimal(10,2))
BEGIN
DECLARE Sal,sumSal decimal(10,2);
DECLARE continueFlag int default 0;
DECLARE maleCursor CURSOR FOR SELECT Salary FROM salesreps where sex='M';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET continueFlag = 1;
OPEN maleCursor;
SET Sal = 0;
SET sumSal= 0;
WHILE continueFlag = 0 DO
FETCH maleCursor INTO Sal;
IF continueFlag = 0 THEN
SET sumSal = sumSal+Sal;
END IF;
END WHILE;
CLOSE maleCursor;
SET sumSalary=sumSal;
END
PL/SQL 12-May-22
//
A procedure to create email list using cursor
43 DELIMITER //
DROP PROCEDURE IF EXISTS emailgroup;
CREATE PROCEDURE emailgroup (INOUT emaillist varchar(4000))
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
COMMENT 'Aprocedure'
BEGIN
DECLARE continueFlag INTEGER DEFAULT 0;
DECLARE useremail varchar(100) DEFAULT "";
DEClARE email_cursor CURSOR FOR SELECT email FROM users;
= 1D;ECLARE CONTINUE HANDLER FOR NOT FOUND SET continueFlag
OPEN email_cursor;
WHILE continueFlag = 0 DO
FETCH email_cursor INTO useremail;
IF continueFlag = 0 THEN
SET emaillist = CONCAT(useremail,";",emaillist);
END IF;
END WHILE;
CLOSE email_cursor;
END
// PL/SQL 12-May-22
DELIMITER ;