Sie sind auf Seite 1von 37

1

OVERVIEW
2
About PL/SQL

PL/SQL is the procedural extension to SQL with
design features of programming languages.

Data manipulation and query statements of SQL
are included within procedural units of code.

Benefits of PL/SQL
Integration.
Improved Performance.
Portability
Modularity of Program development.

3
4
Anonymous Block
The Declaration section (optional).
The Execution section (mandatory).
The Exception Handling section (optional).
[ DECLARE ...
optional declaration statements ... ]
variables, cursors, user-defined exceptions.
BEGIN ...
executable statements ...
SQL statements
PL/SQL statements
[ EXCEPTION ...
optional exception handler statements ... ]
Actions to perform when errors occurs
END;
5
Anonymous Block contd.
Executing Statements and PL/SQL Blocks
DECLARE
v_variable VARCHAR2(5);
BEGIN
SELECT column_name INTO v_variable FROM table_name;
EXCEPTION
WHEN exception_name THEN
. . . .
END;

When PL/SQL Block is executed successfully, without unhandled
errors or compile errors, the message output should be as
Follows
PL/SQL procedure successfully completed


6
Types of Variables
PL/SQL variables
Scalar
Scalar data types which hold a single value.
CHAR,VARCHAR2,NUMBER etc.
Composite
Composite data types, such as records, allow groups of fields to be
defined and manipulated in PL/SQL blocks
Reference
Reference data type hold values, called pointers, that designate
other program items.
LOB
LOB data types hold values, called locators, that specify the
location of large objects that are stored out of line.

Non-PL/SQL variables : Bind or host variables
Bind variables can be used to pass run time values out of the PL/SQL
block back to the SQL environment.
7
Syntax

Identifier [constant] datatype [Not NULL] [: = | DEFAULT
expr ];

Guidelines
Follow naming Conventions
Initialize variables designated as NOT NULL and
CONSTANT.
Declare one identifier per line.
Initialize identifiers by using the assignment operator
(:=) or the DEFUALT reserved word


Syntax and Guidelines for Declaring PL/SQL
variables
Composite Data Type
Must contain one or more components of any Scalar, Record or
INDEX BY table data type called fields.
Are convenient for fetching a row of data from table for processing.

Example
Type emp_record_type is RECORD
( last_name varchar2(25);
job_id number(10) );
emp_record emp_record_type;



8
The %Type and %Rowtype
attribute
% Type Attribute
Declare a variable according to
- A database column definition
- Another previously declared variables

Syntax
Identifier Table.column%Type;
Examples:
v_name employees.last_name%TYPE;
v_balance number;
V_min_balance v_balance%TYPE := 10 ;


9

% RowType Attribute
Declare a variable according to
- a collection of columns in a database table or view.

Syntax
Identifier Table%rowType;
Examples:
v_name employees%ROWTYPE;

10
LOB Data Type Variables
CLOB (character Large Object)
Used to store large blocks of single byte character data in the
database in line and out of line.
BLOB (Binary Large Object )
Used to store large binary objects in the database in line and out of
line.
BFILE ( Binary file)
Used to store large binary objects in OS files outside the database.
NCLOB (National language large objects)
Used to store large blocks of single byte or fixed width multibyte
NCHAR Unicode data in the database, in line and out of line.


11
12
Some symbols used.



Symbol Description
; Semicolon: statement terminator.
% Percent sign: attribute indicator (cursor attributes like %ISOPEN and indirect declaration attributes like
%ROWTYPE). Also used as multibyte wildcard symbol, as in SQL.
_ Single underscore: single-byte wildcard symbol, as in SQL
: Colon: host variable indicator, such as :block.item in Oracle Forms
** Double asterisk: exponentiation operator
< > and != "Not equals"
|| Double vertical bar: concatenation operator
<< and >> Label delimiters
<= and >= Relational operators
:= Assignment operator
=> Association operator for positional notation
-- Double dash: single-line comment indicator
/* and */ Beginning and ending multiple line comment block delimiters
13
Conditional control and Loops
IF <condition-1>
THEN
<statements-1>
...
ELSIF <condition-N>
THEN
<statements-N>
[ELSE
<else_statements>]
END IF;
WHILE <condition>
LOOP
<statement(s)>
END LOOP;
FOR <loop index> IN <lowest no>..<highest no>
LOOP
<statement(s)>
END LOOP;
14
Explicit Cursors
Assigning private work area for SQL statements.

