6820436-PLSQL
-
Upload
sriharsha-majjiga -
Category
Documents
-
view
219 -
download
0
Transcript of 6820436-PLSQL
-
8/7/2019 6820436-PLSQL
1/160
Oracle 9i Database Server
PL/SQL
-
8/7/2019 6820436-PLSQL
2/160
Procedural Language/Structured QueryLanguage
PL/SQL is the procedural extension to SQLwith design features of programminglanguages.
Data manipulation and query statements ofSQL are included within procedural units ofcode.
-
8/7/2019 6820436-PLSQL
3/160
PL/SQL
block
PL/SQL engine
Oracle server
Procedural
statement
executor
PL/SQL
SQL
SQL statement executor
PL/SQL
block
PL/SQL Environment
-
8/7/2019 6820436-PLSQL
4/160
Application Other DBMSs
ApplicationOracle with
PL/SQL
SQL
SQL
SQL
SQL
SQLIF...THEN
SQLELSE
SQLEND IF;SQL
Benefits of PL/SQL
Improved performance
PL/SQL can be used to group SQL statements together within a
single block and to send the entire block to the server in a singlecall, thereby reducing networking traffic.
-
8/7/2019 6820436-PLSQL
5/160
Benefits of PL/SQL
Modularize program development
PL/SQL Block Structure
Every unit of PL/SQL comprises one or more blocks.The basic units (procedures, functions, and anonymousblocks) make up a PL/SQL program.
DECLARE
BEGIN
END;
EXCEPTION
-
8/7/2019 6820436-PLSQL
6/160
Modularized Program Development
Group logically related statements within blocks.
Nest sub-blocks inside larger blocks to build powerfulprograms.
Break down a complex problem into a set ofmanageable, well-defined, logical modules and
implement the modules with blocks.
other benefits are :-
PL/SQL is portable. Can be invoked from other env.
You can declare variables
You can program with procedural language controlstructures.
PL/SQL can handle errors.
-
8/7/2019 6820436-PLSQL
7/160
Benefits of PL/SQL
Subprograms
Stored procedures and functions have many benefits inaddition to modularizing application development:
Easy maintenance that enables you to modify:
Improved data security and integrity.
Improved performance allows you to :
Avoid reparsing for multiple users by exploitingthe shared SQL area
Avoid PL/SQL parsing at run time by parsing at
compile time
Reduce the number of calls to the database anddecrease network traffic by bundling commands
-
8/7/2019 6820436-PLSQL
8/160
xxxxxxxxxxxxxxvvvvvvvvvvvvvv
xxxxxxxxxxxxxxvvvvvvvvvvvvvv
xxxxxxxxxxxxxxvvvvvvvvvvvvvv
xxxxxxxxxxxxxxvvvvvvvvvvvvvv
xxxxxxxxxxxxxxvvvvvvvvvvvvvv
LOG_EXECUTION
procedure
Scott
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvvxxxxxxxxxxxxxx
vvvvvvvvvvvvvv
Scott
Oracle
Forms
Developer
1
2
3
4
Invoking Stored Procedures and Functions
-
8/7/2019 6820436-PLSQL
9/160
DECLARE (Optional)
Variables, cursors, user-defined exceptionsBEGIN (Mandatory)
SQL statementsPL/SQL statements
EXCEPTION (Optional)
Actions to perform when errors occurEND; (Mandatory)
DECLARE
BEGIN
END;
EXCEPTION
PL/SQL Block Structure
-
8/7/2019 6820436-PLSQL
10/160
Anonymous Procedure Function[DECLARE]
BEGIN
--statements
[EXCEPTION]
END;
PROCEDURE name
IS
BEGIN
--statements
[EXCEPTION]
END;
FUNCTION name
RETURN datatype
ISBEGIN
--statements
RETURN value;
[EXCEPTION]
END;
Block Types
-
8/7/2019 6820436-PLSQL
11/160
Variables
Variables are used to store values/data, for
reusability, ease of maintenance using typeattributes.
Types ofVariables
PL/SQL variables:
Scalar
Composite
Reference
LOB (large objects)
Non-PL/SQL variables: Bind and host variables
-
8/7/2019 6820436-PLSQL
12/160
Types of Variables
Scalar data types hold a single value (correspond tocolumn types in Oracle server tables). PL/SQL also
supports Boolean variables.Composite data types, such as records, allow groupsof fields to be defined.
Reference data types hold values, called pointers, that
designate other program items.LOB data types hold values, called locators, thatspecify the location of large objects (such as graphicimages) that are stored out of line.
N
on-PL/SQL variables include host language variablesdeclared in precompiler programs, screen fields in Formsapplications, and SQL*Plus/iSQL*Plus host variables.
-
8/7/2019 6820436-PLSQL
13/160
25-JAN-0125-JAN-01AtlantaAtlanta
Four score and seven years ago
our fathers brought forth upon
this continent, a new nation,
conceived in LIBERTY, and dedicated
to the proposition that all men
are created equal.
256120.08256120.08TRUETRUE
Types ofVariables
-
8/7/2019 6820436-PLSQL
14/160
-
8/7/2019 6820436-PLSQL
15/160
Declaring PL/SQL Variables
identifier[CONSTANT]* datatype [NOT NULL]*[:= | DEFAULT expr];
DECLAREv_hiredate DATE;v_deptno NUMBER(2) NOT NULL := 10;v_location VARCHAR2(13) := 'Atlanta';c_comm CONSTANT NUMBER := 1400;
v_mgr NUMBER(6) DEFAULT 100;
Syntax :
Example :
* value must be assigned while declaring
The names of the variables must not be longer than 30characters.
Adopt a naming convention for PL/SQL identifiers:for example, v_variablename
-
8/7/2019 6820436-PLSQL
16/160
Different Datatypes
BINARY_INTEGERto store signed integers(-2**31 .. 2**31)
BINARY_INTEGERSubtypes
Abase type is the datatype from which a subtype is derived.
Asubtype associates a base type with a constraint and so
defines a subset of values.
BINARY_INTEGERsubtypes:
NATURAL, POSITIVE - integermust be positive value.
NATURALN, POSITIVEN - prevent the assigning ofnulls to
an integer variable.
SIGNTYPE - allows only -1, 0, and 1, which is useful in
programming tri-state logic.
-
8/7/2019 6820436-PLSQL
17/160
NUMBERto store fixed-point or floating-point numbers
Range is 1E-130 .. 10E125
NUMBERSubtypes
DEC, DECIMAL, NUMERIC - fixed-point numbers with a
maximum precision of 38 decimal digits
DOUBLE PRECISION, FLOAT - floating-point numbers with a
maximum precision of 126 binary digits, which is roughly equivalent
to 38 decimal digits.
INTEGER, INT, SMALLINT - integers with a maximum precisionof 38 decimal digits.
REAL - floating-point numbers with a maximum precision of 63
binary digits (approx : 18 decimal digits)
-
8/7/2019 6820436-PLSQL
18/160
CHAR- to store fixed-length character data. Maximum size is
32767 bytes.
Syntax:CHAR[(maximum_size [CHAR| BYTE] )]
CHAR Subtypes -
LONG - to store variable-length character strings. The LONG
datatype is like the VARCHAR2 datatype, except that the
maximum size of a LONG value is 32760 bytes.
LONG RAW - to store binary data or byte strings. Themaximum size of a LONGRAW value is 32760 bytes.
-
8/7/2019 6820436-PLSQL
19/160
ROWID and UROWID
Internally, every database table has a ROWID pseudocolumn,
which stores binary values called rowids.Each rowid represents the storage address of a row.
Aphysical rowid identifies a row in anordinary table.
Alogical rowid identifies a row in an index-organized table.
ROWID storesphysical rowids.
UROWID (universal rowid) datatype can storephysical,
logical, or foreign (non-Oracle) rowids.
Physical Rowids Physical rowidsprovide fast access. As long
as the row exists, its physical rowid does not change.
-
8/7/2019 6820436-PLSQL
20/160
VARCHAR2- to store variable-length character data.
Maximum size is 32767 bytes.
Syntax :VARCHAR2(maximum_size [CHAR| BYTE])
VARCHAR2 Subtypes
STRING,VARCHAR subtypes for compatibility with
ANSI/ISO and IBM types.
-
8/7/2019 6820436-PLSQL
21/160
National Character Types
ASCII and EBCDIC character sets are adequate to represent
the Roman alphabet.But some Asian languages, such as Japanese, contain
thousands of characters which require twoor three bytes to
represent each character
Oracleprovides globalization support with this type.
NCHAR- to store fixed-length national character data.
NVARCHAR2- to store variable-lengthUnicode characterdata.
-
8/7/2019 6820436-PLSQL
22/160
Book(CLOB)
Photo
(BLOB)
Movie(BFILE)
NCLOB
LOB Data Type Variables
-
8/7/2019 6820436-PLSQL
23/160
LOB Types
BFILE, BLOB, CLOB, and NCLOB let you store blocks of
unstructured data (such as text, graphic images, video clips,and sound waveforms) up to 4 gigabytes in size.
LOB types store lob locators, whichpoint to large objects
stored in an external file, in-line (inside the row) orout-of-line
(outside the row).
BLOB, CLOB, and NCLOB data is stored in the database, in
oroutside the row.
BFILEdata is stored inoperating system files outside the
database.
-
8/7/2019 6820436-PLSQL
24/160
PL/SQL operates on LOBs through the locators.
-For example, whenyou select a BLOB column value, only
a locator is returned.LOB locator includes a transactionID.
LOB locators change fromone transaction to another.
BFILE- to store large binaryobjects residing onoperating
system files outside the database.
BFILE variable stores a file locator, whichpoints to a large
binary file on the server.
The locator includes a directory alias, which specifies a full
path name
BFILEs are read-only.
-
8/7/2019 6820436-PLSQL
25/160
Boolean Type
BOOLEAN- stores logical values TRUE, FALSE, and NULL
You cannot insert the values TRUE and FALSE into a
database column.
Also, you cannot select or fetch column values into a
BOOLEAN variable.
-
8/7/2019 6820436-PLSQL
26/160
1 5000
2 2345
3 12
4 3456
1 SMITH
2 JONES
3 NANCY
4 TIM
PL/SQL table structure PL/SQL table structure
BINARY_INTEGER
VARCHAR2
BINARY_INTEGER
NUMBER
TRUE 23-DEC-98 ATLANTA
Composite Data Types
-
8/7/2019 6820436-PLSQL
27/160
User-Defined Subtypes
PL/SQLpredefines several subtypes inpackage STANDARD.
For example, PL/SQLpredefines the subtypes CHARACTERand INTEGERas follows:
SUBTYPECHARACTER IS CHAR;
SUBTYPEINTEGER IS NUMBER(38,0);
Defining Subtypes
SUBTYPE subtype_name IS base_type[(constraint)][NOT
NULL];
-
8/7/2019 6820436-PLSQL
28/160
Some examples follow:
SUBTYPEBirthDate IS DATENOTNULL;
SUBTYPE CounterIS NATURAL;
TYPENameList IS TABLE OF VARCHAR2(10);
SUBTYPE DutyRosterIS NameList;
TYPETimeRec IS RECORD (minutes INTEGER, hours
INTEGER);
SUBTYPE FinishTime IS TimeRec;
SUBTYPEID_NumIS emp.empno%TYPE;
-
8/7/2019 6820436-PLSQL
29/160
InitializingVariables
V_COUNTNUMBERNOTNULL:=0
V_SALARYNUMBER(7,2);
V_ANN_SALNUMBER(9,2):=monthly_sal *12;
tax := price * tax_rate;
bonus := current_salary * 0.10;
amount := TO_NUMBER(SUBSTR('750 dollars', 1, 3));
married BOOLEAN:=FALSE;
today date:=SYSDATE;
credit_limit CONSTANTNUMBER(9,2) := 5000.00;
pi CONSTANTNUMBER(9,5):=3.14159;
-
8/7/2019 6820436-PLSQL
30/160
DBMS_OUTPUT Package
Package DBMS_OUTPUT enables you to displayoutput from
PL/SQL blocks and subprograms.Theprocedure put_line outputs information to a buffer in theSGA. You display the information by setting
SERVEROUTPUTON in SQL*Plus.
SQL> SET SERVEROUTPUTON
SQL> BEGIN
2 DBMS_OUTPUT.PUT_LINE(HelloWorld');
3 END;
4 /
HelloWorld
PL/SQLprocedure successfully completed.
-
8/7/2019 6820436-PLSQL
31/160
SQL>DECLARE
2 X integer;
3 BEGIN
4 X:=5000;5 DBMS_OUTPUT.PUT_LINE('The value of X='||X);
6 END;
7 /
The value of X=5000
*Examples to be covered:
Scope of anobject
-
8/7/2019 6820436-PLSQL
32/160
PL/SQL Control Structures
IF-THEN-ELSIF Statement
IF condition1 THEN
sequence_of_statements1
ELSIF condition2 THEN
sequence_of_statements2ELSE
sequence_of_statements3
END IF;
IF-THEN Statement
IF conditionTHENsequence_of_statements;
END IF;
IF-THEN-ELSE Statement
IF conditionTHEN
sequence_of_statements1;
ELSE
sequence_of_statements2;END IF;
-
8/7/2019 6820436-PLSQL
33/160
Boolean type Example
DECLAREv_flag boolean:=false;
n1 number:=300;n2 number:=200;BEGINv_flag:=n1>n2;if v_flag thendbms_output.put_line('true');
elsedbms_output.put_line('false');
end if;END;
*Income tax example to be discussed
-
8/7/2019 6820436-PLSQL
34/160
CASE Statement[]CASE selector
WHEN expression1 THEN sequence_of_statements1;...WHEN expressionN THEN sequence_of_statementsN;[ELSE sequence_of_statementsN+1;]END CASE [label_name];
DECLAREgrade CHAR:=&grade;
BEGINCASE gradeWHEN A THEN dbms_output.put_line(Excellent);WHEN B THEN dbms_output.put_line(Very Good);WHEN C THEN dbms_output.put_line(Good);WHEN D THEN dbms_output.put_line(Fair);ELSE dbms_output.put_line(No such grade);
END CASE;
END;
-
8/7/2019 6820436-PLSQL
35/160
Searched CASE Statement[]CASE
WHEN search_condition1 THEN statements1;...WHEN search_conditionN THEN statementsN;[ELSE sequence_of_statementsN+1;]END CASE [label_name];
DECLAREgrade CHAR:=&grade;
BEGINCASE
WHEN
grade=A THEN
dbms_output.put_line(Excellent);WHEN grade=B THEN dbms_output.put_line(Very Good);WHEN grade=C THEN dbms_output.put_line(Good);WHEN grade=D THEN dbms_output.put_line(Fair);ELSE dbms_output.put_line(No such grade);
END CASE;
END;
-
8/7/2019 6820436-PLSQL
36/160
Iterative Control: LOOP and EXIT Statements
There are three forms of LOOP statements: LOOP, WHILE-
LOOP, and FOR-LOOP.
LOOP
LOOP
sequence_of_statements;
END LOOP;
use anEXIT / EXITWHEN statement to complete the loop.
-
8/7/2019 6820436-PLSQL
37/160
WHILE-LOOP
WHILE condition LOOP
sequence_of_statements
END LOOP;FOR-LOOP
FORcounterIN[REVERSE] lower_bound..higher_bound
LOOPsequence_of_statements
END LOOP;
NULL Statement
TheNULL statement does nothing other thanpass control to
the next statement.
-
8/7/2019 6820436-PLSQL
38/160
Interacting with the Oracle Server
SELECT .. INTO .. Statement
-retrieves data fromone ormore database tables, then assignsthe selected values to variables
*To be explained with example
-
8/7/2019 6820436-PLSQL
39/160
SQL *PLUS BIND VARIABLES
These are host variables that may be used topass runtimevalues intoorout of PL/SQL block.
Bind variables are declared in SQL *PLUS
VARIABLE variable_name [NUMBER| CHAR| CHAR(N) |VARCHAR2(N)]
Ex:VARIABLE emplnameVARCHAR2(12)
*To be explained with example with PRINT command
-
8/7/2019 6820436-PLSQL
40/160
DeclaringVariables based on database columns
DECLARE
empname EMP.ENAME%TYPE;
.%TYPE attribute enables you to define a variable based on a
table column datatype
% is attribute indicator.
PL/SQL RecordVariablesArecordis a groupof related data items stored infields, each
with its ownname and datatype.
These items are logically related but dissimilar in type.
A record containing a field for each item lets you treat the dataas a logical unit.
To create records, you define a RECORD type, then declare
records of that type.
-
8/7/2019 6820436-PLSQL
41/160
PL/SQL Record Structure
Field1 (data type) Field2 (data type) Field3 (data type)
10 ACCOUNTING NEW YORK
Field1 (data type) Field2 (data type) Field3 (data type)
dept_id number(2) dept_name varchar2(14) dept_loc varchar2(13)
Example:
-
8/7/2019 6820436-PLSQL
42/160
Syntax
Note : RECORD types cannot be CREATEd and stored in the
database.
You canuse %TYPE and %ROWTYPE to specify field types.
In the following example, you define a RECORD type namedDeptRec:TYPE DeptRectype IS RECORD (
dept_id dept.deptno%TYPE, dept_nameVARCHAR2(14),
dept_locVARCHAR2(13));
TYPE type_name IS RECORD
(field_declaration[, field_declaration]);
identifier type_name;
field_name {field_type | variable%TYPE
| table.column%TYPE| table%ROWTYPE}
[[NOT NULL] {:= | DEFAULT} expr]
-
8/7/2019 6820436-PLSQL
43/160
Declaring a record variable
dept_rec deptrectype;
To access individual fieldsdept_rec.dept_id;
dept_rec.dept_name;
*example on recordtype
Record variables based on tables
It means that each field in the record has the same name and
datatype as the columns in the specified table.
%ROWTYPE attribute is used to facilitate the declarationof arecord based on a table.
emprec EMP%ROWTYPE;* example on rowtype
* Retired employees example.
-
8/7/2019 6820436-PLSQL
44/160
PL/SQL Error Handling
In PL/SQL, a warning or error condition is called an
exception.Anexceptionis an identifier in PL/SQL that is raised duringthe executionof a block that terminates its main bodyofactions. A block always terminates when PL/SQL raises an
exception, but canyou specify an exception handler toperform final actions.
Examples of internally defined exceptions include no data
found, fetching multiple rows, value error, division by zero,
out of memory and manymore.
For example, if the error ORA-01403 occurs when norows are retrieved from the database in a SELECTstatement, then PL/SQL raises the exceptionNO_DATA_FOUND.
-
8/7/2019 6820436-PLSQL
45/160
Handling Exceptions
Trap the exception
DECLARE
BEGIN
END;
Exception
is raisedEXCEPTION
Exception
is trapped
Propagate the exception
DECLARE
BEGIN
END;
Exception
is raisedEXCEPTION
Exception
is nottrapped
Exception
propagates to calling
environment
-
8/7/2019 6820436-PLSQL
46/160
Predefined Exception Handler
-
8/7/2019 6820436-PLSQL
47/160
d fi d i i d h
-
8/7/2019 6820436-PLSQL
48/160
Predefined Exception raised when
-
8/7/2019 6820436-PLSQL
49/160
-
8/7/2019 6820436-PLSQL
50/160
-
8/7/2019 6820436-PLSQL
51/160
*Examples to be given for
-
8/7/2019 6820436-PLSQL
52/160
*Examples to be given forno_data_found,too_many_rows,value_error
OTHERS EXCEPTION HANDLER
Can be used as a generic exception handler.
SQLCODE & SQLERRM Functions
SQLCODE returns the number of the Oracle error forinternal exceptions. You can pass an error number to
SQLERRM, which then returns the message associated withthe error number.
USER-DEFINED EXCEPTIONS
PL/SQL lets you define exceptions of your own.
User-defined exceptions must be declared and must beraised explicitly by RAISE statements.
How PL/SQL Exceptions Propagate
-
8/7/2019 6820436-PLSQL
53/160
How PL/SQL Exceptions Propagate
-
8/7/2019 6820436-PLSQL
54/160
-
8/7/2019 6820436-PLSQL
55/160
Procedure RAISE APPLICATION ERROR
-
8/7/2019 6820436-PLSQL
56/160
Procedure RAISE_APPLICATION_ERROR
The procedure RAISE_APPLICATION_ERROR lets youissue user-defined ORAerror messages from stored
subprograms. That way, you can report errors to yourapplication and avoid returning unhandled exceptions.
raise_application_error(error_number, message[, {TRUE |FALSE}]);
error_number is a negative integer in the range -20000.. -20999
message is a character string up to 2048 bytes long.
IfTRUE, the error is placed on the stack of previouserrors.
IfFALSE(the default), the error replaces all previouserrors.
-
8/7/2019 6820436-PLSQL
57/160
RAISE_APPLICATION_ERROR is part of packageDBMS_STANDARD, and as with package STANDARD, you
do not need to qualify references to it.
An application can call raise_application_erroronly froman executing stored subprogram (or method).
When called, raise_application_error ends thesubprogram and returns a user-defined error number andmessage to the application.
The error number and message can be trapped like anyOracle error.
*will be discussed in procedures and triggers topic
Nonp edefined E o
-
8/7/2019 6820436-PLSQL
58/160
Nonpredefined Error
PRAGMA EXCEPTION_INIT
Apart from predefined exception, we can extend the list of exceptionsassociated with an Oracle error within our PL/SQL code with the useofPRAGMA EXCEPTION_INIT keyword.
EXCEPTION PRAGMA is used to associate a named exception with aparticular Oracle error.
This enable us to trap the error specifically, rather than via anOTHERS handle.
Only one user defined exception can be associated with one Oracleerror with each occurrence of PRAGMA EXCEPTION_INIT.
This statement is a compiler directive that allows the developer todeclare the Oracle-numbered error to be associated with a namedexception in the block.
CURSORs
-
8/7/2019 6820436-PLSQL
59/160
CURSORs
Whenever you issue a SQL statement, the Oracleserver opens an area of memory in which the command
is parsed and executed. This area is called a cursor.
PL/SQL cursors provide a way for your program toselect multiple rows of data from the database andthen to process each row individually.
PL/SQL uses two types of cursors: implicitand explicit.
PL/SQL declares a cursor implicitly for all SQL DMLstatements, including select queries that return only
one row.
However, for queries that return more than one row,you must declare an explicit cursor.
-
8/7/2019 6820436-PLSQL
60/160
Controlling Explicit CursorsControlling Explicit Cursors
Create a
named
SQL area
DECLAREDECLARE
Identify
the active
set
OPENOPEN
Load the
current
row into
variables
FETCHFETCH
Release
the active
set
CLOSECLOSEYes
Test for
existing
rows
EMPTY?EMPTY?
Return toFETCH if
rows are
found
No
Declaring a Cursor
-
8/7/2019 6820436-PLSQL
61/160
Declaring a Cursor
When you declare a cursor, you name it and associate itwith a specific query
CURSOR cursor_name [(parameter[, parameter]...)][RETURN return_type] IS select_statement;
where return_type must represent a record or a row in adatabase table.
At this stage, the query is parsed (cols, tables etc., arevalidated) but it is not executed.
Ex:cursor emp_cur is
select ename,sal,hiredate,deptno from emp where
deptno=20;
OPENing the Cursor
-
8/7/2019 6820436-PLSQL
62/160
OPENing the Cursor
Opening the cursor executes the query and identifies theresult set, which consists of all rows that meet the query
search criteria.
For cursors declared using the FOR UPDATE clause, theOPEN statement also locks those rows.
OPEN cursor_name;
Ex:OPEN emp_cur;
OPEN c1(emplname, 3000);
OPEN c1(SMITH, 1500);
OPEN c1(emplname, esal);
Fetching with a Cursor
-
8/7/2019 6820436-PLSQL
63/160
Fetching with a Cursor
The FETCH statement retrieves the rows in the result setone at a time. Each fetch retrieves the current row and
then advances the cursor to the next row in the resultset.
FETCH cursor_name INTO var1,var2,.. or record_list;
Ex:
FETCH c1 INTO my_empno, my_ename, my_deptno;
LOOP
FETCH c1 INTO my_record;EXIT WHEN c1%NOTFOUND;-- process data recordEND LOOP;
Closing a Cursor
-
8/7/2019 6820436-PLSQL
64/160
Closing a Cursor
The CLOSE statement disables the cursor, and the resultset becomes undefined.
Once a cursor is closed, you can reopen it. Any otheroperation on a closed cursor raises the predefinedexception INVALID_CURSOR.
CLOSE cursor_name;
Ex:
CLOSE emp_cur;
CURSOR attributes
-
8/7/2019 6820436-PLSQL
65/160
CURSOR attributes
Cursor attributes return information about the executionof a multi-row query.
%FOUND Attribute: Has a Row Been Fetched?- equates toTRUE if the last fetch returned a row, or FALSE if the lastfetch failed to return a row.
%ISOPEN Attribute: Is the Cursor Open? - equates to TRUEif explicit cursor is open; otherwise, %ISOPEN equates toFALSE. In case of implicit cursors always it equates toFALSE.
%NOTFOUND Attribute: Has a Fetch Failed? - yields FALSE if
the last fetch returned a row, or TRUE if the last fetchfailed to return a row.
%ROWCOUNT Attribute: How Many Rows Fetched So Far?
yields the number of rows fetched so far. The number is
incremented if the last fetch returned a row.
Examples to be discussed:
-
8/7/2019 6820436-PLSQL
66/160
Examples to be discussed:
1. To fetch empno,ename,job,sal,deptno from emp usingrecord type variable using cursor%ROWTYPE
2. To fetch top five employee details.3. To fetch nth row from a table
-
8/7/2019 6820436-PLSQL
67/160
CURSORFORloop:
PL/SQLprovides a special kind of FORloop toprocess therows returned in an explicit CURSOR.
In a CURSORFORloop, a declared CURSORis OPENed,
FETCHed from and CLOSEed automatically when all of therows have be processed.
Each iterationof the loop fetches a row from the active set into
a record, which is implicitly declared foruse within the loop.
The loop is terminated automatically at the end of the iteration
when the last row was FETCHed.
Cursor Variables
-
8/7/2019 6820436-PLSQL
68/160
Cursor VariablesCursor variables are like C pointers, which hold thememory location (address) of some item instead of theitem itself.
In PL/SQL, a pointer has datatype REF X, where REFis short for REFERENCE and X stands for a class ofobjects.
Therefore, a cursor variable has datatype REF CURSOR.
Uses of Cursor VariablesMainly, you use cursor variables to pass query result sets
between PL/SQL stored subprograms and various clients.
Defining REF CURSOR Types
-
8/7/2019 6820436-PLSQL
69/160
Defining REF CURSOR Types
To create cursor variables, you take two steps.
First, you define a REF CURSOR type, then declare cursorvariables of that type.
You can define REF CURSOR types in any PL/SQL block,subprogram, or package
TYPE ref_type_name IS REF CURSOR [RETURNreturn_type];
where ref_type_name is a type specifier used insubsequent declarations of cursor variables and
return_type must represent a record or a row in adatabase table.
Then declare variable ofref_type_name
Example : 2
-
8/7/2019 6820436-PLSQL
70/160
p
SQL> variable g_ref refcursorDECLARE
TYPE emp_cur_t is REF CURSOR returnemp%rowtype;
v_cur emp_cur_t;emp_rec emp%rowtype;
BEGIN
OPENv_cur for select * from emp;FOR idx in 1..6 LOOP
FETCH v_cur into emp_rec;DBMS_OUTPUT.PUT_LINE(emp_rec.ename);
END LOOP;
:g_ref := v_cur;END;/SQL> print g_ref
PL/SQL Subprograms
-
8/7/2019 6820436-PLSQL
71/160
/ Q p g
Subprograms are named PL/SQL blocks that can take
parameters and be invoked.
PL/SQL has two types of subprograms calledprocedures and
functions.
Procedures are used toperform an action
Functions are used to compute a value.
subprograms have a declarative part, anexecutable part, and
anoptional exception-handlingpart.
The declarativepart contains declarations of types, cursors,
constants, variables, exceptions, and nested subprograms.
Advantages of Subprograms
-
8/7/2019 6820436-PLSQL
72/160
g p g
Extensibility: that is, they let you tailor the PL/SQL language
to suit yourneeds.
Modularity: that is, they let you break a program down into
manageable, well-defined modules.
reusability and maintainability: Once validated, a subprogram
can be used with confidence in anynumberof applications. If
its definition changes, only the subprogram is affected. This
simplifies maintenance.
Abstraction:Touse subprograms, youmust know what theydo, not how they work.
PL/SQL Procedures
-
8/7/2019 6820436-PLSQL
73/160
/ QSyntax:
[CREATE [OR REPLACE]]PROCEDURE procedure_name[(parameter[,parameter]...)]{IS | AS}[local declarations]
BEGINexecutable statements[EXCEPTIONexception handlers]END[procedure_name];
First 2 lines are procedure specification and rest isprocedure body
declarative part is placed between the IS and BEGIN
-
8/7/2019 6820436-PLSQL
74/160
p p
keyword DECLARE is not used.
Procedures that take no parameters are written withoutparentheses.
You cannot constrain the datatype of a parameter.
PROCEDURE reconcile (acct_id CHAR(5)) IS ... illegal
However, you can use the following workaround to size-constrain parameter types indirectly:
DECLARESUBTYPE Char5 IS CHAR(5);
PROCEDURE reconcile (acct_id Char5) IS ...
whereparameterstands for the following syntax:
parameter_name [IN | OUT | IN OUT ] datatype [{:= |
DEFAULT} expression]
-
8/7/2019 6820436-PLSQL
75/160
Procedural ParameterModes
Calling
environment
Procedure
procedure
BEGIN
EXCEPTION
END;
IN parameter
OUT parameter
IN OUT parameter
-
8/7/2019 6820436-PLSQL
76/160
A simple PL/SQLprocedure
-
8/7/2019 6820436-PLSQL
77/160
p Q p
To increase the salaryof employee
CREATE ORREPLACE PROCEDURE raise_salary (emp_idINTEGER, increase REAL) is
BEGIN
UPDATE emp SET sal = sal + increase
WHERE empno = emp_id;commit;
END raise_salary;
Calling a procedure
SQL> EXECUTERAISE_SALARY(7369,100);SQL> begin
2 raise_salary(7369,100);
3 end;
4 /
CREATE PROCEDURE calc bonus (emp id IN
-
8/7/2019 6820436-PLSQL
78/160
_ ( p_
emp.empno%TYPE, bonus OUTREAL) IS
BEGIN
SELECT sal * 3 INTO bonus FROM empWHEREempno = emp_id;
END;
Callingprocedure from a PL/SQL blockDECLARE
empid emp.empno%TYPE:=&EMPNO;
bonusNUMBER;
BEGINcalc_bonus(empid,bonus);
dbms_output.put_line('Bonus='||bonus);
END;
Example for inserting a row:
-
8/7/2019 6820436-PLSQL
79/160
PROCEDURE create_dept (new_dname VARCHAR2,new_loc VARCHAR2) ISBEGININSERT INTO dept VALUES (deptno_seq.NEXTVAL,new_dname, new_loc);END create_dept;
ExamplesInserting row into table. Handling exception.Delete row from table. Handle exception if any.
Declaring PL/SQL
-
8/7/2019 6820436-PLSQL
80/160
Subprograms
You can declaresubprograms in any PL/SQLblock, subprogram, orpackage.
Subprograms must bedeclared at the end of adeclarative section after allother program items.
DECLARE
-
8/7/2019 6820436-PLSQL
81/160
empid INTEGER:=&EMPNO;
bon NUMBER;
PROCEDUREcalc_bonus (emp_idin INTEGER,bonus outREAL) IS
hire_datedate;
BEGIN
SELECTsal* 3,hiredate INTObonus,hire_date
FROMemp WHEREempno = emp_id;
IFmonths_between(sysdate,hire_date) > 60 THEN
bonus:= bonus + 500;
END IF;
END;BEGIN
calc_bonus(empid,bon);
dbms_output.put_line('Bonus='||bon);
END;
Default Values for Subprogram Parameters
-
8/7/2019 6820436-PLSQL
82/160
PROCEDURE create_dept (dno dept.deptno%type,new_dname dept.dname%type DEFAULT TEMP,new_loc dept.loc%type VARCHAR2 DEFAULT TEMP) ISBEGININSERT INTO deptVALUES (dno, new_dname, new_loc);
Commit;END;
If an actual parameter is not passed, the default value ofits corresponding formal parameter is used.
create_dept;create_dept(MARKETING);create_dept(MARKETING, NEW YORK);
-
8/7/2019 6820436-PLSQL
83/160
you cannot skip a formal parameter by leaving out itsactual parameter.
create_dept(NEW YORK); -- incorrect
You cannot solve the problem by leaving a placeholder forthe actual parameter.
create_dept(, NEW YORK); -- not allowedIn such cases, you must use named notation, as follows:
create_dept(new_loc => NEW YORK);
d
-
8/7/2019 6820436-PLSQL
84/160
Dropping Procedures
DROP PROCEDURE procedure_name;
PL/SQL Functions
-
8/7/2019 6820436-PLSQL
85/160
Functions and procedures are structured alike, exceptthat functions have a RETURN clause.[CREATE [OR REPLACE ] ]FUNCTION function_name [ ( parameter [ , parameter ]...) ] RETURN datatype{IS | AS}
[ local declarations ]BEGINexecutable statements;RETURN Statement;
[ EXCEPTION
exception handlers ]END[ function_name ];RETURN StatementRETURN statement mustcontain an expression, which isevaluated when the RETURN statement is executed.
In a function, there must be at least one execution pathth t l d t RETURN t t t Oth i t
-
8/7/2019 6820436-PLSQL
86/160
that leads to a RETURN statement. Otherwise, you get afunction returned withoutvalue error at run time.Examples :
A function which returns string in sentence case afteraccepting a string
CREATE OR REPLACE FUNCTION SENTCASE(STR
VARCHAR2)RETURN VARCHAR2ISS VARCHAR2(80);BEGIN
S:=UPPER(SUBSTR(STR,1,1))||LOWER(SUBSTR(STR,2));RETURN S;END;
Calling a function
-
8/7/2019 6820436-PLSQL
87/160
SELECT SENT_CASE('HOW are YOU now') FROMDUAL;
Examples:
Function to get day of the week.
Function to calculate your age in years and months
Function to retrieve emprecord with max salary.
Dropping Functions
DROP FUNCTION function_name
-
8/7/2019 6820436-PLSQL
88/160
Procedures
Execute as a PL/SQLstatement
Do not contain RETURNclause in the header
Can return none, one,or many values
Can contain a RETURNstatement
Functions
Invoke as part of anexpression
Must contain a RETURNclause in the header
Must return a single value
Must contain at least oneRETURN statement
Comparing Procedures
and Functions
Overview of Packages
-
8/7/2019 6820436-PLSQL
89/160
Packages:
Group logically related PL/SQL types, items,and subprograms
Consist of two parts:
SpecificationBody
Cannot be invoked, parameterized, or nested
Allow the Oracle server to read multipleobjects into memory at once
Components of a Package
-
8/7/2019 6820436-PLSQL
90/160
p g
ProcedureA
declaration
ProcedureA
definition
Procedure Bdefinition
Public variable
Private variable
Public procedure
Private procedure
Public procedure
Local variable
Package
specification
Package
body
Note : A package specification can exist without a packagebody, but a package body cannot exist without a package
specification.
Packages usually have twoparts, aspecification and a body,
-
8/7/2019 6820436-PLSQL
91/160
although sometimes the body is unnecessary.
The specification is the interface toyour applications; itdeclares the types, variables, constants, exceptions, cursors,
and subprograms available foruse.
The body fully defines cursors and subprograms, and soimplements the spec.
Package Specification
-
8/7/2019 6820436-PLSQL
92/160
Package Specification
Package Body
Package for handling employees
-
8/7/2019 6820436-PLSQL
93/160
CREATE ORREPLACE PACKAGE emp_actions AS
PROCEDURE hire_employee (empnoNUMBER,
ename VARCHAR2,
job VARCHAR2,
mgr NUMBER,sal NUMBER,
comm NUMBER,
deptnoNUMBER);
PROCEDURE fire_employee (emp_id NUMBER);PROCEDURE raise_salary (emp_id INTEGER, increase
NUMBER);
END emp_actions;
Package body
CREATE OR REPLACE PACKAGE BODY i AS
-
8/7/2019 6820436-PLSQL
94/160
CREATE ORREPLACE PACKAGEBODY emp_actions AS
PROCEDURE hire_employee (
empnoNUMBER,ename VARCHAR2,
job VARCHAR2,
mgr NUMBER,
sal NUMBER,comm NUMBER,
deptnoNUMBER) IS
BEGIN
INSERTINTO empVALUES (empno, ename, job, mgr,SYSDATE, sal, comm, deptno);
END hire_employee;
(contd)
Package body contd
PROCEDURE fi l ( id NUMBER) IS
-
8/7/2019 6820436-PLSQL
95/160
PROCEDURE fire_employee (emp_id NUMBER) IS
BEGIN
DELETE FROM empWHERE empno = emp_id;END fire_employee;
PROCEDURE raise_salary (emp_id INTEGER, increase
NUMBER) ISBEGIN
UPDATE emp SET sal = sal + increase WHERE empno =
emp_id;
END raise_salary;END emp_actions;
Executing Packages
EXECUTE EMP ACTIONS FIRE EMPLOYEE(7566)
-
8/7/2019 6820436-PLSQL
96/160
-EXECUTEEMP_ACTIONS.FIRE_EMPLOYEE(7566);
-EXECUTEEMP_ACTIONS.HIRE_EMPLOYEE
(1000,'RAJESH','MANAGER',7566,3000,500,10);-EXECUTEEMP_ACTIONS.RAISE_SALARY(7369,100);
Using cursors in a package
CREATE PACKAGE emp_stuffAS
CURSORc1 RETURN emp%ROWTYPE;
END emp_stuff;
CREATE PACKAGEBODY emp_stuffAS
CURSORc1 RETURN emp%ROWTYPEIS
SELECT * FROM empWHERE sal > 2500;
END emp_stuff;
(contd ..)
U i i PL/SQL bl k
-
8/7/2019 6820436-PLSQL
97/160
Using cursor in a PL/SQL block
DECLAREemp_rec emp%ROWTYPE;
BEGIN
OPENemp_stuff.c1;
LOOPFETCH emp_stuff.c1 INTO emp_rec;
EXITWHENemp_stuff.c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(emp_rec.ename||','||
emp_rec.job||','||emp_rec.sal);END LOOP;
CLOSE emp_stuff.c1;
END;
Overloading
-
8/7/2019 6820436-PLSQL
98/160
Enables you to use the same name for differentsubprograms inside a PL/SQL block, a subprogram, or apackage
Requires the formal parameters of the subprograms todiffer in number, order, or data type family
Enables you to build more flexibility because a user orapplication is not restricted by the specific data type ornumber of formal parameters
Example :
-
8/7/2019 6820436-PLSQL
99/160
Package Specification
CREATE OR REPLACE PACKAGE over_pack
IS
PROCEDURE add_dept
(p_deptno IN dept.deptno%TYPE,
p_name IN dept.dname%TYPE DEFAULT 'unknown',
p_loc IN dept.loc%TYPE DEFAULT 'unknown');
PROCEDURE add_dept
(p_name IN dept.dname%TYPE DEFAULT 'unknown',
p_loc IN dept.loc%TYPE DEFAULT 'unknown');
END over_pack;
/
Package BodyCREATE OR REPLACE PACKAGE BODY over pack IS
-
8/7/2019 6820436-PLSQL
100/160
CREATE OR REPLACE PACKAGE BODY over_pack IS
PROCEDURE add_dept(p_deptno IN dept.deptno%TYPE,
p_name IN dept.dname%TYPE DEFAULT 'unknown',p_loc IN dept.loc%TYPE DEFAULT 'unknown')ISBEGININSERT INTO dept VALUES (p_deptno, p_name, p_loc);END add_dept;
PROCEDURE add_dept(p_name IN dept.dname%TYPE DEFAULT 'unknown',p_loc IN dept.loc%TYPE DEFAULT 'unknown')ISBEGIN
INSERT INTO dept VALUES (dept_seq.NEXTVAL, p_name,p_loc);END add_dept;END over_pack;/
OBJECTS
-
8/7/2019 6820436-PLSQL
101/160
What Is an Object Type?
Anobject type is a user-defined composite datatype thatencapsulates a data structure along with the functions and
procedures needed tomanipulate the data.
The variables that form the data structure are called
attributes.
The functions andprocedures that characterize the behaviorof
the object type are called methods.
Object type is the closest thing to a class.
Object Type and Objects (Instances) of that Type
-
8/7/2019 6820436-PLSQL
102/160
Why Use Object Types?
-
8/7/2019 6820436-PLSQL
103/160
Object types reduce complexity by breaking down a large
system into logical entities.
This lets you create software components that are modular,
maintainable, and reusable.
It also allows different teams ofprogrammers to develop
software components concurrently.
Object types minimize side effects by allowing access to data
only through approved operations.
*USER_OBJECTS-procedures,functions,types etc*USER_TYPES-object_types
*USER_SOURCE-code forobjects
*USER_TYPE_ATTRS-objects attributes
*USER_TYPE_METHODS-objects methods
Structure of an Object Type
-
8/7/2019 6820436-PLSQL
104/160
The specification is the interface toyour applications; it
declares a data structure (set of attributes) along with the
operations (methods) needed tomanipulate the data.
The body fully defines the methods, and so implements the
spec.
Defining Object Types
You cannot define object types in a PL/SQL block
-
8/7/2019 6820436-PLSQL
105/160
You cannot define object types in a PL/SQL block,
subprogram, orpackage. You can define them interactively in
SQL*PlusCREATE[ORREPLACE]TYPE type_name {IS | AS}
OBJECT
(
attribute_name datatype[, attribute_name datatype]...[MEMBERsubprogram_spec ,..]
)
CREATE[ORREPLACE]TYPEBODY type_name {IS |AS}
{MEMBER| STATIC} {subprogram_body | call_spec};
END;
Simple Example without body
-
8/7/2019 6820436-PLSQL
106/160
CREATE or REPLACE TYPE address_type AS OBJECT
(
RESNO NUMBER(4),STREETVARCHAR2(12),
CITYVARCHAR2(12),
PHONE VARCHAR2(20)
);
CREATE TABLE EMPADDRESS(
ENAMEVARCHAR2(12),
ADDRESS address_type);
INSERT INTO EMPADDRESS VALUES('SMITH',
address_type(112,'M G ROAD','BLORE','1234567'));
SELECT ENAME,E.ADDRESS.PHONE FROM EMPADDRESS E;
observe
-
8/7/2019 6820436-PLSQL
107/160
E.address.phone
Note that the access of the datatypes attribute requires the useof a table alias. A table alias, also known as a correlation
variable, allows oracle to resolve any ambiguity regarding the
name of the object being selected.
Format for columnname is
Correlation.column.attribute
Previous example with spec and body
-
8/7/2019 6820436-PLSQL
108/160
CREATEorREPLACE type address_type AS OBJECT(
resnoNUMBER(5),streetVARCHAR2(10),
cityVARCHAR2(12),
phoneVARCHAR2(20),
MEMBERFUNCTION getresnoRETURNNUMBER,MEMBERFUNCTION getstreet RETURNVARCHAR2,
MEMBERFUNCTION getcityRETURNVARCHAR2,
MEMBERFUNCTION getphone RETURNVARCHAR2
);
CREATE OR REPLACE TYPE BODY address_type AS
MEMBER FUNCTION getresno RETURN NUMBER is
-
8/7/2019 6820436-PLSQL
109/160
g
BEGIN
RETURN resno;
END;MEMBER FUNCTION getstreet RETURN VARCHAR2 is
BEGIN
RETURN street;
END;MEMBER FUNCTION getcity RETURN VARCHAR2 is
BEGIN
RETURN city;
END;
MEMBER FUNCTION getphone RETURN VARCHAR2 isBEGIN
RETURN phone;
END;
END;
DECLARE
ADDR1 ADDRESS TYPE;
-
8/7/2019 6820436-PLSQL
110/160
ADDR1 ADDRESS_TYPE;
BEGIN
SELECTADDRESS INTO ADDR1 FROMEMPADDRESSWHEREENAME='SMITH';
DBMS_OUTPUT.PUT_LINE(ADDR1.PHONE);
END;
declare
addr1 address_type;
begin
addr1:=address_type(20,'JAYANAGAR','DELHI',787889);dbms_output.put_line(addr1.getresno||,||addr1.street||,||addr1.ci
ty||,||addr1.phone);
end;
Adding an attribute to an existing object type
-
8/7/2019 6820436-PLSQL
111/160
alter type address_type add attribute(state varchar2(20))
cascade;
When a new row is inserted the existing data will be NULL
for that column attribute.
Adding anmethod to anobject type
ALTERTYPEADDRESS_TYPEADD MEMBER
FUNCTIONGETSTATERETURNVARCHAR2 CASCADE
Dropping attribute from anobject type
ALTERTYPEADDRESS_TYPE DROP ATTRIBUTE
STATE CASCADE
OBJECTTABLES
-
8/7/2019 6820436-PLSQL
112/160
A table in which each row represents anobject
-CREATETABLE address OF address_type;
-INSERTINTO addressVALUES (address_type(10
,MNagar',Blore',Kar','23445'));
-SELECT * FROMADDRESS;
-update address set street=MExtn' where resno=10;
-delete address where resno=10;
Example forpractice
-
8/7/2019 6820436-PLSQL
113/160
CREATETYPEADDRESS_TYAS OBJECT
(STREETVARCHAR2(20),CITYVARCHAR2(20),
STATE CHAR(2),
ZIPNUMBER);
CREATETYPE PERSON_TYAS OBJECT
(NAMEVARCHAR2(20),
ADDRESS ADDRESS_TY);
CREATETABLE CUSTOMER
(CUSTOMER_IDNUMBER,
PERSON PERSON_TY);
INSERTINTO CUSTOMERVALUES(1,
PERSON TY('NEILMULLANE'
-
8/7/2019 6820436-PLSQL
114/160
PERSON_TY(NEILMULLANE ,
ADDRESS_TY('57 MT PLEASANT ST', 'FINN', 'NH',
11111)));
INSERTINTO CUSTOMERVALUES(2,
PERSON_TY('SEYMOURHESTER',
ADDRESS_TY('1 STEPAHEAD RD', 'BRIANT', 'NH',11111)));
SELECT CUSTOMER_ID,C.PERSON.NAME FROM
CUSTOMERC;
SELECT C.PERSON.ADDRESS.STREET FROM
CUSTOMERC;
COLLECTION
-
8/7/2019 6820436-PLSQL
115/160
Acollection is anordered groupof elements, all of the
same type.It is a general concept that encompasses lists, arrays,
and other familiar datatypes.
Each element has a unique subscript that determines
its position in the collection
Types of Collections
-
8/7/2019 6820436-PLSQL
116/160
PL/SQL tables: to hold arbitrarynoof elements. Indexing is
by binary_integer.
Nested tables hold an arbitrarynumberof elements. Theyuse
sequential numbers as subscripts.
Varrays (variable-size arrays) hold a fixed numberof
elements (although you can change the numberof elements at
runtime). Theyuse sequential numbers as subscripts.
INDEX BY Tables
Objects of the TABLE type are called INDEX BY tables.
-
8/7/2019 6820436-PLSQL
117/160
j yp
They are modeled as database tables (but not the
same as).INDEX BY tables use a primary key to provide you witharray-like access to rows.
A INDEX BY table:
Is similar to an arrayMust contain two components:
A primary key of data type BINARY_INTEGERthat indexes the INDEX BY table
A column of a scalar or record data type, whichstores the INDEX BY table elements
Can increase dynamically because it isunconstrained
C ti INDEX BY T bl
-
8/7/2019 6820436-PLSQL
118/160
Creating anINDEX BY Table
Syntax:TYPE type_name IS TABLE OF
{column_type | variable%TYPE
| table.column%TYPE} [NOT NULL]
| table.%ROWTYPE
[INDEX BY BINARY_INTEGER];identifier type_name;
...
TYPE ename_table_type IS TABLE OFemp.ename%TYPE
INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
...
Example:
Declare an INDEX BY table to store names.
INDEX BY T bl St t
-
8/7/2019 6820436-PLSQL
119/160
INDEX BY Table Structure
Unique identifier Column
... ...
1 JONES
2 SMITH
3 KING
... ...
BINARY_INTEGER Scalar
Example :
-
8/7/2019 6820436-PLSQL
120/160
DECLARE
TYPEIntDataTypIS TABLE OF integer
INDEX BYBINARY_INTEGER;
inttab IntDataTyp;
BEGIN
inttab(1):=10;
inttab(12):=20;
inttab(25):=30;
dbms_output.put_line(inttab(1)||','||inttab(12)||','||inttab(25));
END;
Analyze followingprogram
DECLARE
-
8/7/2019 6820436-PLSQL
121/160
TYPEname_table IS TABLE OF VARCHAR2(100)
INDEX BYBINARY_INTEGER;old_names name_table;
new_names name_table;
BEGIN
old_names(1) := 'Smith';old_names(2) := 'Harry';
new_names(111) := 'Hari';
new_names(342) := 'Bindu';
new_names(500) := 'Simi';old_names := new_names;
DBMS_OUTPUT.PUT_LINE (old_names (1));
END;
Note :No DML (except delete) or transactions can be
implemented on PL/SQL tables
-
8/7/2019 6820436-PLSQL
122/160
p Q
Built-in Functions and Procedures for PL/SQL Tables
Operator Description
COUNT Returns the numberof elements currently contained in the PL/SQL table.
DELETE Deletes one ormore elements from the PL/SQL table.
EXISTS Returns FALSE if a reference to an element at the specified index wouldraise the NO_DATA_FOUND exception.
FIRST Returns the smallest index of the PL/SQL table for which an element is
defined.
LAST Returns the greatest index of the PL/SQL table for which an element is
defined.
NEXT Returns the smallest index of the PL/SQL table containing an element
which is greater than the specified index.
PRIOR Returns the greatest index of the PL/SQL table containing an element which
is less than the specified index.
Deleting rows in PL/SQL tables
-
8/7/2019 6820436-PLSQL
123/160
To delete specific row
.delete()
To delete all the rows
.delete
To delete range of rows.DELETE (start_index_in IN INTEGER,end_index_in IN INTEGER);
DECLARETYPE stringtabtype IS TABLE OF varchar2(15)INDEX BY BINARY_INTEGER;l li t t i t bt
-
8/7/2019 6820436-PLSQL
124/160
playerslist stringtabtype;BEGIN
playerslist(99):='Sachin';
playerslist(10):='Dravid';playerslist(5):='Shewag';playerslist(12):='Ganguly';playerslist(25):='Yuvraj';playerslist(15):='Harbajan';playerslist(19):='Kumble';dbms_output.put_line('Total Players :'||playerslist.count);
FOR i IN playerslist.first..playerslist.last LOOPif playerslist.exists(i) thendbms_output.put_line(i||'.'||playerslist(i));
end if;END LOOP;playerslist.delete(12,19);--deleting range of elementsFOR i IN playerslist.first..playerslist.last LOOP
if playerslist.exists(i) thendbms_output.put_line('Indexes - Prior :'||playerslist.prior(i)||' Next
:'||playerslist.next(i));dbms_output.put_line(i||'.'||playerslist(i));
end if;END LOOP;
END;
INDEX BY Table of Records
-
8/7/2019 6820436-PLSQL
125/160
INDEX BY Table ofRecords
DECLARE
TYPE dept_table_type IS TABLE OF dept%ROWTYPE
INDEX BY BINARY_INTEGER;
dept_table dept_table_type;
-- Each element of dept_table is a recordto refer each field
dept_table(index).field_name must be used
Define a TABLE variable with a permitted PL/SQL data type.
Declare a PL/SQL variable to hold department information.
Examp
le:Examp
le:
Example
-
8/7/2019 6820436-PLSQL
126/160
DECLARETYPE EmpTabTyp IS TABLE OF emp%ROWTYPE
INDEX BY BINARY_INTEGER;emp_tab EmpTabTyp;
BEGINSELECT * INTO emp_tab(7566) FROM emp
WHERE empno = 7566;dbms_output.put_line(emp_tab(7566).ename);END;
-
8/7/2019 6820436-PLSQL
127/160
Nested Tables
nested tables can be considered one-column database tables
-
8/7/2019 6820436-PLSQL
128/160
nested tables can be considered one-column database tables.
oracle stores the rows of a nested table innoparticularorder.whenyou retrieve the nested table into a PL/SQL variable,
the rows are given consecutive subscripts starting at 1. That
gives you array-like access to individual rows.
NESTED ARRAY vs ARRAY
-
8/7/2019 6820436-PLSQL
129/160
Arrays are dense and have a fixed upper bound, but nested
tables are initially dense but become sparse and are unbounded
In arrays you cannot delete elements
Innested table you can delete elements using the built-inprocedure DELETE. That might leave gaps in the index, but
the built-in functionNEXT lets you iterate over any series of
subscri ts.
Understanding Varrays
Items of type VARRAY are called varrays
-
8/7/2019 6820436-PLSQL
130/160
Items of type VARRAY are called varrays.
They allow you to associate a single identifier with an entirecollection. This association lets youmanipulate the collection
as a whole and reference individual elements easily.
To reference an element, youuse standard subscripting syntax
A varray has a maximum size
Defining Collection Types
You can define TABLE andVARRAY types in the declarative
-
8/7/2019 6820436-PLSQL
131/160
You can define TABLE andVARRAY types in the declarative
part of any PL/SQL block, subprogram, orpackage.
Nested Tables
TYPE type_name IS TABLE OF element_type [NOTNULL]
type_name is a type specifierused later to declare collections.element_type is any PL/SQL datatype
Varrays
TYPE type_name IS {VARRAY | VARYINGARRAY} (
size_limit) OF element_type [NOTNULL]
type_name and element_type are the same as fornested tables
size_limitis apositive integer
Example:
DECLARE
-
8/7/2019 6820436-PLSQL
132/160
TYPENumList IS TABLE OF VARCHAR2(12);
nums NumList := NumList(10,20,30);BEGIN
for i in 1..3 loop
DBMS_OUTPUT.PUT_LINE(nums(i));
end loop;nums(1):='A';
nums(2):=60;
nums(3):='welcome';
for i in 1..3 loopDBMS_OUTPUT.PUT_LINE(nums(i));
end loop;
END;
-CREATETYPE PHONE_TYPEAS OBJECT(
PHONE_LOCVARCHAR2(10),
-
8/7/2019 6820436-PLSQL
133/160
PHONE_NO NUMBER(12));
-CREATETYPE PHONE_TABAS TABLE OF
PHONE_TYPE;
-CREATETABLEEMP_PHONE(ENAMEVARCHAR2(12),
PHONE_DETAILS PHONE_TAB)
NESTED TABLE PHONE_DETAILS STOREAS
PHONE_EXTABLE;The NESTEDTABLEclause is required whenever a database
table has a nested table column. The clause identifies the
nested table and names a system-generated store table, in
which Oracle stores the nested table data.
Inserting rows
-
8/7/2019 6820436-PLSQL
134/160
-INSERTINTO EMP_PHONEVALUES('SMITH',
PHONE_TAB(PHONE_TYPE('HOME',12345),PHONE_TYPE('OFF',56789)))
-INSERTINTO EMP_PHONEVALUES('JONES',
PHONE_TAB(PHONE_TYPE('CELL',23456),PHONE_TYPE('OFF',98765),PHONE_TYPE('OFF',99999)))
-SELECT * FROMEMP_PHONE;
-SELECT PHONE_LOC,PHONE_NO FROMTHE(SELECTPHONE_DETAILS FROMEMP_PHONEWHERE
ENAME='SMITH');
Performing DML actions onnested table
-INSERT INTO THE(SELECT PHONE DETAILS FROM
-
8/7/2019 6820436-PLSQL
135/160
INSERTINTO THE(SELECT PHONE_DETAILS FROM
EMP_PHONEWHEREENAME='SMITH')
VALUES('CELL',777777);
-INSERTINTO TABLE(SELECT PHONE_DETAILS FROM
EMP_PHONEWHEREENAME='SMITH')
VALUES('CELL',99999)-UPDATETHE(SELECT PHONE_DETAILS FROM
EMP_PHONEWHEREENAME='SMITH') SET
PHONE_NO=11111 WHERE PHONE_LOC='HOME';
-DELETETHE(SELECT PHONE_DETAILS FROM
EMP_PHONEWHEREENAME='SMITH') WHERE
PHONE_LOC='OFF';
VARRAYS
-
8/7/2019 6820436-PLSQL
136/160
DECLARE
TYPE NumList IS VARRAY(3) OFVARCHAR2(12);
nums NumList := NumList(10,20,30);
BEGIN
for i in 1..3 loop
DBMS_OUTPUT.PUT_LINE(nums(i));
end loop;nums(1):='A';
nums(2):=60;
nums(3):='welcome';
for i in 1..3 loop
DBMS_OUTPUT.PUT_LINE(nums(i));
end loop;
END;
CREATETYPETOOL_TYAS OBJECT (TOOLNAME
VARCHAR2(25));
-
8/7/2019 6820436-PLSQL
137/160
CREATE ORREPLACETYPETOOLS_VAAS VARRAY(5)OF TOOL_TY;
CREATETABLEBORROWER
(NAMEVARCHAR2(25),TOOLS TOOLS_VA);
INSERTINTO BORROWERVALUES ('JED HOPKINS',
TOOLS_VA(TOOL_TY('HAMMER),TOOL_TY('SLEDGE), TOOL_TY('AX)));
SELECT * FROMBORROWER;
SELECT * FROMTHE(SELECTTOOLS FROM
-
8/7/2019 6820436-PLSQL
138/160
BORROWERWHERENAME='JED HOPKINS')
SELECTB.NAME,N.* FROMBORROWER
B,TABLE(B.TOOLS)N;
UPDATEBORROWERSET
TOOLS=TOOLS_VA(TOOL_TY(PLIER'),TOOL_TY(SCREW DRIVER'))
Using cursormethod
DECLARE
C SO O O C SO S S C * O
-
8/7/2019 6820436-PLSQL
139/160
CURSORBORROWER_CURSORIS SELECT * FROM
BORROWER;BEGIN
FORBORROWER_REC INBORROWER_CURSOR
LOOP
DBMS_OUTPUT.PUT_LINE('ContactName:'||borrower_rec.name);
for i in 1..borrower_rec.tools.count
loop
dbms_output.put_line(borrower_rec.tools(i));end loop;
end loop;
end;
Currently, you cannot reference the individual elements of avarray in anINSERT, UPDATE, orDELETE statement. You
i h i PL/SQL d l
-
8/7/2019 6820436-PLSQL
140/160
must retrieve the entire varray, use PL/SQLprocedural
statements to add, delete, orupdate its elements, and then storethe changed varray back in the database table.
Procedure for adding row into varray
CREATE ORREPLACE PROCEDUREADD_TOOLS(BNAMEINVARCHAR2,
NEW_TOOL INTOOL_TY,
POSITIONINNUMBER)AS
MY_TOOLS TOOLS_VA;BEGIN
SELECTTOOLS INTO MY_TOOLS FROMBORROWER
WHERENAME=BNAME FORUPDATE OF TOOLS;
MY_TOOLS.EXTEND;-- make room for new
project
/* M l t f d */
-
8/7/2019 6820436-PLSQL
141/160
/* Move varrayelements forward. */
FORIINREVERSE POSITION..MY_TOOLS.LAST-1LOOP
MY_TOOLS(I+1):=MY_TOOLS(I);
END LOOP;
MY_TOOLS(POSITION):=NEW_TOOL;-- add newproject
UPDATEBORROWERSETTOOLS=MY_TOOLS
WHERENAME=BNAME;
END;
EXECUTEADD_TOOLS('JED HOPKINS',
TOOL_TY('SCREW DRIVER'),2);
Procedure forupdatingVARRAYCREATEor replace PROCEDUREupdate_tools(
bname IN varchar2
-
8/7/2019 6820436-PLSQL
142/160
bname IN varchar2,
oldtoolname IN varchar2,
newtool INVARCHAR2) ASmy_tools tools_va;
BEGIN
SELECT tools INTO my_tools FROM borrowerWHEREname = bname
FOR
UPDATE OF tools;/* Find toos, update it, then exit loop immediately. */
FOR i INmy_tools.FIRST..my_tools.LAST LOOP
IF my_tools(i).toolname = oldtoolname THEN
my_tools(i).toolname:= newtool;
EXIT;END IF;
END LOOP;
UPDATE borrower SET tools = my_tools WHEREname = bname;
END;
-EXECUTEUPDATE_PROJECT('JED HOPKINS','SLEDGE','GIROD');
TRIGGER
-
8/7/2019 6820436-PLSQL
143/160
A trigger:
Is a PL/SQL block or a PL/SQL procedureassociated with a table, view, schema, or thedatabase
Executes implicitly whenever a particular event
takes place
USES OF TRIGGERS
Triggers may be used to
-
8/7/2019 6820436-PLSQL
144/160
gg y
-supplement declarative referential integrity.
-enforce complex business rules.
-audit change to data.
-monitor database related actions.
Creating DML Triggers
-
8/7/2019 6820436-PLSQL
145/160
A triggering statement contains:
Trigger timing
For table: BEFORE, AFTER
For view: INSTEAD OF
Triggering event: INSERT/UPDATE/DELETE
Table name: On table, view
Trigger type: Row or statement
WHEN clause: Restricting condition
Trigger body: PL/SQL block
DML Trigger Components
-
8/7/2019 6820436-PLSQL
146/160
Trigger timing: When should the trigger fire?
BEFORE: Execute the trigger body before thetriggering DML event on a table.
AFTER: Execute the trigger body after thetriggering DML event on a table.
INSTEAD OF: Execute the trigger body insteadof the triggering statement. This is used forviews that are not otherwise modifiable.
DML Trigger Components
Triggering user event: Which DML statement
-
8/7/2019 6820436-PLSQL
147/160
Triggering user event: Which DML statementcauses the trigger to execute?
You can use any of the following:
INSERT
UPDATE
DELETE
DML Trigger Components
-
8/7/2019 6820436-PLSQL
148/160
Trigger type: Should the trigger body execute
for each row the statement affects or onlyonce?
Statement: The trigger body executes once forthe triggering event. This is the default. A
statement trigger fires once, even if no rowsare affected at all.
Row: The trigger body executes once for eachrow affected by the triggering event. A row
trigger is not executed if the triggering eventaffects no rows.
DML Trigger Components
-
8/7/2019 6820436-PLSQL
149/160
Trigger body: What action should the triggerperform?
The trigger body is a PL/SQL block or a call to aprocedure.
Syntax for Creating
DML Statement Triggers
-
8/7/2019 6820436-PLSQL
150/160
CREATE [OR REPLACE] TRIGGERtrigger_nametimingevent1[ORevent2ORevent3]
ONtable_nametrigger_body
Note: Trigger names must be unique withrespect to other triggers in the same schema.
Syntax:
DML Statement Triggers
CREATE OR REPLACE TRIGGER secure_empBEFORE INSERT or UPDATE or DELETE ON emp
Example:
-
8/7/2019 6820436-PLSQL
151/160
BEFORE INSERT or UPDATE or DELETE ON empBEGIN
IF (TO_CHAR(SYSDATE,'DY') IN ('SAT','SUN')) OR(TO_CHAR(SYSDATE,'HH24:MI')NOT BETWEEN '08:00' AND '18:00')THEN RAISE_APPLICATION_ERROR (-20500,
'DML allowed only during business hours.');END IF;
END;/
CREATE OR REPLACE TRIGGER secure_empBEFORE INSERT OR UPDATE OR DELETE ON emp
Using Conditional Predicates
-
8/7/2019 6820436-PLSQL
152/160
BEFORE INSERT ORUPDATE OR DELETE ON empBEGIN
IF (TO_CHAR (SYSDATE,'DY') IN ('SAT','SUN')) OR(TO_CHAR (SYSDATE, 'HH24') NOT BETWEEN '08' AND '18')THENIF DELETING THEN
RAISE_APPLICATION_ERROR (-20502,'You may delete fromEMP table only during business hours.');
ELSIF INSERTING THEN
RAISE_APPLICATION_ERROR (-20500,'You may insert intoEMP table only during business hours.');
ELSIF UPDATING THENRAISE_APPLICATION_ERROR (-20504,'You may update
EMP table only during normal hours.');END IF;END IF;
END;
Creating a DML Row Trigger
-
8/7/2019 6820436-PLSQL
153/160
CREATE [OR REPLACE] TRIGGERtrigger_name
timing
event1[ORevent2ORevent3]
ON table_name
[REFERENCING OLD AS old| NEW AS new]
FOR EACH ROW
[WHEN (condition)]
trigger_body
Using OLD and NEW Qualifiers
Within a ROW trigger reference the value of a column
-
8/7/2019 6820436-PLSQL
154/160
Within a ROW trigger, reference the value of a columnbefore and after the data change by prefixing it with the
OLD and NEW qualifier.
The OLD and NEW qualifiers are available only in ROWtriggers.
Prefix these qualifiers with a colon (:) in every SQL and
PL/SQL statement.There is no colon (:) prefix if the qualifiers arereferenced in the WHEN restricting condition.
Note: Row triggers can decrease the performance if you doa lot of updates on larger tables.
Fires when DML is performed onEMP table
CREATE OR REPLACE TRIGGER Print salary changes
-
8/7/2019 6820436-PLSQL
155/160
CREATE ORREPLACETRIGGERPrint_salary_changes
BEFOREINSERT ORUPDATE ONEmpFOREACH ROW
WHEN (new.Empno > 0)
DECLARE
sal_diffnumber;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;
-
8/7/2019 6820436-PLSQL
156/160
Creating anINSTEAD OF Trigger
-
8/7/2019 6820436-PLSQL
157/160
CREATE [OR REPLACE] TRIGGERtrigger_nameINSTEAD OFevent1[ORevent2ORevent3]ON view_name
[REFERENCING OLD AS old| NEW AS new][FOR EACH ROW]trigger_body
Syntax:
INSTEAD OF Trigger Example
CREATE ORREPLACEVIEWEMPDEPTVIEW
AS
SELECTEMPNO,ENAME,JOB,SAL,E.DEPTNO,DNAME,LOC
FROM EMP E DEPTD WHERE E DEPTNO=D DEPTNO;
-
8/7/2019 6820436-PLSQL
158/160
FROMEMP E,DEPTD WHEREE.DEPTNO D.DEPTNO;
CREATE ORREPLACETRIGGERINSTEADTRIGINSTEAD OF INSERT ONEMPDEPTVIEW
FOREACH ROW
DECLARE
dnos NUMBER(2);
BEGIN
IF INSERTINGTHEN
SELECT COUNT(*) INTO dnos FROM DEPTWHERE DEPTNO=:NEW.DEPTNO;IF dnos=0 THEN
INSERTINTO DEPTVALUES(:NEW.DEPTNO,:NEW.DNAME,:NEW.LOC);
INSERTINTO EMP(EMPNO,ENAME,JOB,SAL,DEPTNO)
VALUES(:NEW.EMPNO,:NEW.ENAME,:NEW.JOB,:NEW.SAL,:NEW.DEPTNO);
ELSE
INSERTINTO EMP(EMPNO,ENAME,JOB,SAL,DEPTNO)
VALUES(:NEW.EMPNO,:NEW.ENAME,:NEW.JOB,:NEW.SAL,:NEW.DEPTNO);END IF;
END IF;
EXCEPTION
WHENothers THEN
dbms_output.put_line('Exceptionoccurred.');
END;
Altering triggers
ALTER TRIGGER trigger_name ENABLE|DISABLE;
-
8/7/2019 6820436-PLSQL
159/160
ALTER TABLE table_name ENABLE|DISABLE alltriggers;
Dropping triggers:
DROP TRIGGER trigger_name;
The following data dictionary views revealinformation about triggers:
- USER_TRIGG
ERS
-
8/7/2019 6820436-PLSQL
160/160