Вы находитесь на странице: 1из 81

.

Advanced PL/SQL Programming

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

• Design features of programming languages


• Variable Types
• Block Structure
• Portability
• Error handling

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

Create a Identify the Load the Test for Release the


named SQL active set current row existing rows active set
area into
variables

Cursor Attributes

%Isopen - Evaluates TRUE if the cursor is open

%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

For Update Clause


• Use explicit locking to deny access for the duration of a transaction.
• Lock the rows before update or delete

CURSOR <Cursor name >


SELECT < columns>
FROM < tables >
FOR UPDATE < Column_reference > NOWAIT;

Column_reference  columns in the table against which the query is performed.


NOWAIT  returns an oracle error if the rows are locked by another session

10
Advanced Cursors

Where Current of clause


• Use cursors to update or delete the current row.
• Include the FOR UPDATE clause in the cursor query to lock the rows first.
• Use the WHERE CURRENT OF clause to reference the current row from an
explicit cursor.

UPDATE < table name >


SET <column name> = < value >
WHERE CURRENT OF < cursor name>;

11
Advanced Cursors

Cursors with Subqueries


DECLARE
CURSOR my_cursor IS
SELECT t1.department_id, t1.department_name, t2.staff
FROM departments t1, (SELECT department_id,
COUNT(*) AS STAFF
FROM employees
GROUP BY department_id) t2
WHERE t1.department_id = t2.department_id
AND t2.staff >= 3;
...

12
.

Dynamic SQL

13
Dynamic SQL

• Static SQL statements do not change from execution to


execution.
• Dynamic SQL is a programming technique that enables
you to build SQL statements dynamically at runtime.

Methods for using dynamic SQL within PL/SQL


• DBMS_SQL package
• Native dynamic SQL

14
Native Dynamic SQL Vs DBMS_SQL

Native dynamic SQL


1. Enables you to place dynamic SQL statements directly into PL/SQL code.
2. Use EXECUTE IMMEDIATE statement for single row query.
3. Use OPEN-FOR , FETCH ,CLOSE statements for multi row query.
4. Provides support for user-defined types, such as objects, collections, and REFs

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

CREATE OR REPLACE PROCEDURE delete_all_rows


(p_tab_name IN VARCHAR2,
p_rows_del OUT NUMBER)
IS
cursor_name INTEGER;
BEGIN
cursor_name := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cursor_name, 'DELETE FROM '||p_tab_name,
DBMS_SQL.NATIVE );
p_rows_del := DBMS_SQL.EXECUTE (cursor_name);
DBMS_SQL.CLOSE_CURSOR(cursor_name);
END;

17
EXECUTE IMMEDIATE statement

EXECUTE IMMEDIATE dynamic_string


[INTO {define_variable , define_variable] ... | record}]
[USING [IN|OUT|IN OUT] bind_argument
[, [IN|OUT|IN OUT] bind_argument] ... ];

 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.

With out bind variables


EXECUTE IMMEDIATE 'DELETE FROM dept WHERE deptno = ' || to_char (my_deptno);
Each distinct my_deptno variable, a new cursor is created, which can cause resource
contention and poor performance.

With Bind Variables


EXECUTE IMMEDIATE 'DELETE FROM dept WHERE deptno = :1' USING my_deptno;
same cursor is reused for different values of the bind my_deptno, thereby improving
performance and scalability.

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

Associated Arrays Example


Declare
TYPE array_num_type IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
TYPE array_str_type IS TABLE OF VARCHAR2(32) INDEX BY PLS_INTEGER;
TYPE array_str_type2 IS TABLE OF VARCHAR2(32) INDEX BY VARCHAR2(64);
v3 array_num_type;
v4 array_str_type;
v5 array_str_type2;
BEGIN
v3(99) := 10;
v3(7) := 100;
v4(42) := 'Cat';
v4(54) := 'Hat';
v5('Canada') := 'North America';
v5('Greece') := 'Europe';
END;

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.

NO_DATA_FOUND subscript designates an element that


was deleted, or a nonexistent element
of an associative array.

SUBSCRIPT_BEYOND_COUNT a subscript exceeds the number of


elements in a collection

