STORED PROCEDURE
STORED PROCEDURE
 A procedure is a subroutine (like a subprogram) in a
regular scripting language, stored in a database
 In the case of MySQL, procedures are written in MySQL
and stored in the MySQL database/server
 A MySQL procedure has a name, a parameter list, and
SQL statement(s)
STORED PROCEDURES
 Database program modules that are stored and
executed by the DBMS at the server
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;
WHY STORED PROCEDURES
 Reduces Duplication of effort and improves software modularity
ď‚— Multiple applications can use the stored procedure vs. the SQL
statements being stored in the application language (PHP)
Reduces communication and data transfer cost between
client and server (in certain situations)
ď‚— Instead of sending multiple lengthy SQL statements, the
application only has to send the name and parameters of the
Stored Procedure
Can be more secure than SQL statements
ď‚— Permission can be granted to certain stored procedures without
granting access to database tables
DISADVANTAGES OF STORED PROCEDURES
 Difficult to debug
ď‚— MySQL does not provide ways for debugging stored
procedures
Many stored procedures can increase memory use
ď‚— The more stored procedures you use, the more memory is
used
Can be difficult to maintain and develop stored procedures
ď‚— Another programming language to learn
CREATING STORED PROCEDURES
DELIMITER //
CREATE PROCEDURE NAME
BEGIN
SQL STATEMENT
END //
DELIMITER ;
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;
CALLING STORED PROCEDURES
CALL
STORED_PROCEDURE_NAME
CALL GetAllProducts();
TYPES OF MYSQL PROCEDURES:
1. Procedure with no parameters:
2. Procedure with IN parameter:
3. Procedure with OUT parameter:
4. Procedure with IN-OUT parameter:
1. PROCEDURE WITH NO PARAMETERS:
A procedure without parameters does not
take any input or casts an output
indirectly.
It is simply called with its procedure
name followed by () (without any
parameters).
It is used for simple queries.
EXAMPLE PROCEDURE WITH NO PARAMETERS
delimiter //
create procedure display_book()
-> begin
-> select *from book;
-> end //
call display_book(); //
PARAMETERS
 There may be times where you want to pass
information to the stored procedures
ď‚— Getting user input from a form and using that input in a
SQL statement
PROCEDURE WITH IN PARAMETER:
 An IN parameter is used to take a parameter as
input such as an attribute
 When we define an IN parameter in a procedure,
the calling program has to pass an argument to the
stored procedure
 The value of an IN parameter is protected
EXAMPLE PROCEDURE WITH IN PARAMETER:
delimiter //
create procedure update_price
(IN temp_ISBN varchar(10), IN new_price
integer)
-> begin
-> update book set price=new_price
-> where ISBN=temp_ISBN;
-> end; //
call update_price(001, 600); //
PROCEDURE WITH OUT PARAMETER:
 An OUT parameter is used to pass a parameter as
output or display like the select operator, but
implicitly (through a set value)
 The value of an OUT parameter can be changed
inside the procedure and its new value is passed
back to the calling program
 A procedure cannot access the initial value of the
OUT parameter when it starts.
EXAMPLE ON PROCEDURE WITH OUT
PARAMETER:
delimiter //
create procedure
disp_max(OUT highestprice integer)
-> begin
-> select max(price) into
highestprice from book;
-> end; //
call disp_max(@M); //
select @M;
PROCEDURE WITH IN-OUT PARAMETER:
 An INOUT parameter is a combination of IN and OUT
parameters
 It means that the calling program may pass the
