0% found this document useful (0 votes)
30 views44 pages

Chapter 9

Uploaded by

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

Chapter 9

Uploaded by

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

CHAPTER 9:

STORED PROCEDURES
AND FUNCTION

Advanced PL/SQL 1
SQL:1999 AND SQL:200N
ENHANCEMENTS/EXTENSIONS
 User-defined data types (UDT)
 Subclasses of standard types or an object type

 Analytical functions (for OLAP)


 CEILING, FLOOR, SQRT, RANK, DENSE_RANK
 WINDOW–improved numerical analysis capabilities

 New Data Types


 BIGINT, MULTISET (collection), XML

 CREATE TABLE LIKE–create a new table similar to an


existing one
 MERGE

2
SQL:1999 AND SQL:200N
ENHANCEMENTS/EXTENSIONS
(CONT.)
 Persistent Stored Modules (SQL/PSM)
 Capability to create and drop code modules
 New statements:
 CASE, IF, LOOP, FOR, WHILE, etc.
 Makes SQL into a procedural language

 Oracle has propriety version called PL/SQL, and


Microsoft SQL Server has Transact/SQL

3
ROUTINES AND TRIGGERS
 Routines
 Program modules that execute on demand
 Functions–routines that must return values and take input
parameters (we call function using select)

 Procedures–routines that may or may not return values and can


take input or output parameters (we call procedure using Exec/
Execute command)

 Triggers
 Routines that execute in response to a database event (INSERT,
UPDATE, or DELETE)

4
Figure 8-10 Triggers contrasted with stored procedures

Procedures are called explicitly

Triggers are event-driven


Source: adapted from Mullins, 1995.

5
Figure 8-11 Simplified trigger syntax, SQL:200n

Figure 8-12 Create routine syntax, SQL:200n

6
Basic
Basic PL/SQL
PL/SQL

• Before we start looking at some examples on stored


procedures, we will go through basic PL/SQL syntax in the
following few slides.
• A stored procedure in Oracle basically contains a set of
SQL statements grouped together with PL/SQL syntax.
• PL/SQL structure:

DECLARE
[local_variable_declarations]

BEGIN
program body;

END ;
Basic
Basic PL/SQL
PL/SQL

• Whenever you want to display an output to the screen for


debugging purpose, you can insert the following line in
your PL/SQL block:
DBMS_OUTPUT.PUT_LINE(‘Data inserted …’);

Make sure you turn on the server output in SQL Plus by


typing:
SQL> SET SERVEROUTPUT ON;
PL/SQL
PL/SQL Basic:
Basic: Variable/Parameter
Variable/Parameter Declaration
Declaration

TYPE
In many cases, a PL/SQL variable will be used to manipulate data stored in a
database table. In this case, the variable should have the same type as the table
column. For example the first_name column of the STUDENT table has type
VARCHAR2(20). Based on this we can declare a variable as follows;

DECLARE
V_FirstName VARCHAR2(20);

But what if the table definition of first_name changed? For example to


VARCHAR2(25)! Therefore to declare a variable of the same data type of that
the table definition

DECLARE
V_Firstname student.first_name%type

Syntax
<variable name> <table name>.<column name>%type
PL/SQL
PL/SQL Basic:
Basic: Local
Local Variable
Variable Declarations
Declarations

· Local variable declarations can be divided into two


types:

· Simple Variable

temp_name varchar2(30);
temp_salary staff.salary%type;

· Cursor Variable

Cursor <cursor name> IS


Select …
From …
Where … ;
PL/SQL
PL/SQL Basic:
Basic: Program
Program Body
Body

· In the program body section, several different structure


can be used, including:

· IF-THEN-ELSE
· WHILE - LOOP
· Cursor Fetching:

for <variable name> in <cursor name> loop


………
end loop;

· Insert statement
· Update statement
· Delete statement
PL/SQL
PL/SQL Basic:
Basic: Simple
Simple Assignment
Assignment

Example

DECLARE
V_string1 VARCHAR2(10);
V_string2 VARCHAR2(15);
V_numeric NUMBER;
BEGIN
V_string1:='Hello';
V_string2:= V_string1;
V_numeric:=12;
DBMS_OUTPUT.PUT_LINE(' My first PL/SQL '||V_string2);
END;
PL/SQL
PL/SQL Basic:
Basic: IF-THEN-ELSE
IF-THEN-ELSE

