Advanced PLSQL - Updated
Advanced PLSQL - Updated
Advanced PLSQL - Updated
1
Topics
Benefits of PL/SQL
Variable Types
Benefits of subprograms
Advanced Cursors
Dynamic SQL
Object Oriented Oracle
Debugging and Error Handling
PL/SQL Tuning
2
.
Benefits of PL/SQL
3
Benefits of PL/SQL
4
PL/SQL Execution Environment
Oracle
SGA
PL/SQL
Application Compiler
pvm
database
(Stored procedure
Mcode )
Application:
• Anonymous PL/SQL block
• Stored Procedure
5
.
Advanced Cursors
7
Advanced Cursors
Cursor Types
• Implicit cursors
Declared for all DML and PL/SQL SELECT statements
• Explicit cursors
Explicit cursors are declared and named by the programmer and
manipulated through specific statements in the block’s
executable actions.
• Parameterized cursors
8
Advanced Cursors
Controlling Explicit Cursors No
Yes
Declare Open Fetch Empty Close
Cursor Attributes
%NotFound - Evaluates to TRUE if most recent fetch does not return a row
%Found – Evaluates to TRUE if the fetch returns a row
%Rowcount – Total number of rows returned so far
9
Advanced Cursors
10
Advanced Cursors
11
Advanced Cursors
12
.
Dynamic SQL
13
Dynamic SQL
14
Native Dynamic SQL Vs DBMS_SQL
DBMS_SQL
1. performing simple operations requires a large amount of code when you use the
DBMS_SQL package.
2. procedures and functions that must be used in a strict sequence.
3. Does not support these user-defined types
15
DBMS_SQL Package
DBMS_SQL package
The DBMS_SQL package is used to write dynamic SQL in stored procedures and to parse DDL
statements.
Some of the procedures and functions of the package include:
OPEN_CURSOR - Opens a new cursor and assigns a cursor ID number
PARSE - Parses the DDL or DML statement
BIND_VARIABLE - Binds the given value to the variable identified by its name in the parsed
. statement in the given cursor
EXECUTE - Executes the SQL statement and returns the number of rows processed
FETCH_ROWS - Retrieves a row for the specified cursor (for multiple rows, call in a loop)
CLOSE_CURSOR - Closes the specified cursor
16
DBMS_SQL example
17
EXECUTE IMMEDIATE statement
INTO is used for single-row queries and specifies the variables or records into
which column values are retrieved.
USING is used to hold all bind arguments. The default parameter mode is IN.
18
Bind Variables
Bind variables allows Oracle to share a single cursor for multiple
SQL statements.
19
Execute Immediate
Dynamic Single-Row Query
CREATE OR REPLACE FUNCTION get_num_of_employees (loc VARCHAR2,
. job VARCHAR2)
RETURN NUMBER IS
query_str VARCHAR2(1000);
num_of_employees NUMBER;
BEGIN
query_str := 'SELECT COUNT(*) FROM '
|| ' emp_' || loc || ' WHERE job = :job_title';
EXECUTE IMMEDIATE query_str
INTO num_of_employees
USING job;
RETURN num_of_employees;
END;
20
Execute Immediate
Dynamic Multiple-Row Query
CREATE OR REPLACE PROCEDURE list_employees(loc VARCHAR2,
. job VARCHAR2) IS
TYPE cur_typ IS REF CURSOR;
c cur_typ;
query_str VARCHAR2(1000);
emp_name VARCHAR2(20);
emp_num NUMBER;
BEGIN
query_str := 'SELECT ename, empno FROM emp_' || loc
|| ' WHERE job = :job_title';
OPEN c FOR query_str USING job;
LOOP FETCH c INTO emp_name, emp_num;
EXIT WHEN c%NOTFOUND;
END LOOP;
CLOSE c;
END;
21
Bulk Dynamic SQL
Bulk SQL is the ability to process multiple rows of data in a single DML statement.
Bulk SQL improves performance by reducing the amount of context switching between SQL and
the host language.
DBMS_SQL package supports bulk dynamic SQL.
Bulk SQL Simulation for Native Dynamic SQL
Create TYPE name_array_type IS
VARRY(100) of VARCHAR2(50);
CREATE OR REPLACE PROCEDURE copy_ename_column (table1 VARCHAR2,
table2 VARCHAR2) IS
ename_col NAME_ARRAY_TYPE;
BEGIN
EXECUTE IMMEDIATE 'BEGIN SELECT ename BULK COLLECT INTO :tab FROM ' || table1 || '; END;'
USING OUT ename_col;
EXECUTE IMMEDIATE 'BEGIN FORALL i IN :first .. :last INSERT INTO ' || table2 || ' VALUES (:tab(i)); END;'
USING ename_col.first, ename_col.last, ename_col;
END;
22
DML Returning Example
DML Returning Example
BEGIN
stmt_str := 'UPDATE dept_new SET loc = :newloc
WHERE deptno = :deptno
RETURNING dname INTO :dname’;
EXECUTE IMMEDIATE stmt_str
USING location, deptnumber, OUT deptname;
END;
Fetching Into Records
DECLARE
TYPE EmpCurTyp IS REF CURSOR;
c EmpCurTyp;
emp_rec emp%ROWTYPE;
stmt_str VARCHAR2(200);
e_job emp.job%TYPE;
BEGIN
stmt_str := 'SELECT * FROM emp WHERE job = :1';
OPEN c FOR stmt_str USING 'MANAGER';
LOOP FETCH c INTO emp_rec;
EXIT WHEN c%NOTFOUND;
END LOOP;
CLOSE c;
-- in a single-row query
EXECUTE IMMEDIATE stmt_str INTO emp_rec USING 'PRESIDENT'; END;
23
Collections
Collection Types
Associative Arrays
VArrays
Nested Tables
Associative Arrays
• Elements using number and strings for subscript values.
Syntax
TYPE <<type_name >> IS TABLE OF << element_type >>
INDEX BY [PLS_INTEGER | BINARY_INTEGER | VARCHAR2(size_limit)];
24
Collections
25
Collections
Nested Tables
Holds an arbitrary number of elements
Unbounded
Column type in database that store a set of values
Simplifies the SQL operations
Syntax
TYPE << type_name>> IS TABLE OF << element_type >> [NOT NULL];
Example :
Declare
TYPE nested_type IS TABLE OF VARCHAR2(20);
v1 nested_type;
BEGIN
v1 := nested_type('Arbitrary','number','of','strings');
Dbms_output.put_line (v1(1));
END;
26
Collections
Varrays
Fixed number of elements
Bounded
Syntax
TYPE < type_name >> IS {VARRAY | VARYING ARRAY} (size_limit) OF <<element_type
>> [NOT NULL];
Example :
Declare
Type colors IS VARRAY(10) OF VARCHAR2(16);
rainbow colors;
BEGIN
rainbow := Colors('Red','Orange','Yellow','Green','Blue','Indigo','Violet');
dbms_output.put_line (rainbow(1));
END;
27
Collections
Collection Methods
1. EXISTS
2. COUNT
3. LIMIT
4. FIRST and LAST
5. PRIOR and NEXT
6. EXTEND
7. TRIM
8. DELETE
Restrictions:
Collection can not be called from SQL statements
EXTEND and TRIM can not be used with associated arrays
28
Collections
Collection Exception
COLLECTION_IS_NULL Operation on NULL Collection.
29
Multi Collections
Varray
Declare
Type t1 is varray(10) of integer;
Type nt1 is varray (10) of t1;
Va t1 := t1(2,3,5);
Nva nt1 := nt1( va , t1(55, 6, 73), t1(2,4) , va );
BEGIN
dbms_output.put_line( nva(2)(3) ); -- Gives value 73
nva(4) := t1(45,43,67,43345);
Nva(4).extend;
Nva(4)(5) := 100;
END;
30
Multi Collections
Nested Tables
DECLARE
type tb1 is table of varchar2(20);
type ntb1 is table of tb1;
type tv1 is varray(10) of integer;
type ntb2 is table of tv1;
vtb1 tb1 := tb1('one', 'three');
vntb1 ntb1 := ntb1(vtb1);
vntb2 ntb2 := ntb2(tv1(3,5), tv1(5,7,3));
BEGIN
vntb1.extend;
vntb1(2) := vntb1(1);
vntb1.delete(1);
vntb1(2).delete(1);
END;
31
Multi Collections
Associated Arrays
DECLARE
type tb1 is table of integer index by binary_integer;
type ntb1 is table of tb1 index by binary_integer;
type va1 is varray(10) of varchar2(20);
type ntb2 is table of va1 index by binary_integer;
v1 va1 := va1('hello', 'world');
v2 ntb1;
v3 ntb2;
v4 tb1;
v5 tb1; -- empty table
BEGIN
v2(35) := v5;
v2(35)(2) := 78;
END;
32
Bulk Binding
Categories :
FORALL
Data passed from the PL/SQL engine to the SQL engine to execute INSERT,
UPDATE, and DELETE statements.
FORALL index IN lower_bound..upper_bound
sql_statement;
BULK COLLECT
Data passed from the SQL engine to the PL/SQL engine as a result of
SELECT or FETCH statements.
... BULK COLLECT INTO collection_name
33
Bulk Binding
FORALL Error Handling
SAVE EXCEPTIONS
SQL%BULK_EXCEPTIONS – Collection of records
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX – stores iteration when exception
is raised.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE - stores Oracle error code.
Example :
BEGIN
--
FORALL i IN 1..l_data.COUNT SAVE EXCEPTIONS
--
Exception
When Others Then
errors := SQL%BULK_EXCEPTIONS.COUNT;
34
PL/SQL Record
record is a group of related data items stored in fields.
Syntax
TYPE < record name > IS RECORD << Fields with data types >>;
Restrictions
Nested Record Types
Functions that returns a record
Record update/ insert using EXECUTE IMMEDIATE Statement
35
PL/SQL Record Example
DECLARE
TYPE EmpRec IS RECORD (last_name employees.last_name%TYPE, salary employees.salary%TYPE);
dept_info dept%ROWTYPE;
BEGIN
dept_info.deptno := 70;
dept_info.department_name := 'PERSONNEL';
dept_info.loc := 'DALLAS';
INSERT INTO dept VALUES dept_info;
dept_info.loc := ‘NEW YORK';
- - To update entire row
UPDATE dept SET ROW = dept_info WHERE deptno = 70;
- - RETURNING Clause
UPDATE employees SET salary = salary * 1.1 WHERE employee_id = 100
RETURNING last_name, salary INTO emp_info;
END;
36
.
37
Debugging and Error Handling
Exception Management
38
Debugging and Error Handling
Exception Management
Exception Types
Exception Description Directions for Handling
Predefined Oracle One of approximately 20 Do not declare and allow the Oracle
Server error, also errors that occur most Server to raise then implicitly
called named system often in PL/SQL code
exceptions
39
Debugging and Error Handling
Exception Propagation
When a sub block handles an exception, it terminates normally, and control resumes in
the enclosing block immediately after the sub block END statement.
However, if PL/SQL raises an exception and the current block does not have a handler
for that exception, the exception propagates in successive enclosing blocks until it finds
a handler. If none of these blocks handle the exception, an unhandled exception in the
host environment results.
When the exception propagates to an enclosing block, the remaining executable actions
in that block are bypassed.
40
User Defined Exceptions
1. Declare
2. Raise
3. Reference
Declare
V_exception EXCEPTION;
Begin
<< block logic >>
RAISE v_exception;
EXCEPTION
WHEN v_exception THEN
<< exception logic >>
END;
41
Debugging and Error Handling
PRAGMA EXCEPTION_INIT
DECLARE
e_emps_remaining EXCEPTION;
PRAGMA EXCEPTION_INIT (e_emps_remaining, -2292);
BEGIN
<< block logic >>
EXCEPTION
WHEN e_emps_remaining THEN
DBMS_OUTPUT.PUT_LINE ('Cannot remove dept '|| TO_CHAR(v_deptno) ||
'. Employees exist. ');
END;
RAISE_APPLICATION_ERROR
Raise_application_error (error_number, message);
user specified number for the exception between –20000 and –20999.
Functions for Trapping Exceptions
SQLCODE : Returns the numeric value for the error code
SQLERRM : Returns the message associated with the error num
42
Global Temporary Tables
The data in a temporary table is private for the session that created.
It and can be session-specific or transaction-specific.
transaction Specific
CREATE GLOBAL TEMPORARY TABLE temp_table ( column1 NUMBER,
column2 NUMBER)
ON COMMIT DELETE ROWS;
Session Specific
CREATE GLOBAL TEMPORARY TABLE temp_table (column1 NUMBER,
column2 NUMBER)
ON COMMIT PRESERVE ROWS;
Features
• TRUNCATE - session specific data is truncated.
• Data automatically deleted at the end of the session
• Index , Views creation on Temporary tables
43
UTL_FILE
44
UTL_FILE Processing
Yes
Get line from
Text file
No Close the
Open the More Lines to Text file
Text file Process
Put lines into
Text file
45
UTL_FILE Procedures and Functions
FOPEN A function that opens a file for input or output and returns a file
handle used in subsequent I/O operations
IS_OPEN A function that returns a Boolean value whenever a file handle refers
to an open file
GET_LINE A procedure that reads a line of text from the opened file and places
the text in the output buffer parameter
PUT_LINE procedure that writes a text string stored in the buffer parameter to the
opened file
NEW_LINE Procedure that terminates a line in an output file
FFLUSH Procedure that writes all data buffered in memory to a file
FCLOSE Procedure that closes an opened file
FCLOSE_ALL Procedure that closes all opened file handles for the session
46
UTL_FILE Exceptions
47
UTL_FILE Example
48
.
Sub programs
49
Benefits of Subprograms
Easy Maintenance
- Modify routines online without interfering with other users
- Modify one routine to affect multiple applications
- Modify one routine to eliminate duplicate testing
Improved data security and Integrity
- Control indirect access to database objects from nonprivileged users with security
privileges.
- Ensure that related actions are performed together.
Improved performance
- Avoid reparsing for multiple users by exploiting the shared SQL area
- Avoid PL/SQL parsing at run time by parsing at compile time
- Reduce the number of calls to the database and decrease network traffic by bundling
commands.
Improved code clarity
- appropriate identifier names to describe the action of the routines reduces the need for
comments and enhances the clarity of the code.
50
Autonomous Block
51
Autonomous Vs Nested Transactions
52
Definer's Rights and Invoker’s Rights
Definer's Right
A routine stored in the database by default, is executed with the owner of the routine
depending on the user who calls it.
It gives better control, preventing direct access to objects that belong to another user.
Invoker’s Rights
multiple schemas, accessing only those elements belonging to the invoker, can share the
same piece of code.
AUTHID CURRENT_USER clause required in the routine for invoker right
Ex : Schema : A and B
Table : emp_rec created in schema A
Procedure : emp_rec_prc created in schema A
53
Invoker Rights
Restrictions
1. AUTHID is specified in the header of a program unit. The same cannot be
specified for individual programs or methods within a package or object type.
2. Definer rights will always be used to resolve any external references when
compiling a new routine.
3. For an invoker rights routine referred in a view or a database trigger, the owner
of these objects is always considered as the invoker, and not the user triggering it.
External References
SELECT, INSERT, UPDATE, and DELETE data manipulation statements
The LOCK TABLE transaction control statement
OPEN and OPEN-FOR cursor control statements
EXECUTE IMMEDIATE and OPEN-FOR-USING dynamic SQL statements
54
LOB Data Types
55
LOB vs. LONG
LOB LONG
Multiple LOB columns per table Single LONG column per table
Up to 4 GB Up to 2 GB
56
Migrating from LONG to LOB
Implicit conversion:
LONG or a VARCHAR2(RAW) variable to a CLOB (BLOB) variable
Explicit conversion:
– TO_CLOB() converts LONG, VARCHAR2, and CHAR to CLOB
– TO_BLOB() converts LONG RAW and RAW to BLOB
Function and Procedure Parameter Passing:
– CLOBs and BLOBs as actual parameters
– VARCHAR2, LONG, RAW, and LONG RAW are formal parameters
57
DBMS_LOB Package
58
DBMS_LOB.READ and DBMS_LOB.WRITE
59
LOB Updation Example
DECLARE
lobloc CLOB;
text VARCHAR2(32767):= 'Resigned: 5 August 2000';
amount NUMBER ; -- amount to be written
offset INTEGER; -- where to start writing
BEGIN
SELECT resume INTO lobloc FROM employees
WHERE employee_id = 405 FOR UPDATE;
offset := DBMS_LOB.GETLENGTH(lobloc) + 2;
amount := length(text);
DBMS_LOB.WRITE (lobloc, amount, offset, text );
text := ' Resigned: 30 September 2000';
SELECT resume INTO lobloc FROM employees
WHERE employee_id = 170 FOR UPDATE;
amount := length(text);
DBMS_LOB.WRITEAPPEND(lobloc, amount, text);
END;
60
Temporary Lobs
Temporary LOB’s:
– Provide an interface to support creation of LOB’s
that act like local variables
– Can be BLOB, CLOB, or NCLOB
– Are not associated with a specific table
– Are created using DBMS_LOB.CREATETEMPORARY
– Use DBMS_LOB routines
The lifetime of a temporary LOB is a session.
Temporary LOB’s are useful for transforming data in permanent
internal LOB’s.
61
Creating a Temporary LOB
62
BFILE
63
Loading BFILE
CREATE OR REPLACE PROCEDURE load_emp_bfile (p_file_loc IN VARCHAR2) IS
v_file BFILE;
v_filename VARCHAR2(16);
CURSOR emp_cursor IS
SELECT first_name FROM employees
WHERE department_id = 60 FOR UPDATE;
BEGIN
FOR emp_record IN emp_cursor LOOP
v_filename := emp_record.first_name || '.bmp';
v_file := << File location name >>
DBMS_LOB.FILEOPEN(v_file);
UPDATE employees SET emp_video = v_file
WHERE CURRENT OF emp_cursor;
DBMS_LOB.FILECLOSE(v_file);
END LOOP;
END load_emp_bfile;
/
64
SQL *Loader Concepts
SQL*Loader Basics
SQL*Loader Control File
Input Data and Datafiles
Data Conversion and Datatype Specification
Discarded and Rejected Records
Log File and Logging Information
65
.
66
SQL*Loader Basics
67
SQL*Loader Basics
SQL*Loader Features:
Load data from multiple input data files of different file types
Handle fixed-format, delimited-format, and variable-length records
Manipulate data fields with SQL functions before inserting the data into
database columns
Load multiple tables during the same run, loading selected rows into
each table
Combine multiple physical records into a single logical record
Handle a single physical record as multiple logical records
Generate unique, sequential key values in specified columns
68
Control File
69
Bad File
The bad file contains records rejected, either by SQL*Loader or by Oracle.
Record
Read In
SQL*Loader
Field Processing
Accepted
SQL*Loader Bad
When-Clause Evaluation File
Discard
File selected
RDBMS
Inserted
Database
70
Loading Methods
INSERT -- table to be empty before loading.
APPEND -- appends the new rows to it.
REPLACE -- All rows in the table are deleted and the new data is loaded.
TRUNCATE
Reserved words
COUNT DATA DATE FORMAT
OPTIONS PART POSITION
72
Case 2 : Loading Fixed-Format Fields
LOAD DATA
INFILE ’ case2.dat’
INTO TABLE emp
(empno POSITION(01:04) INTEGER EXTERNAL,
ename POSITION(06:15) CHAR,
job POSITION(17:25) CHAR,
mgr POSITION(27:30) INTEGER
EXTERNAL,
sal POSITION(32:39) DECIMAL
EXTERNAL,
comm POSITION(41:48) DECIMAL
EXTERNAL,
deptno POSITION(50:51) INTEGER EXTERNAL)
Data file
782 CLARK MANAGER 7839 2572.50 10
7839 KING PRESIDENT 5500.00 10
7934 MILLER CLERK 7782 920.00 10
73
Case 3 : Loading Delimited File
LOAD DATA
INFILE *
APPEND
INTO TABLE emp
FIELDS TERMINATED BY ”,” OPTIONALLY ENCLOSED BY ’”’
(empno, ename, job, mgr,
hiredate ”DD-Month-YYYY”,
sal, comm, deptno CHAR TERMINATED BY ’:’,
projno,
loadseq SEQUENCE(MAX,1))
BEGINDATA
7782, ”Clark”, ”Manager”, 7839, 09-June-1981, 2572.50,,
10:101
7839, ”King”, ”President”, , 17-November-
1981,5500.00,,10:102
74
Case 4: Loading Combined Physical Records
LOAD DATA
INFILE ’ case4.dat’
DISCARDFILE ’ case4.dsc’
DISCARDMAX 999
REPLACE
CONTINUEIF THIS (1) = ’*’
INTO TABLE emp
(empno POSITION(1:4) INTEGER
EXTERNAL,
ename POSITION(6:15) CHAR,
job POSITION(17:25) CHAR,
mgr POSITION(27:30) INTEGER
EXTERNAL,
sal POSITION(32:39) DECIMAL
EXTERNA )
Case4.dat
*7782 CLARK
MANAGER 7839 2572.50
*7839 KING
PRESIDENT 5500.00 75
Case 5: Loading Data into Multiple Tables
LOAD DATA
INFILE ’case5.dat’
DISCARDFILE ’case5.dsc’
REPLACE
INTO TABLE emp
( empno POSITION(1:4) INTEGER EXTERNAL,
ename POSITION(6:15) CHAR,
deptno POSITION(17:18) CHAR,
mgr POSITION(20:23) INTEGER EXTERNAL)
INTO TABLE proj
WHEN projno != ’ ’
(empno POSITION(1:4) INTEGER EXTERNAL,
projno POSITION(25:27) INTEGER EXTERNAL) -- 1st proj
INTO TABLE proj
WHEN projno != ’ ’
(empno POSITION(1:4) INTEGER EXTERNAL,
projno POSITION(29:31 INTEGER EXTERNAL) -- 2nd proj
76
TRAILING NULLCOLS Clause
SQL Loader treat any relatively positioned columns that are not present in the
record as null columns.
DATA
10 Accounting
77
Generating Data
CONSTANT
Column_name CONSTANT <<value >>
RECNUM
column_name RECNUM
SYSDATE
column_name SYSDATE
SEQUENCE
column_name SEQUENCE ( n , <<Increment >> )
column_name SEQUENCE ( MAX , <<Increment >> )
column_name SEQUENCE ( COUNT , <<Increment >> )
78
SQL Operators to Fields
1. LOAD DATA
INFILE *
APPEND INTO TABLE temp_tab
( LAST position(1:7) char "UPPER(:LAST)",
FIRST position(8:15) char "UPPER(:FIRST)“
)
BEGINDATA
Phil Locke
Jason Durbin
2. Field_1 POSITION(1:4) INTEGER EXTERNAL
"decode(:field2, ’22’, ’34’, :field1)”
79
SQL*Loader Command Line
80
Concurrent Program Creation
81
.
Thank You
82