argument, and the stored procedure can modify the
INOUT parameter and pass the new value back to the
calling program.
EXAMPLE ON PROCEDURE WITH IN-OUT PARAMETER
ARGUMENTS AND PARAMETERS
DELIMITER //
CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(25
BEGIN
SELECT * FROM offices WHERE country = countryName;
END //
DELIMITER ;
Defining
Calling
CALL GetOfficeByCountry('USA')
The values being copied from the calling stored procedure are calling
arguments.
The variables being copied into are called parameters.
OUT PARAMETER
DELIMITER //
CREATE PROCEDURE CountOrderByStatus(IN orderStatus
VARCHAR(25), OUT total INT)
BEGIN
SELECT count(orderNumber) INTO total FROM orders WHERE status =
orderStatus;
END//
DELIMITER ;
Defining
Calling
CALL CountOrderByStatus('Shipped',@total);
SELECT @total;
The out parameter is used outside of the stored
procedure.
VARIABLES
 A variable is a name that refers to a value
A name that represents a value stored in the
computer memory
C program
int name=“Amit”;
int age=25
 MySQL
DECLARE name VARCHAR(255)
DECLARE age INT
DELIMITER //
CREATE PROCEDURE declare2(IN value
int,IN name varchar(20))
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = value;
SET str = name;
SELECT x,str;
END//
DELIMITER ;
CONDITIONALS
THE “IF” STATEMENT
Mysql Syntax
IF if_expression THEN commands
[ELSEIF elseif_expression THEN commands]
[ELSE commands]
END IF;
First line is known as the IF clause
Includes the keyword IF followed by condition followed by the
keyword THEN
 When the IFstatement executes, the condition is tested,
and if it is true the block statements are executed.
Otherwise, block statements are skipped
“IFEXPRESSION”: BOOLEAN EXPRESSIONS AND
OPERATORS
IF STATEMENT
DELIMITER //
CREATE PROCEDURE
GetProductsInStockBasedOnQuantitityLevel(IN p_operator
VARCHAR(255), IN p_quantityInStock INT)
BEGIN
IF p_operator = "<" THEN
select * from products WHERE quantityInStock <
p_quantityInStock;
ELSEIF p_operator = ">" THEN
select * from products WHERE quantityInStock >
p_quantityInStock;
END IF;
END //
DELIMITER ;
IF STATEMENT
 CREATE PROCEDURE
GetProductsInStockBasedOnQuantitityLevel
(IN p_operator VARCHAR(255), IN p_quantityInStock
INT)
The ooperator > or < The number in stock
THE IF STATEMENT
IF p_operator = "<" THEN
select * from products WHERE quantityInStock <
p_quantityInStock;
ELSEIF p_operator = ">" THEN
select * from products WHERE quantityInStock >
p_quantityInStock;
END IF;
LOOPS
 While
 Repeat
 Loop
Repeats a set of commands until some condition
is met
Iteration: one execution of the body of a loop
If a condition is never met, we will have an infinite
loop
WHILE LOOP
WHILE expression DO
Statements
END WHILE
The expression must evaluate
to true or false
while loop is known as a pretest loop
Tests condition before performing an iteration
Will never execute if condition is false to start with
Requires performing some steps prior to the loop
INFINITE LOOPS
 Loops must contain within themselves a way to
terminate
ď‚— Something inside a while loop must eventually make
the condition false
 Infinite loop: loop that does not have a way of
stopping
ď‚— Repeats until program is interrupted
ď‚— Occurs when programmer forgets to include
stopping code in the loop
WHILE LOOP
DELIMITER //
CREATE PROCEDURE WhileLoopProc()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 1;
SET str = '';
WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;
SELECT str;
END//
DELIMITER ;
WHILE LOOP
 Creating Variables
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 1;
SET str = '';
WHILE LOOP
WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;

Stored procedures

  • 1.
  • 2.
    STORED PROCEDURE  Aprocedure is a subroutine (like a subprogram) in a regular scripting language, stored in a database  In the case of MySQL, procedures are written in MySQL and stored in the MySQL database/server  A MySQL procedure has a name, a parameter list, and SQL statement(s)
  • 3.
    STORED PROCEDURES  Databaseprogram modules that are stored and executed by the DBMS at the server DELIMITER // CREATE PROCEDURE GetAllProducts() BEGIN SELECT * FROM products; END // DELIMITER ;
  • 4.
    WHY STORED PROCEDURES Reduces Duplication of effort and improves software modularity  Multiple applications can use the stored procedure vs. the SQL statements being stored in the application language (PHP) Reduces communication and data transfer cost between client and server (in certain situations)  Instead of sending multiple lengthy SQL statements, the application only has to send the name and parameters of the Stored Procedure Can be more secure than SQL statements  Permission can be granted to certain stored procedures without granting access to database tables
  • 5.
    DISADVANTAGES OF STOREDPROCEDURES  Difficult to debug  MySQL does not provide ways for debugging stored procedures Many stored procedures can increase memory use  The more stored procedures you use, the more memory is used Can be difficult to maintain and develop stored procedures  Another programming language to learn
  • 6.
    CREATING STORED PROCEDURES DELIMITER// CREATE PROCEDURE NAME BEGIN SQL STATEMENT END // DELIMITER ; DELIMITER // CREATE PROCEDURE GetAllProducts() BEGIN SELECT * FROM products; END // DELIMITER ;
  • 7.
  • 9.
    TYPES OF MYSQLPROCEDURES: 1. Procedure with no parameters: 2. Procedure with IN parameter: 3. Procedure with OUT parameter: 4. Procedure with IN-OUT parameter:
  • 10.
    1. PROCEDURE WITHNO PARAMETERS: A procedure without parameters does not take any input or casts an output indirectly. It is simply called with its procedure name followed by () (without any parameters). It is used for simple queries.
  • 11.
    EXAMPLE PROCEDURE WITHNO PARAMETERS delimiter // create procedure display_book() -> begin -> select *from book; -> end // call display_book(); //
  • 12.
    PARAMETERS  There maybe times where you want to pass information to the stored procedures  Getting user input from a form and using that input in a SQL statement
  • 13.
    PROCEDURE WITH INPARAMETER:  An IN parameter is used to take a parameter as input such as an attribute  When we define an IN parameter in a procedure, the calling program has to pass an argument to the stored procedure  The value of an IN parameter is protected
  • 14.
    EXAMPLE PROCEDURE WITHIN PARAMETER: delimiter // create procedure update_price (IN temp_ISBN varchar(10), IN new_price integer) -> begin -> update book set price=new_price -> where ISBN=temp_ISBN; -> end; // call update_price(001, 600); //
  • 15.
    PROCEDURE WITH OUTPARAMETER:  An OUT parameter is used to pass a parameter as output or display like the select operator, but implicitly (through a set value)  The value of an OUT parameter can be changed inside the procedure and its new value is passed back to the calling program  A procedure cannot access the initial value of the OUT parameter when it starts.
  • 16.
    EXAMPLE ON PROCEDUREWITH OUT PARAMETER: delimiter // create procedure disp_max(OUT highestprice integer) -> begin -> select max(price) into highestprice from book; -> end; // call disp_max(@M); // select @M;
  • 17.
    PROCEDURE WITH IN-OUTPARAMETER:  An INOUT parameter is a combination of IN and OUT parameters  It means that the calling program may pass the argument, and the stored procedure can modify the INOUT parameter and pass the new value back to the calling program.
  • 18.
    EXAMPLE ON PROCEDUREWITH IN-OUT PARAMETER
  • 19.
    ARGUMENTS AND PARAMETERS DELIMITER// CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(25 BEGIN SELECT * FROM offices WHERE country = countryName; END // DELIMITER ; Defining Calling CALL GetOfficeByCountry('USA') The values being copied from the calling stored procedure are calling arguments. The variables being copied into are called parameters.
  • 20.
    OUT PARAMETER DELIMITER // CREATEPROCEDURE CountOrderByStatus(IN orderStatus VARCHAR(25), OUT total INT) BEGIN SELECT count(orderNumber) INTO total FROM orders WHERE status = orderStatus; END// DELIMITER ; Defining Calling CALL CountOrderByStatus('Shipped',@total); SELECT @total; The out parameter is used outside of the stored procedure.
  • 21.
    VARIABLES  A variableis a name that refers to a value A name that represents a value stored in the computer memory C program int name=“Amit”; int age=25  MySQL DECLARE name VARCHAR(255) DECLARE age INT
  • 22.
    DELIMITER // CREATE PROCEDUREdeclare2(IN value int,IN name varchar(20)) BEGIN DECLARE x INT; DECLARE str VARCHAR(255); SET x = value; SET str = name; SELECT x,str; END// DELIMITER ;
  • 23.
  • 24.
    THE “IF” STATEMENT MysqlSyntax IF if_expression THEN commands [ELSEIF elseif_expression THEN commands] [ELSE commands] END IF; First line is known as the IF clause Includes the keyword IF followed by condition followed by the keyword THEN  When the IFstatement executes, the condition is tested, and if it is true the block statements are executed. Otherwise, block statements are skipped
  • 25.
  • 26.
    IF STATEMENT DELIMITER // CREATEPROCEDURE GetProductsInStockBasedOnQuantitityLevel(IN p_operator VARCHAR(255), IN p_quantityInStock INT) BEGIN IF p_operator = "<" THEN select * from products WHERE quantityInStock < p_quantityInStock; ELSEIF p_operator = ">" THEN select * from products WHERE quantityInStock > p_quantityInStock; END IF; END // DELIMITER ;
  • 27.
    IF STATEMENT  CREATEPROCEDURE GetProductsInStockBasedOnQuantitityLevel (IN p_operator VARCHAR(255), IN p_quantityInStock INT) The ooperator > or < The number in stock
  • 28.
    THE IF STATEMENT IFp_operator = "<" THEN select * from products WHERE quantityInStock < p_quantityInStock; ELSEIF p_operator = ">" THEN select * from products WHERE quantityInStock > p_quantityInStock; END IF;
  • 29.
    LOOPS  While  Repeat Loop Repeats a set of commands until some condition is met Iteration: one execution of the body of a loop If a condition is never met, we will have an infinite loop
  • 30.
    WHILE LOOP WHILE expressionDO Statements END WHILE The expression must evaluate to true or false while loop is known as a pretest loop Tests condition before performing an iteration Will never execute if condition is false to start with Requires performing some steps prior to the loop
  • 31.
    INFINITE LOOPS  Loopsmust contain within themselves a way to terminate  Something inside a while loop must eventually make the condition false  Infinite loop: loop that does not have a way of stopping  Repeats until program is interrupted  Occurs when programmer forgets to include stopping code in the loop
  • 32.
    WHILE LOOP DELIMITER // CREATEPROCEDURE WhileLoopProc() BEGIN DECLARE x INT; DECLARE str VARCHAR(255); SET x = 1; SET str = ''; WHILE x <= 5 DO SET str = CONCAT(str,x,','); SET x = x + 1; END WHILE; SELECT str; END// DELIMITER ;
  • 33.
    WHILE LOOP  CreatingVariables DECLARE x INT; DECLARE str VARCHAR(255); SET x = 1; SET str = '';
  • 34.
    WHILE LOOP WHILE x<= 5 DO SET str = CONCAT(str,x,','); SET x = x + 1; END WHILE;