DECLARE
v_NumberSeats rooms.number_seats%TYPE;
v_Comment VARCHAR2(35);
BEGIN
-- Retrieve the number of seats in the room identified
-- by ID 99999. Store the result in v_NumberSeats.

SELECT number_seats
INTO v_NumberSeats INTO
FROM rooms Stores values of select
WHERE room_id = 9;
statement into variables
IF v_NumberSeats < 50 THEN
v_Comment := 'Fairly small';
ELSE IF v_NumberSeats < 100 THEN
v_Comment := 'A little bigger';
ELSE
v_Comment := 'Lots of room';
END IF;
END IF;

INSERT INTO temp_table


VALUES (9, v_Comment);
END;
PL/SQL
PL/SQL Basic:
Basic: IF-THEN-ELSE
IF-THEN-ELSE (ctd.)
(ctd.)

NOTES:
Before you can compile the previous PL/SQL statements,
you need to make sure that you have the rooms table, and
the temp_table in your database with all the necessary
attributes. Make sure you also have a room_id=99999 in your database (check the
correspondence number_seats of this particular room).

On successful compilation, Oracle will display


‘PL/SQL procedure successfully completed’

Check your temp_table and see whether it has the correct data in it.
PL/SQL
PL/SQL Basic:
Basic: LOOPS
LOOPS

Simple Loops

DECLARE
v_Counter INTEGER := 1;
BEGIN
LOOP
-- Insert a row into temp_table with the
-- current value of the
-- loop counter

INSERT INTO temp_table


VALUES (v_Counter, 'Loop index');
v_Counter := v_Counter + 1;

-- Exit condition - when the loop counter > 50 we will


-- break out of the loop

IF v_Counter > 50 THEN


EXIT;
END IF;

END LOOP;
END;
PL/SQL
PL/SQL Basics:
Basics: LOOPS
LOOPS

WHILE Loops

DECLARE
v_Counter INTEGER:=1;

BEGIN

WHILE v_Counter <= 50 LOOP

INSERT INTO temp_table


VALUES (v_Counter, 'Loop index');
v_Counter := v_Counter + 1;

END LOOP;

END;
Stored
Stored Procedures
Procedures

A stored procedure is a self-contained schema object (database’s


metadata ) that logically groups a set of SQL statements written
in respective database and trigger language (eg. PL/SQL  in
ORACLE) to perform a specific task.

The concept of procedure in PL/SQL is the same as that in other


high level programming languages, when it is called, it may
accept parameters, perform some operations, and return to the
caller.
To make your PL/SQL programs persistent (i.e. stored in the
database), you need to create a stored procedure and encapsulate
your PL/SQL statements into the stored procedure.
Stored
Stored Procedures:
Procedures: Syntax
Syntax

CREATE [OR REPLACE] PROCEDURE <procedure name>


[(parameter [{IN | OUT | IN OUT}] type,....,
parameter [{IN | OUT | IN OUT}] type)] AS

[local_variable_declarations]

BEGIN

procedure_body;

END <procedure name>;


Stored
Stored Procedures:
Procedures: Syntax
Syntax

Mode {IN | OUT | IN OUT} description

IN (DEFAULT)
The value of the actual parameter is passed into the procedure when the procedure
is invoked. Inside the procedure, the formal parameter is considered read-only; it
cannot be changed. Then the procedure finishes and control returns to the calling
environment, the actual parameter is not changed.

OUT
Any value the actual parameter has when the procedure is called is ignored. Inside
the procedure, the formal parameter is considered write-only; it can only be
assigned to and cannot be read from. When the procedure finishes and control
returns to the calling environment, the contents of the formal parameter are
assigned to the actual parameter.
IN OUT
This mode is a combination of IN and OUT. The value of the actual parameter is
passed into the procedure when the procedure is invoked. Inside the procedure, the
formal parameter can be read from and written to. When the procedure finishes
and control returns to the calling environment, the contents of the formal
parameter are assigned to the actual parameter
Stored
Stored Procedures:
Procedures: Example
Example 11