PARSE
Check Validity Determine execution Plan.
BIND
Association of values with placeholders.
OPEN
Bind variables are attached to result set.
EXECUTE
Statement run within SQL engine.
FETCH
Retrieves the next row or record.
CLOSE
Releases memory.
15

1 DECLARE
2 /* Explicit declaration of a cursor */
3 CURSOR emptyp_cur IS
4 SELECT emptyp.type_desc
5 FROM employees emp, employee_type emptyp
6 WHERE emp.type_code = emptyp.type_code;
7 BEGIN
8 /* Check to see if cursor is already open. If not, open it. */
9 IF NOT emptyp_cur%ISOPEN
10 THEN
11 OPEN emptyp_cur;
12 END IF;
13
14 /* Fetch row from cursor directly into an Oracle Forms item */
15 FETCH emptyp_cur INTO :emp.type_desc;
16
17 /* Close the cursor */
18 CLOSE emptyp_cur;
19 END;
16
Cursor contd.
Attribute Description
%ISOPEN
TRUE if cursor is open.
FALSE if cursor is not open.
%FOUND
INVALID_CURSOR is raised if cursor has not been OPENed.
NULL before the first fetch.
TRUE if record was fetched successfully.
FALSE if no row was returned.
INVALID_CURSOR if cursor has been CLOSEd.
%NOTFOUND
INVALID_CURSOR is raised if cursor has not been OPENed.
NULL before the first fetch.
FALSE if record was fetched successfully.
TRUE if no row was returned.
INVALID_CURSOR if cursor has been CLOSEd.
%ROWCOUNT
INVALID_CURSOR is raised if cursor has not been OPENed.
The number of rows fetched from the cursor.
INVALID_CURSOR if cursor has been CLOSEd.
17
Revisiting the FOR loop.
DECLARE
CURSOR occupancy_cur IS
SELECT pet_id, room_number
FROM occupancy WHERE occupied_dt = SYSDATE;
occupancy_rec occupancy_cur%ROWTYPE;
BEGIN
OPEN occupancy_cur;
LOOP
FETCH occupancy_cur INTO occupancy_rec;
EXIT WHEN occupancy_cur%NOTFOUND;
update_bill
(occupancy_rec.pet_id, occupancy_rec.room_number);
END LOOP;
CLOSE occupancy_cur;
END;
Cursor without FOR loop implementation.
18

DECLARE
CURSOR occupancy_cur IS
SELECT pet_id, room_number
FROM occupancy WHERE occupied_dt = SYSDATE;
BEGIN
FOR occupancy_rec IN occupancy_cur
LOOP
update_bill (occupancy_rec.pet_id, occupancy_rec.room_number);
END LOOP;
END;
FOR Loop cursor.
19
PL/SQL Blocks
Stored Procedures


A named PL/SQL block that performs one or more actions and is called as an
executable PL/SQL statement. You can pass information into and out of a procedure
through its parameter list.
CREATE OR REPLACE PROCEDURE <name> [ ( parameter [, parameter ... ] ) ]
IS
[declaration statements]

BEGIN
<executable-statements>

[ EXCEPTION
exception handler statements]

END [ name ];
20



CREATE OR REPLACE PROCEDURE show_emp( p_empno IN NUMBER, rec OUT NUMBER)
IS
records NUMBER(3);
BEGIN
FOR c1 IN (SELECT ename,job,sal,comm FROM emp WHERE empno = p_empno)
LOOP
DBMS_OUTPUT.PUT_LINE('Name: ' || c1.ename);
DBMS_OUTPUT.PUT_LINE('Job: ' || c1.job);
DBMS_OUTPUT.PUT_LINE('Salary: ' || c1.sal);
DBMS_OUTPUT.PUT_LINE('Commission: ' || c1.comm);
records := records + 1;
END LOOP;
rec := records;
END show_emp;
/
Stored Procedures contd.
1) From the SQL prompt.
EXECUTE [or EXEC] :count := show_emp (10616621);

2) Within another procedure simply use the procedure name.
show_emp (10616621, count);
21
1) IN : These types of parameters are used to send values to stored procedures.

2) OUT : These types of parameters are used to get values from stored procedures.

3) IN OUT: These types of parameters are used to send values and get values from
stored procedures.

Positional vs. Notational parameters
CREATE OR REPLACE PROCEDURE show_emp(ename varchar2, eno varchar2)
IS
BEGIN
/***<procedure body>***/
END;
/

show_emp (eno => 10616621, ename =>'Arjun');

