Chapter 9
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
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
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)
Triggers
Routines that execute in response to a database event (INSERT,
UPDATE, or DELETE)
4
Figure 8-10 Triggers contrasted with stored procedures
5
Figure 8-11 Simplified trigger syntax, SQL:200n
6
Basic
Basic PL/SQL
PL/SQL
DECLARE
[local_variable_declarations]
BEGIN
program body;
END ;
Basic
Basic PL/SQL
PL/SQL
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);
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
· Simple Variable
temp_name varchar2(30);
temp_salary staff.salary%type;
· Cursor Variable
· IF-THEN-ELSE
· WHILE - LOOP
· Cursor Fetching:
· 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;
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).
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
END LOOP;
END;
PL/SQL
PL/SQL Basics:
Basics: LOOPS
LOOPS
WHILE Loops
DECLARE
v_Counter INTEGER:=1;
BEGIN
END LOOP;
END;
Stored
Stored Procedures
Procedures
[local_variable_declarations]
BEGIN
procedure_body;
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
COMMIT;
END INCREASE_SALARY;
Stored
Stored Procedures:
Procedures: Example
Example 22
BEGIN
-- Insert a new row in the students table. Use
-- 0 for total_current_credits.
END AddNewStudent;
Stored
Stored Procedures:
Procedures: Example
Example 33 -- Exception
Exception
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. */
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
CURSOR <cursor_name> IS
SELECT statement;
Stored
Stored Procedures:
Procedures: Cursor
Cursor
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*/
dbms_output.put_line
(v_cursrec.ename||' '|| v_cursrec.sal);
END LOOP;
END salcheck;
Stored
Stored Procedures:
Procedures: Cursor
Cursor
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.*/
END LOOP;
END CheckStudentCompletion;
Stored
Stored
Stored Procedures:
Stored Procedures:
Procedures: Executing
Procedures: Execute
Execute and
Executing and Drop
Drop
Syntax
BEGIN
function_body;
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;
END ClassInfo;
Stored Function
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;
END;
SELECT *
FROM user_objects
WHERE OBJECT_TYPE = 'PROCEDURE';
SELECT *
FROM user_source
WHERE NAME= 'AddNewStudent';
Stored Procedures and Functions:
Advantages
– 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