CREATE OR REPLACE PROCEDURE INCREASE_SALARY(E IN NUMBER,


I IN NUMBER, S OUT NUMBER)AS
BEGIN

--Procedure to update the salary of an employee

UPDATE EMP SET SAL= SAL + I


WHERE EMPNO= E;

COMMIT;

SELECT SAL INTO S FROM EMP WHERE EMPNO=E;

END INCREASE_SALARY;
Stored
Stored Procedures:
Procedures: Example
Example 22

CREATE OR REPLACE PROCEDURE AddNewStudent (


p_ID students.id%TYPE,
p_FirstName students.first_name%TYPE,
p_LastName students.last_name%TYPE,
p_Major students.major%TYPE) AS

BEGIN
-- Insert a new row in the students table. Use
-- 0 for total_current_credits.

INSERT INTO students (ID, first_name, last_name,


major, total_current_credits)
VALUES (p_ID, p_FirstName, p_LastName,
p_Major, 0);

END AddNewStudent;
Stored
Stored Procedures:
Procedures: Example
Example 33 -- Exception
Exception

CREATE PROCEDURE credit_account


(acct NUMBER, credit NUMBER) AS

old_balance NUMBER;
new_balance NUMBER;
BEGIN
/* This procedure accepts two arguments: an account number
and an amount of money to credit to the specified account.
If the specified account does not exist, a new account is
created. */

SELECT balance INTO old_balance FOR UPDATE OF


FROM accounts Locks the row with the
WHERE acct_id = acct
result set.
FOR UPDATE OF balance;
new_balance := old_balance + credit; ‘OF balance’ specifies you
will update the balance
UPDATE accounts SET balance = new_balance
WHERE acct_id = acct; column

EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO accounts (acct_id, balance)
VALUES (acct, credit);
END credit_account;
Stored
Stored Procedures:
Procedures: Cursor
Cursor

In order to process a SQL statement, Oracle will allocate an area of memory known as the
context area. The context area contains information necessary to complete the processing,
including the number of rows processed by the statement, a pointer to the parsed
representation of the statement, and in the case of a query, the active set, which is the set of
rows returned by the query.

A cursor is a handle, or pointer, to the context area. Through the cursor, a PL/SQL program
can control the context area and what happens to it as the statement is processed. The
following PL/SQL block illustrates a cursor fetch loop, in which multiple rows of data are
returned from a query.
Stored
Stored Procedures:
Procedures: Cursor
Cursor

SYNTAX of CURSOR Declaration

CURSOR <cursor_name> IS
SELECT statement;
Stored
Stored Procedures:
Procedures: Cursor
Cursor

CREATE OR REPLACE PROCEDURE salcheck(


MinSalary number) AS

CURSOR executive IS
SELECT ename, sal
FROM Emp
WHERE sal > MinSalary;

BEGIN
/*Procedure to display names and salaries of all employees
who have a salary greater than MinSalary variable passed to it*/

FOR v_cursrec IN executive LOOP

dbms_output.put_line
(v_cursrec.ename||' '|| v_cursrec.sal);
END LOOP;

END salcheck;
Stored
Stored Procedures:
Procedures: Cursor
Cursor

CREATE OR REPLACE PROCEDURE CheckStudentCompletion AS


CURSOR c_student IS
SELECT id, last_name, total_current_credits
FROM students;

BEGIN
/*Procedure to copy names of all students who are about
to graduate into the temp_table. Condition for ‘about to
graduate’ is that they have completed at least 300
credits.*/

FOR v_StudentRecord IN c_student LOOP

IF (v_StudentRecord.total_current_credit > 300) THEN


INSERT INTO temp_table (desc_col) VALUES
(v_StudentRecord.id ||' '||v_StudentRecord.last_name ||
' final semester student!');
END IF;

END LOOP;

END CheckStudentCompletion;
Stored
Stored
Stored Procedures:
Stored Procedures:
Procedures: Executing
Procedures: Execute
Execute and
Executing and Drop
Drop

To display the results of the previous stored procedure we can do


the following:

EXECUTE procedure name [param1,param2..];

To delete the stored procedure we can do the following:

DROP PROCEDURE procedure name;


Stored Function

Functions–routines that must return values and take input parameters


(we call function using select)

Syntax