SUBSCRIPT_OUTSIDE_LIMIT a subscript is outside the allowed range

VALUE_ERROR a subscript is null or not convertible to


the key type

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

 binding of an entire collection at once


 performance improve ness

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;

FOR i IN 1 .. Errors LOOP


dbms_output.put_line('Error #' || i || ' at '|| 'iteration
#' || SQL%BULK_EXCEPTIONS(i).ERROR_INDEX);
dbms_output.put_line('Error message is ' ||
SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
END LOOP;
END;

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
.

Debugging and Error Handling

37
Debugging and Error Handling
Exception Management

Types of PL/SQL Errors

Error Type When Reported How Handled

Compile-time, or PL/SQL compiler Interactively: compiler


syntax error reports errors, and you have
to correct them.

Run-time PL/SQL run-time Programmatically:


engine exceptions are raised and
caught by exception
handlers.

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

Non-predefined Any other standard Oracle Declare within the declarative


Oracle Server error, Server error section and allow the Oracle Server
also called unnamed to raise them implicitly
system exceptions

Programmer-defined An error that is defined by Declare within the declarative


error the developer. For section and raise explicitly
example, negative
balance in account.

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

 Extends I/O to text files within PL/SQL


 Provides security for directories on the server through
init.ore file
 similar to standard operating system I/O
– Open files
– Get text
– Put text
– Close files
– Use the exceptions specific to the UTL_FILE package

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

INVALID_PATH file location or filename was invalid.

INVALID_MODE The OPEN_MODE parameter in FOPEN was invalid.

INVALID_FILEHANDLE The file handle was invalid.

READ_ERROR operating system error occurred during the read


operation.
WRITE_ERROR operating system error occurred during the write
operation.

47
UTL_FILE Example

CREATE OR REPLACE PROCEDURE sal_status


(p_filedir IN VARCHAR2, p_filename IN VARCHAR2)
IS
v_filehandle UTL_FILE.FILE_TYPE;
BEGIN
v_filehandle := UTL_FILE.FOPEN (<<file_dir>>, << file_name>>,'w');
--
UTL_FILE.PUT_LINE (v_filehandle, ‘Example ');
UTL_FILE.FCLOSE (v_filehandle);
EXCEPTION
WHEN UTL_FILE.WRITE_ERROR THEN
RAISE_APPLICATION_ERROR (-20002, 'Unable to write to file');
END;

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

An autonomous transaction is an independent transaction started by another


transaction, the main transaction. Autonomous transactions let you suspend the main
transaction, do SQL operations, commit or roll back those operations, then resume the
main transaction.
Advantages
 Fully independent
 shares no locks , resources , commit dependencies
 Transaction control statements in Triggers ( autonomous triggers)
Define Autonomous Transaction
 Use Pre compiler directive AUTONOMOUS_TRANSACTION
 Code in declaration section of a routine
PRAGMA AUTONOMOUS_TRANSACTION;
Restrictions
 Can not use the pragma to mark all subprograms in a package as autonomous.
 Cannot mark a nested PL/SQL block as autonomous

51
Autonomous Vs Nested Transactions

Autonomous Nested Transactions


Does not share the Shares the transaction
transaction resources with resources with main
main transaction transaction
not depend on the main Depends on main
transaction transaction

Committed changes are Committed changes are not


visible to other transactions visible to other transactions
immediately until main transaction
commits

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

 Stores unstructured data such as text, graphic images, films,


and sound waveforms.

• CLOB - large blocks of single-byte character data in the database.


• BLOB - store large binary objects in the database.
• BFILE - store large binary objects in operating system files outside the database.

• NCLOB - single-byte or multiple-byte fixed-width character data.

55
LOB vs. LONG

LOB LONG
Multiple LOB columns per table Single LONG column per table

Up to 4 GB Up to 2 GB

SELECT returns locator SELECT returns data

Random access to data Sequential access to data

• Oracle 9i provides a LONG to LOB conversion API

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

 Modify LOB values:


APPEND, COPY, ERASE, TRIM, WRITE, LOADFROMFILE
 Read or examine LOB values:
GETLENGTH, INSTR, READ, SUBSTR
 Specific to BFILEs:
FILECLOSE
FILECLOSEALL
FILEEXISTS
FILEGETNAME
FILEISOPEN
FILEOPEN

58
DBMS_LOB.READ and DBMS_LOB.WRITE

PROCEDURE READ ( lobsrc IN BFILE|BLOB|CLOB ,


amount IN OUT BINARY_INTEGER,
offset IN INTEGER,
buffer OUT RAW|VARCHAR2 );

PROCEDURE WRITE ( lobdst IN OUT BLOB|CLOB,


amount IN OUT BINARY_INTEGER,
offset IN INTEGER := 1,
buffer IN RAW|VARCHAR2 );

EMPTY_BLOB() -- Places a null value BLOB column

EMPTY_CLOB() – Places a null value in CLOB column

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

CREATE OR REPLACE PROCEDURE IsTempLOBOpen


(p_lob_loc IN OUT BLOB,
p_retval OUT INTEGER)
IS
BEGIN
-- create a temporary LOB
DBMS_LOB.CREATETEMPORARY (p_lob_loc, TRUE);
-- see if the LOB is open: returns 1 if open
p_retval := DBMS_LOB.ISOPEN (p_lob_loc);
DBMS_OUTPUT.PUT_LINE ('The file returned a value ....' || p_retval);
-- free the temporary LOB
DBMS_LOB.FREETEMPORARY (p_lob_loc);
END;

62
BFILE

 Create an OS directory and supply files.


 Create an Oracle table with a column that holds the BFILE data type.
 Create a DIRECTORY object.
CREATE DIRECTORY <<dir_name >> AS <<server path >>;

 Grant privileges to read the DIRECTORY object to users.


GRANT READ ON DIRECTORY <<dir_name>>
TO user|role|PUBLIC;

 Insert rows into the table by using the BFILENAME function.


 Declare and initialize a LOB locator in a program.
 Read the 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
.

SQL *Loader Concepts

66
SQL*Loader Basics

Date Files Control File

Log File SQL *Loader Bad File

Data Base Discard Files

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

Provides information about the data to be loaded to columns of a table.

 Specifications for loading logical records into tables


 Field condition specifications
 Data-field position specifications
 Datatype specifications
 Setting columns to null or zero
 Loading all-blank fields
 Trimming blanks and tabs
 Preserve white space
 Applying SQL operators to fields

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

INTO TABLE temp_table


(partnum INTEGER,
”PART” CHAR(15),
”COUNT” INTEGER,
”DATA” VARCHAR2(30)) ;
71
Case 1 : Loading Variable-Length Data
LOAD DATA
INFILE *
INTO TABLE dept
FIELDS TERMINATED BY ’,’ OPTIONALLY ENCLOSED BY ’”’
(deptno, dname, loc)
BEGINDATA
12,RESEARCH,”SARATOGA”
10,”ACCOUNTING”,CLEVELAND
11,”ART”,SALEM
13,FINANCE,”BOSTON”
21,”SALES”,PHILA.
Syntax :
sqlldr userid=apps/apps control=case1.ctl log=case1.log

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.

INTO TABLE dept


TRAILING NULLCOLS
( deptno CHAR TERMINATED BY ” ”,
dname CHAR TERMINATED BY
WHITESPACE,
loc CHAR TERMINATED BY
WHITESPACE )

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)”

3. Field_1 TO_DATE(RTRIM(:field_1>), ’dd-mon-yyyy’)

79
SQL*Loader Command Line

 USERID — Oracle username/password


 CONTROL — Control file name
 LOG — Log file name
 BAD — Bad file name
 DATA — Data file name
 DISCARD — Discard file name
 DISCARDMAX — Number of discards to allow
 SKIP — Number of logical records
to skip
 LOAD — Number of logical records to
load
 ERRORS — Number of errors to allow
 SILENT — Suppress messages during run

80
Concurrent Program Creation

1. Move the control file to Product directory bin folder


2. Concurrent executable with execution method SQL* Loader
3. Mention the control file with out file extention
4. Create concurrent program with a parameter to pass the data file
server path
5. Check the log and out file for record information

81
.

Thank You

82

Вам также может понравиться