show_emp ('Arjun', 10616621);
Parameters
22
Functions



A function is a module that returns a value.
Unlike a procedure, which is a standalone executable statement,
a call to a function can only be part of an executable statement.
CREATE OR REPLACE FUNCTION name [ ( parameter [, parameter ... ] ) ]
RETURN <return_datatype>
IS
[ declaration statements ]

BEGIN
executable statements

[ EXCEPTION
exception handler statements ]

END [ name ];
23
Functions contd.
CREATE OR REPLACE FUNCTION tot_sales (company_id_in IN company.company_id%TYPE,
status_in IN order.status%TYPE := NULL)
RETURN NUMBER
IS
return_value NUMBER;
CURSOR sales_cur (status_in status_code%TYPE)
IS SELECT SUM(amount*discount)
FROM item
WHERE EXISTS (SELECT 'X' FROM order
order.order_id = item.order_id
AND company_id = company_id_in
AND status_code LIKE status_in);

BEGIN
OPEN sales_cur (status_in);
FETCH sales_cur INTO return_value;
IF sales_cur%NOTFOUND
THEN
CLOSE sales_cur;
RETURN NULL;
ELSE
CLOSE sales_cur;
RETURN return_value;
END IF;

END tot_sales;
/
24
Calling a Function
Call tot_sales to assign a value to a local PL/SQL variable:
sales_for_1995 := tot_sales (1504, 'C');

Use a call to tot_sales to set a default value for a variable:

DECLARE
sales_for_1995 NUMBER DEFAULT tot_sales (1504, 'C');
BEGIN

Use tot_sales directly in an expression:

IF tot_sales (275, 'O') > 10000
THEN
...

