L 23 Introduction To PLSQL and Stored Procedures

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Database Systems

and Web
(15B11CI312)
Database Systems and Web

Lecture 24: Introduction to PL/SQL, Stored Procedures


Contents to be covered
▪ PL/SQL
▪ PL/SQL Features
▪ Stored Program
▪ Stored Procedures
▪ MySQL Delimiter
▪ Create and Execute Procedure
▪ Stored Procedure Parameters
▪ Drop Procedure
▪ Condition Statement
▪ Case Statement
▪ Loops
▪ Error Handling
PL/SQL
PL/SQL

Procedural Language Extension to SQL


PL/SQL
❑Combination of SQL along with the procedural features of programming
languages.
❑Developed by Oracle Corporation in the early 90's to enhance the capabilities of
SQL.
❑One of three key programming languages embedded in the Oracle Database,
along with SQL itself and Java.
❑PL/SQL instructs the compiler 'what to do' through SQL and 'how to do'
through its procedural way.
PL/SQL
❑Completely portable, high-performance transaction-processing language.

❑ Provides a built-in, interpreted and OS independent programming environment.

❑ Directly called from the command-line SQL*Plus interface.

❑ Direct call can also be made from external programming language calls to database.

❑ General syntax is based on that of ADA and Pascal programming language.

❑Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2.
PL/SQL Features
❑ Tightly integrated with SQL.

❑ Offers extensive error checking.

❑ Offers numerous data types.

❑ Offers a variety of programming structures.

❑ Supports structured programming through functions and procedures.


❑ Supports object-oriented programming.

❑ Supports the development of web applications and server pages.


PL/SQL Blocks
PL/SQL code is built of Blocks, with a unique structure.
There are two types of blocks in PL/SQL:
1. Anonymous Blocks: have no name (like scripts)
◦ can be written and executed immediately.
2. Named Blocks:
◦ Procedures
◦ Functions
◦ To use pl/sql in MySql, need to use the Named blocks.
Stored Programs
❑ A database stored program is also known as stored module or a stored routine.

❑ Stored program is a computer program or a set of instructions associated with a name which are
stored within, and executes within, the database server.

❑Stored programs are categorised mainly in three types:


❖ Stored procedures
❖ Stored functions
❖ Triggers
Stored Procedures
❑ The most common type of stored program.

❑ Generic program unit that is executed on request.

❑ Stored procedures are portable.

❑ A procedure has a name, a parameter list, and SQL statement(s)

❑ Accepts multiple input and output parameters.


SQL Query
SELECT
customerName,
city,
state, If you want to store this query to execute later
postalCode, or to use several times.
country ◦ One way is to store it on database server as
FROM a stored procedure.
customers
ORDER BY customerName;
Stored Procedure
The procedure was created and stored and
DELIMITER $$ can now be executed by any user. To
CREATE PROCEDURE GetCustomers() execute the procedure a user must “call”
BEGIN the procedure:
SELECT
customerName, CALL GetCustomers();
city,
state,
postalCode,
country SQL query and this stored procedure will
FROM customers return the same result.
ORDER BY customerName;
END$$
DELIMITER ;
MySQL Delimiter
❑ MYSQL program uses the (;) delimiter to separate statements and executes each statement
separately.
❑ A stored procedure consists of multiple statements separated by a semicolon (;).
❑ If MySQL client program is used to define a stored procedure that contains semicolon
characters, the MySQL client program will not treat the whole stored procedure as a single
statement, but many statements.
❑ Therefore, We need to redefine the delimiter temporarily so that the whole stored procedure is
passed to the server as a single statement.
To change the default MySQL delimiter:

DELIMITER delimiter_character
MySQL Delimiter
SELECT * FROM products; DELIMITER // To change the
SELECT * FROM customers // delimiter to //
SELECT * FROM customers; SELECT * FROM products //
DELIMITER ; To change the
delimiter back to
semicolon
Note: Output of both the programs will be same
MySQL Delimiter
DELIMITER $$ ❑ Change the default delimiter to $$
CREATE PROCEDURE sp_name()
BEGIN ❑ Use (;) in the body of the stored procedure
- - statements and $$ after the END keyword to end the stored
END $$ procedure.
DELIMITER ;
❑ Change the default delimiter back to a
semicolon (;)
Create and Execute a procedure
❑ A procedure can return one or more than one value through parameters or may not return at all.

❑ The procedure can be used in SQL queries.