CREATE [OR REPLACE] FUNCTION <function name>


[(parameter type,....,
RETURN <return type> IS
[local_variable_declarations]

BEGIN

function_body;

END <function name>;


Stored Function
A function is very similar to a procedure, however:
- a procedure call is a PL/SQL statement by itself
- a function call is called as part of an expression. The RETURN statement is used to return
control to the calling environment with a value.

CREATE OR REPLACE FUNCTION ClassInfo (p_Course classes.course%TYPE)

/* Returns 'Full' if the class is completely full,


'Some Room' if the class is over 80% full,
'More Room' if the class is over 60% full,
'Lots of Room' if the class is less than 60% full, and
'Empty' if there are no students registered. */

RETURN VARCHAR2 IS

v_CurrentStudents NUMBER;
v_MaxStudents NUMBER;
v_PercentFull NUMBER;

BEGIN
<< Function Body is in the NEXT SLIDE >>
END ClassInfo;
Stored Function

BEGIN
-- Get the current and maximum students
for the -- requested course.
SELECT current_students, max_students
INTO v_CurrentStudents, v_MaxStudents
FROM classes
WHERE course = p_Course;

-- Calculate the current percentage.


v_PercentFull := v_CurrentStudents / v_MaxStudents * 100;

IF v_PercentFull = 100 THEN


RETURN 'Full';
ELSIF v_PercentFull > 80 THEN
RETURN 'Some Room';
ELSIF v_PercentFull > 60 THEN
RETURN 'More Room';
ELSIF v_PercentFull > 0 THEN
RETURN 'Lots of Room';
ELSE
RETURN 'Empty';
END IF;

END ClassInfo;
Stored Function

To execute the previous function, we need to use an SQL statement:

SELECT course, classinfo(course)


FROM classes;
Stored Function

Calling a standalone function:


This function returns the total number of CUSTOMERS in the
customers table.

Example will work on the Customers data:


Stored Function

CREATE OR REPLACE FUNCTION TotalCustomers

RETURN number IS
total number(2) := 0;

BEGIN

SELECT count(*)
INTO total
FROM customers;

RETURN total;

END;
Stored Function

DECLARE
c number(2);

BEGIN

c := TotalCustomers;

dbms_output.put_line('Total number of Customers is: '||c);

END;

Output of above code:


Stored
Stored Procedures
Procedures and
and Functions
Functions

You should design stored procedures or function so that they


have the following properties:

– Define procedures or functions to complete a single, focused


task.

– DO NOT define procedures or functions that duplicate the


functionality already provided by the database language.
Stored Procedures and Functions

To list all procedures in the user schema

SELECT *
FROM user_objects
WHERE OBJECT_TYPE = 'PROCEDURE';

To list the code of a procedures in the user schema

SELECT *
FROM user_source
WHERE NAME= 'AddNewStudent';
Stored Procedures and Functions:
Advantages

Advantages of using stored procedures

– Security

– Performance

– Memory allocation

– Modular Design

– Streamlined Maintenance

– Integrity
Stored Procedures and Functions:
Advantages

Security:
Stored procedures can help enforce data security.
– Limit direct access to tables via defined roles in
the database
– Provide an “interface” to the underlying data
structure so that all implementation and even the
data itself is shielded.
Stored Procedures and Functions:
Advantages

Performance:
It reduces the amount of information that must be
sent over network compared to issuing individual
SQL statements. The information is sent only
once and thereafter invoked when it is used.
Stored Procedures and Functions:
Advantages

Memory Allocation:
Shared memory - only a single copy of the stored
procedures needs to be loaded into memory for
execution by multiple users.
Stored Procedures and Functions:
Advantages

Modular Design:
Stored procedures can be shared by applications
that access the same database, eliminating
duplicate code, coding errors and reducing the
size of applications. This will increase the overall
productivity.
Stored Procedures and Functions:
Advantages

Streamlined maintenance:
When a procedure is updated, the changes are
automatically reflected in all applications that use
it without the need to re-compile and re-link
them. They are compiled and optimised only once
for each client.
Stored Procedures and Functions:
Advantages

Integrity:
Developing all applications around a common
group of procedures helps to reduce coding errors
and provide consistency of data access across all
applications.
Next Lecture …

Triggers

You might also like