SELECT Query:
SELECT company_id, tot_sales (company_id, O')
FROM company;
25
Triggers
A database triggers is stored PL/SQL program unit
associated with a specific database table or view.
The code in the trigger defines the action the database needs to perform
whenever some database manipulation (INSERT, UPDATE, DELETE) takes place.
A triggering event
A trigger constraint (Optional)
Trigger action
CREATE OR REPLACE TRIGGER Print_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab
FOR EACH ROW
WHEN (new.Empno > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :new.sal - :old.sal;
dbms_output.put_line ('Old salary: ' || :old.sal);
dbms_output.put_line (' New salary: ' || :new.sal);
dbms_output.put_line(' Difference ' || sal_diff);
END;
/
26
Types of Triggers
Row level triggers Statement level triggers
BEFORE statement triggers AFTER statement triggers
LOGON / LOGOFF triggers INSTEAD OF triggers
FOR EACH ROW
BEFORE | AFTER
INSERT | [OR] UPDATE | [OR] DELETE
DDL triggers
INSTEAD OF INSERT ON manager_info
FOR EACH ROW
AFTER LOGON ON DATABASE |
BEFORE LOGOFF ON DATABASE
BEFORE | AFTER
CREATE | ALTER | DROP
27
An error generated by the system (such as Unique constraint violation")
An error caused by a user action
A warning issued by the application to the user
Exception
EXCEPTION
WHEN exception_name [ OR exception_name ... ]
THEN
<executable statements>
END;
The Exception Section An English-like Translation
EXCEPTION
WHEN NO_DATA_FOUND
THEN
executable_statements1;
If the NO_DATA_FOUND exception was raised, then execute the
first set of statements.
WHEN payment_overdue
THEN
executable_statements2;
If the payment is overdue, then execute the second set of
statements.
WHEN OTHERS
THEN
executable_statements3;END;
If any other exception is encountered, then execute the third
set of statements.
28
Types of Exception
Named system exceptions. Exceptions that have been given names by PL/SQL and
raised as a result of an error in PL/SQL or RDBMS processing.

EXCEPTION
WHEN CURSOR_ALREADY_OPEN
THEN
CLOSE my_cursor;
END;

Named programmer-defined exceptions. Exceptions that are raised as a result of
errors in your application code. You give these exceptions names by declaring them in the
declaration section. You then raise the exceptions explicitly in the program.

PROCEDURE calc_annual_sales
(company_id_in IN company.company_id%TYPE)
IS
invalid_company_id EXCEPTION;
BEGIN
<... body of executable statements ...>
EXCEPTION
WHEN invalid_company_id
THEN
...
END;



29
Unnamed system exceptions. Exceptions that are raised as a result of an error in PL/SQL
or RDBMS processing but have not been given names by PL/SQL. Only the most common
errors are so named; the rest have numbers and can be assigned names with the special
PRAGMA EXCEPTION_INIT syntax.

Consider the below Error Description
ORA-02292 : integrity constraint (string.string) violated - child record found
Cause : attempted to delete a parent key value that had a foreign key dependency.
Action : delete dependencies first then parent or disable constraint.


PROCEDURE delete_company (company_id_in IN NUMBER)
IS
/* Declare the exception. */
still_have_employees EXCEPTION;
/* Associate the exception name with an error number. */
PRAGMA EXCEPTION_INIT (still_have_employees, -2292);
BEGIN
/* Try to delete the company. */
DELETE FROM company
WHERE company_id = company_id_in;
EXCEPTION
/* If child records were found, this exception is raised! */
WHEN still_have_employees
THEN
DBMS_OUTPUT.PUT_LINE
(' Please delete employees for company first.');
END;
30
Unnamed programmer-defined exceptions. Exceptions that are defined and raised in
the server by the programmer.

The programmer provides both an error number (between -20000 and -20999) and an error
message, and raises that exception with a call to RAISE_APPLICATION_ERROR, a system
defined error handling procedure.

The error, along with its message, is propagated back to the client-side application.
CREATE OR REPLACE TRIGGER minimum_age_check
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
IF ADD_MONTHS (:new.birth_date, 18*12) > SYSDATE
THEN
RAISE_APPLICATION_ERROR
(-20001, 'Employees must at least eighteen
years of age.');
END IF;
END;

31
Packages
A package is a group of procedures, functions,
variables and SQL statements created as a single unit.
It is used to store together related objects.
A package has two parts,
Package Specification or package header and Package Body.
Components
Cursors
Variables (scalars, records, tables, etc.)
Exception names
PL/SQL table and record TYPE statements
Procedures and Functions
Advantages of Using Package
Information Hiding
Object-Oriented Design
Top-Down Design
Object Persistence
Performance Improvement
32
PACKAGE package_name
IS
[ declarations of variables and types ]
[ specifications of cursors ]
[ specifications of modules ]
END [ package_name ];
Packages contd.
Specification
Body
PACKAGE BODY package_name
IS
[ declarations of variables and types ]
[ specification and SELECT statement of cursors ]
[ specification and body of modules ]
[ BEGIN
executable statements ]
[ EXCEPTION
exception handlers ]
END [ package_name ];
33
Data Privacy
Public
Defined in the specification.
A public element can be referenced from other programs and PL/SQL blocks.

Private
Defined only in the body of the package, but does not appear in the specification.
A private element cannot be referenced outside of the package.
Any other element of the package may, however, reference and use a private element.
34
CREATE OR REPLACE PACKAGE update_planned_hrs
IS
Planned_hours NUMBER(4);

PROCEDURE set_new_planned (p_emp_id IN NUMBER, p_project_id IN NUMBER, p_hours IN NUMBER);
FUNCTION existing_planned (p_emp_id IN NUMBER, p_project_id IN NUMBER)
RETURN NUMBER;

END update_planned_hrs;
/
CREATE OR REPLACE PACKAGE BODY update_planned_hrs
IS

PROCEDURE set_new_planned (p_emp_id IN NUMBER, p_project_id IN NUMBER, p_hours IN NUMBER)
IS
BEGIN
UPDATE employee_on_activity e
SET e.ea_planned_hours = p_hours
WHERE
e.ea_emp_id = p_emp_id
AND e.ea_proj_id = p_project_id;

EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR (-20100, 'No such employee or project');

END set_new_planned;
--continued to next slide
The purpose of the package is to update the planned hours of an employee, to a project.
The employee is constrained to the passed in parameter.
An error is raised if the employee or project does not exist.
35
FUNCTION existing_planned (p_emp_id IN NUMBER, p_project_id IN NUMBER) RETURN NUMBER
IS
existing_hours NUMBER(4);

BEGIN
SELECT ea.ea_planned_hours INTO existing_hours
FROM employee_on_activity e
WHERE
e.ea_emp_id = p_emp_id
AND e.ea_proj_id = p_project_id;

RETURN (existing_hours);
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR (-20100, 'No such employee or project');
END existing_planned;
END update_planned_hrs; --ending the package
/
36
Accessing components
EXEC update_planned_hrs.set_new_planned (1001, MonteCarlo, 9);
SELECT
update_planned.existing_planned (1001, MonteCarlo)
FROM
DUAL;
37

Das könnte Ihnen auch gefallen