CREATE PROCEDURE procedure_name ( [IN | OUT | INOUT] parameter_name


datatype[(length)]
BEGIN
Declaration_section
Executable_section
END;
CALL stored_procedure_name(argument_list);
Stored Procedure Parameters
❑ IN: This is the default (if not specified). It is passed to the routine and can be changed inside the
routine, but remains unchanged outside.

❑ OUT: No value is supplied to the routine (it is assumed to be NULL), but it can be modified
inside the routine, and it is available outside the routine. “ @”

❑ INOUT: The characteristics of both IN and OUT parameters. A value can be passed to the
routine, modified there as well as passed back again.
Example
Create and call a procedure to extract the details of products from Products table.

DELIMITER //
CREATE PROCEDURE GetAllProducts()
CALL GetAllProducts();
BEGIN
SELECT * FROM Products;
END //
DELIMITER ;
Drop Procedure
DROP PROCEDURE [IF EXISTS] stored_procedure_name;

❑ While dropping a procedure that does not exist by using the IF EXISTS option, MySQL issues a
warning .

❑ Otherwise, MySQL issues an error.

To Drop “GetAllProducts()” procedure:

DROP PROCEDURE [IF EXISTS] GetAllProducts();


Declaring variables
DECLARE variable_name datatype(size) [DEFAULT default_value];

Example: Two integer variables x and y with default values to zero.

DECLARE x, y INT
DEFAULT 0;
Assigning variables

SET variable_name = value;

Example:

DECLARE total INT DEFAULT 0;


SET total = 10;

There is one more statement “SELECT INTO” to assign the result of a query to a variable.

DECLARE productCount INT DEFAULT 0;

SELECT COUNT(*) ,A,B


INTO productCount,A1,B1
FROM products;
Altering a Stored Procedure
Two step approach:
❑ DROP PROCEDURE
❑ CREATE PROCEDURE
IF-THEN-ELSEIF-ELSE Statements
IF expression THEN
statements that execute if the expression is TRUE
ELSEIF expression THEN
statements that execute if expression1 is TRUE
ELSE
statements that execute if all the preceding expressions
are FALSE or NULL
END IF;
IF-THEN-ELSEIF-ELSE Statements
DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(
IN p_CustomerNumber INT,
OUT level VARCHAR(20))
BEGIN
DECLARE credit DECIMAL DEFAULT 0;
CALL GetCustomerLevel(447, @
SELECT creditLimit level);
INTO credit
FROM customers
SELECT @ level;
WHERE customerNumber = p_CustomerNumber;

IF credit > 50000 THEN Output:


SET level = 'PLATINUM';
ELSEIF credit <= 50000 AND credit > 10000 THEN
SET level = 'GOLD';
ELSE
SET level = 'SILVER';
END IF;
END $$
DELIMITER ;
Case Statement
CASE case_value
WHEN value THEN
statements
[WHEN value THEN
statements ]
[ELSE
statements]
END CASE;
Case Statement
DELIMITER $$
CREATE PROCEDURE GetCustomerShipping(
IN p_CustomerNUmber INT,
OUT Shipping VARCHAR(50) )
BEGIN
DECLARE customerCountry VARCHAR(100);
CALL GetCustomerShipping(112,@shipping);
SELECT country
INTO customerCountry SELECT @shipping;
FROM customers
WHERE customerNumber = p_CustomerNUmber;

CASE customerCountry Output:


WHEN 'USA' THEN
SET Shipping = '2-day Shipping'; WHEN
'Canada' THEN
SET Shipping = '3-day Shipping'; ELSE
SET Shipping = '5-day Shipping'; END CASE;
END$$
DELIMITER ;
Loops
❑ LOOP – Executes a list of statements repeatedly based on a condition.

❑ WHILE Loop– Executes a loop as long as a condition is true.

❑ REPEAT Loop– Executes a loop until a search condition is true.

❑ LEAVE statement– Exit a loop immediately.


Create a stored procedure that constructs a string from the
even numbers between 1 to 10
DELIMITER $$
CREATE PROCEDURE LoopExample()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);

SET x = 1; CALL LoopExample();


SET str = ‘ ,’;

loop_label: LOOP
IF x > 10 THEN
LEAVE loop_label;
END IF;

SET x = x + 1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str,x,',');
END IF;
END LOOP;
SELECT str;
END$$
Create a stored procedure that constructs a string from the
even numbers between 1 to 10
DELIMITER $$
CREATE PROCEDURE WhileLoopExample()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);

SET x = 1; CALL WhileLoopExample();


SET str = ‘ ';

WHILE x<=10 DO
IF (x mod 2) THEN
SET x = x + 1;
ELSE
SET str = CONCAT(str,x,',');
SET x = x + 1;
END IF;
END WHILE;
SELECT str;
END$$
DELIMITER ;
Create a stored procedure that constructs a string from the
even numbers between 1 to 10
DELIMITER $$
CREATE PROCEDURE RepeatLoopExample()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);

SET x = 1; CALL RepeatLoopExample();


SET str = ‘ ';

REPEAT
IF (x mod 2) THEN
SET x = x + 1;
ELSE
SET str = CONCAT(str,x,',');
SET x = x + 1;
END IF;
UNTILL x<11
END REPEAT;
SELECT str;
END$$
DELIMITER ;
Error Handling in Stored Procedures

DECLARE action HANDLER FOR condition_value statement;

There are two options as action:

❑ CONTINUE : The execution of the enclosing code block ( BEGIN … END ) continues.

❑ EXIT : The execution of the enclosing code block, where the handler is declared, terminates.
References
1. https://www.oracletutorial.com/plsql-tutorial
2. https://www.mysqltutorial.org/
3. https://www.javatpoint.com/mysql-procedure
4. https://www.w3resource.com/mysql/mysql-procedure.php
5. Murach's MySQL, 3rd edition by Joel Murach.

You might also like