Features of Oracle 9i & PL/SQL
Features of Oracle 9i & PL/SQL
&
PL/SQL
. 1
Features of Oracle 9i & PL/SQL
. 2
Features of Oracle 9i &
PL/SQL
. 3
ORACLE RDBMS
Database (information)
Physical Layer
Logical Layer
Server/Instance
Memory
Processes
. 4
Database Physical Layer
. 5
Database Logical Layer
Tablespaces – Logically related group of data
Schema Objects – Logical DB structures/abstractions
Segments – Set of extents
Data – Stores user data
Index – Stores indexes
Rollback – Stores info required for rollback of transactions
Temporary – Work area for SQL statements
Extents – Set of data blocks
Data Blocks – Smallest unit of info stored in DB
. 6
Instance Memory – System Global Area (SGA)
. 7
Instance Memory – Program Global Area (PGA)
Session Information
. 8
Instance Processes
Server (Shadow) – Interacts with Oracle to carry out user request
Background – Task within Oracle RDBMS
DBWR – Reads/Writes DB/DD Cache to files
LGWR – Writes Redo Log buffer to files
CKPT – Signals DBWR to write modified buffers to files
PMON – Keeps track of DB processes, cleanup, lock management
RECO – Commit/Rollback pending transactions in a distributed DB
ARCH – Copies filled Redo Logs to archival storage
LCKn – Number of lock processes in Oracle Parallel Server option
Dnnn – Dispatches/routes requests to available server processes (MTS)
. 9
Features of Oracle 9i &
PL/SQL
. 10
Tables
Table creation:
create table EMPLOYEE
( employee_id NUMBER,
date_of_joining DATE,
department_id VARCHAR2(2),
sex CHAR(1),
passport_no VARCHAR2(20),
address VARCHAR2(50),
salary NUMBER(12, 2),
constraint EMPLOYEE_PK PRIMARY KEY(employee_id)
using index tablespace INDEX_LARGE
)
tablespace DATA_LARGE PCTFREE 10 PCTUSED 40
storage( INITIAL 1M NEXT 1M MINEXTENTS 1 MAXEXTENTS unlimited PCTINCREASE 0 );
. 11
Constraints
Checks/Validations/Referential Integrity imposed on data
Primary Key:
constraint EMPLOYEE_PK PRIMARY KEY(employee_id)
Foreign Key:
constraint DEPT_FK FOREIGN KEY(department_id) references DEPARTMENT(department_id)
Check:
CHECK (salary > 0)
CHECK (sex in (‘M’, ‘F’))
Unique:
constraint PASSPORT_UQ UNIQUE(passport_no)
. 12
Views
Structure showing data from one or more tables when invoked
Data Hiding
Data Modification
Reporting
. 13
Indexes
Similar to Index of a book (Listing of keywords accompanied by location of information)
Used to improve query performance or enforce uniqueness
Internally stored using Binary Search (B-Tree) structure
Types of indexes:
Unique
Non-unique
Bitmapped
Function based
. 14
Indexes
Oracle Optimizer:
2 primary modes:
Rule-based (RBO)
Cost-based (CBO)
Set using OPTIMIZER_MODE parameter
To use CBO, analyze tables and indexes using:
Compute statistics – full object scan
Estimate statistics – part object scan
analyze table BOOKSHELF estimate statistics;
From Oracle 9i use DBMS_STATS package:
execute DBMS_STATS.GATHER_TABLE_STATS (‘TRNG’, ‘BOOKSHELF’);
. 15
Indexes
Operations that access Tables:
TABLE ACCESS FULL
select * from BOOKSHELF;
. 16
Indexes
When Indexes are used:
When an indexed column is set equal to a value
select title from BOOKSHELF where categoryName = ‘ADULTNF’;
When a range of values is specified for an indexed column
select title from BOOKSHELF where title > ‘M’;
When no functions are performed on the column in the where clause
select title from BOOKSHELF where UPPER(categoryName) = ‘ADULTNF’;
When no IS NULL or IS NOT NULL checks are used on the indexed column
select title from BOOKSHELF where categoryName IS NOT NULL;
When equivalence conditions are used
select title from BOOKSHELF where categoryName != ‘ADULTNF’;
When MAX or MIN functions are used
select MAX(categoryName) from BOOKSHELF;
When the leading column of a multi-column index is set equal to a value
select title from BOOKSHELF where categoryName = ‘ADULTNF’;
. 17
Partitions
Splitting rows of a large table into smaller parts based on certain criteria
Partitions based on 3 criteria:
Range
Hash
List
. 18
Partitions
Splitting rows of a large table into smaller parts based on certain criteria
Benefits of Partitions–
Separation of data as per user choice
Smaller data segments, smaller table scans
Smaller indexes, faster access
Parallel DML on partition basis
Parallel backup and recovery
Parallel loading by partition
Export/Import by partition
Local/Global indexes
Parallel ANALYZE command for cost-based optimization more quick
Better data availability
. 19
Partitions
Range Partitions:
partition by range(categoryName)
(partition PART1 values less than (‘B’) tablespace PART1_TS,
partition PART2 values less than (MAXVALUE) tablespace PART2_TS);
. 20
Partitions
Hash Partitions:
)
partition by hash(categoryName)
(partition PART1 tablespace PART1_TS,
partition PART2 tablespace PART2_TS);
. 21
Partitions
List Partitions:
. 22
Sequences
. 23
Features of Oracle 9i &
PL/SQL
Section 3: PL/SQL
. 24
PL/SQL
Introduction
. 25
PL/SQL Execution Environments - The PL/SQL Engine
. 26
PL/SQL BLOCK STRUCTURE
DECLARE
BEGIN
EXCEPTION
END
. 27
PL/SQL BLOCK STRUCTURE
Declaration Section
Executable Section
. 28
PL/SQL
Variable Declaration
. 29
Variable Declarations Overview
Syntax of Declaration
identifier [constant ] datatype [not null ] [:= plsql_expression ] ;
DECLARE
firstname lastname CHAR(20) ; - illegal
DECLARE
firstname CHAR(20) ; -legal
lastname CHAR(20) ; - legal
. 30
Variable Declarations Overview
NUMBER
Count NUMBER;
revenue NUMBER (9,2);
second_per_day CONSTANT NUMBER := 60 * 60* 24 ;
running _total NUMBER (10,0) := 0;
VARCHAR2
mid_initial VARCHAR2 := ‘K’;
last_name VARCHAR2(10) NOT NULL;
company_name CONSTANT VARCHAR2(12);
DATE
anniversary DATE := ‘05-NOV-78’;
project_complexion DATE;
next_checkup DATE NOT NULL := ‘28-JUN-90’;
BOOLEAN
over_budget BOOLEAN NOT NULL := FALSE;
available BOOLEAN := NULL ;
. 31
Attribute Declaration
%TYPE attribute
DECLARE
books_printed NUMBER (6);
books_sold books.sold%TYPE ;
maiden_name emp.ename%TYPE ;
%ROWTYPE attribute
DECLARE
dept_row dept%ROWTYPE ;
. 32
Variable Assignment
PL/SQL Expressions consist of Variables, Constants, Literals, and
Function Calls.
ASSIGNMENT Syntax
plsql_variable := plsql_expression;
. 33
Scoping
SCOPING RULES:
1. An identifier is visible in the block in which it is declared and all its
sub-blocks unless rule #2 applies.
. 34
Scoping Variables and Constants
DECLARE
credit_limit CONSTANT NUMBER (6,2) : =2000;
account NUMBER := 100;
BEGIN
DECLARE
account CHAR(10) := ‘ABC’;
new_balance NUMBER (9,2);
BEGIN
new_balance account credit_limit
END;
DECLARE
account NUMBER := 200;
old_balance NUMBER (9,2);
BEGIN
old_balance account credit_limit
END;
. 35
PL/SQL
SQL in PL/SQL
. 36
SQL & PL/SQL Overview
. 37
SQL & PL/SQL Overview
INSERT
DECLARE
my_sal NUMBER(7,2) := 3040.22;
my_ename CHAR(25) := ‘WANDA’;
my_hiredate DATE := ‘08-SEP-01’;
BEGIN
INSERT INTO EMP (empno, ename, job, hiredate, sal , deptno)
VALUES (2345, my_ename, ’cab Driver’, my_hiredate, my_sal, 20);
END;
EMPNO ENAME SAL EMPNO ENAME SAL
7644 TURNER 1500 7644 TURNER 1500
7400 ALLEN 1600
. 38
SQL & PL/SQL Overview
UPDATE
DECLARE
max_allowed CONSTANT N UMBER := 5000;
good_cust CHAR(8) := ‘VIP’;
BEGIN
UPDATE ACCOUNT SET CREDIT_LIMIT = MAX_ALLOWED
WHERE TYPE = ‘EMPLOYEE ‘ OR TYPE = good_cust;
END;
UPDATE
. 39
SQL & PL/SQL Overview
DELETE
DECLARE
bad_child_type CHAR(8) := ‘NAUGHTY’;
BEGIN
DELETE FROM santas_gift_list WHERE kid_rating = bad_child_type ;
END;
DELETE
. 40
SQL & PL/SQL Overview
VAR2
VAR3
. 42
Transaction processing
SAVEPOINT Syntax
SAVEPOINT <marker_name>;
ROLLBACK TO Syntax
ROLLBACK [WORK] TO SAVEPOINT <marker_name>;
BEGIN
INSERT INTO temp VALUES (1,1 ‘ROW 1’); SAVEPOINT A;
INSERT INTO temp VALUES (2,2 ‘ROW 2’); SAVEPOINT B ;
….
ROLLBACK TO SAVEPOINT B;
COMMIT ;
END;
. 43
SQL Functions
SQL Functional Support (within a SQL Statement):
1. Numeric (e.g. SQRT, ROUND, POWER)
2. Character (e.g. LENGTH, UPPER)
3. Date (e.g. ADD_MONTHS, MONTH_BETWEEN);
4. Group(e.g. AVG, MAX, COUNT)
. 44
PL/SQL
. 45
Logical Comparisons
•Logical Comparisons form the basis of conditional control in PL/SQL
•The result of these comparisons are always either TRUE ,FALSE or NULL
•Anything compared with NULL results in a NULL value.
•A NULL in an expression evaluates to NULL (except concatenation)
E.g.
5 + NULL evaluates to NULL
‘PL/’ || NULL || ‘SQL’ evaluates to ‘PL/SQL’
. 46
IF Statements
QuickNotes - IF Statement
1. <condition> must evaluate to a Boolean datatype (TRUE, FALSE,
NULL)
2. If <condition> is TRUE, then the associated <sequence of statements>
is executed; otherwise it is not
3. At most one <sequence of statements > gets executed
. 47
IF Statements
DECLARE
num_jobs NUMBER(7);
BEGIN
SELECT COUNT(*) INTO num_jobs FROM auditions
WHERE actorid=&&actor_id AND called_back =‘YES’;
IF num_jobs> 90 THEN
UPDATE actor SET actor_rating = ‘ OSCAR time’
WHERE actorid = &&actor_id;
ELSE IF num_jobs> 75 THEN
UPDATE actor SET actor_rating = ‘ DAY time soaps’
WHERE actorid = &&actor_id;
ELSE
UPDATE actor SET actor_rating = ‘ Waiter’
WHERE actorid = &&actor_id;
END IF;
COMMIT;
END;
. 48
IF Statements
The NULL Trap
BLOCK 1 BLOCK 2
. .
IF a >= b THEN IF a < b THEN
do_this …..; do_that …..;
ELSE ELSE
do_that….; do_this….;
END IF; END IF;
. 49
Loop Statement Overview
. 50
Loop Statements
. 51
Loop Statements ……Example
DECLARE
ctr NUMBER(3) := 0;
BEGIN
LOOP
INSERT INTO LOG VALUES (ctr, ’ITERATION COMPLETE’);
ctr := ctr +1;
IF ctr = 1500 THEN EXIT;
END IF;
END LOOP;
END;
DECLARE
ctr NUMBER(3) := 0;
BEGIN
LOOP
UPDATE TABLE 1 SET COMMIT = ‘UPDATES’ WHERE COUNT_COL = ctr;
ctr := ctr +1;
IF ctr = 1500 THEN EXIT;
END IF;
END LOOP;
END;
. 52
Loop Statements
Numeric FOR Loops repeat sequence of statements fixed number
of times.
Numeric FOR Loop Syntax
FOR <index> IN [REVERSE ] <integer>..<integer> LOOP <sequence of
statements>
The Loop Index takes on each value in range , one of a time , either in
forward or reverse order.
E.g.
BEGIN
FOR I IN 1..500 LOOP
INSERT INTO temp(message)VALUES (‘I will not sleep in class.’);
END LOOP;
END;
. 53
Loop Statements
QuickNotes - Index
1. It is implicitly of type NUMBER
2. It is only defined within the loop
3. Value may be referenced in an expression, but a new value may not be
assigned to it within the loop
E.g.
DECLARE
my_index CHAR(20) := ‘Fettuccini Alfredo’;
BEGIN
FOR my index IN REVERSE 21…30 LOOP /* redeclare s my_index*/
INSERT INTO temp(coll.)VALUES (my_index); /* insert the numbers 30 through 21*/
END LOOP;
END;
FOR i I N 1…256 LOOP
x := x + i ; -- legal
i := I + 5; -- illegal
END LOOP;
. 54
Loop Statements
WHILE Loops repeat a sequence of statements until a specific condition is no
longer
TRUE.
While Loop Syntax
WHILE <condition > LOOP <sequence of statements > END LOOP;
DECLARE
ctr NUMBER (3) := 0;
BEGIN
WHILE ctr < 500 LOOP
INSERT INTO temp(message) VALUES (‘Well,I might sleep just a little’);
ctr := ctr +1 ;
END LOOP;
END;
. 55
“ GO TO ” Statement Overview
. 56
“ GO TO ” Statements
NOT ALL GOTOs are Legal !
You can legally a GOTO a statement that is either:
1.in the same sequence of statements as the GOTO STATEMENT
2. In the sequence of statements that encloses the GOTO statement (I.e.
an outer block)
. 57
Other Uses for Statement Labels
Labels may label any statement
In addition to their use as targets for GOTO statements, labels may be used for :
1. Blocks
2. Loops
Labeling a block allows referencing of DECLARED objects that would
otherwise not be visible because of Scoping rules.
Syntax
<< label_name>>
[ DECLARE
-- declarations go here ]
BEGIN
-- executable statements go here
[ EXCEPTION
-- exception handlers go here ]
END label_name ; -- must include the label_name
. 58
Other Uses for Statement Labels
E.g.
<< outer_block >>
DECLARE
n NUMBER;
BEGIN
n := 5;
/* Start a sub block */
DECLARE
x NUMBER := 10;
n CHAR (10) := ‘Fifteen’;
BEGIN
INSERT INTO TEMP VALUES (outer_block.n , x , n );
COMMIT;
END ; /* End of the sub block */
END outer_block;
. 59
Other Uses for Statement Labels
E.g.
. 60
Other Uses for Statement Labels
Labeling Loops allows you to reference objects that would otherwise not
be visible because of scoping rules
E.g.
. 61
Other Uses for Statement Labels
. 62
PL/SQL
Cursors
. 63
Cursor Overview
1. EXPLICIT
Multiple row SELECT STATEMENTS
2. IMPLICIT
All INSERT statements
All UPDATE statements
All DELETE statements
Single row SELECT….INTO Statements
. 64
Using Explicit Cursors
STEP 1 . Declare the cursor
DECLARE
CURSOR <cursor name> IS <regular select statement> ;
. 65
Using Explicit Cursors
. 66
Explicit Cursors Attributes
%NOTFOUND
E.g.
LOOP
FETCH my_cursor INTO my_ename , my_sal ;
EXIT WHEN my_cursor%NOTFOUND ;
-- process data here
END LOOP ;
%FOUND
E.g.
FETCH my_cursor INTO my_ename ,my_sal ;
WHILE my_cursor%FOUND LOOP
-- process data here
FETCH my_cursor INTO my_ename ,my_sal ;
END LOOP ;
. 67
Explicit Cursor Attributes
%ROWCOUNT
E.g.
LOOP
FETCH my_cursor INTO my_ename , my_sal ;
EXIT WHEN (my_cursor%NOTFOUND)
OR (my_cursor%ROWCOUNT > 10) ;
-- process data here
END LOOP
%ISOPEN
E.g.
IF my_cursor%ISOPEN THEN
FETCH my_cursor INTO my_ename , my_sal ;
ELSE
OPEN my_cursor ;
END IF ;
. 68
Using Explicit Cursors
E.g.
DECLARE
sal_limit NUMBER ( 4 ) := 0 ;
my_ename emp.ename%TYPE ;
my_sal emp.sal%TYPE ;
CURSOR my_cursor IS SELECT ename , sal FROM emp WHERE sal > sal_limit ;
BEGIN
sal_limit := 1200 ;
OPEN my_cursor INTO my_ename , my_sal ;
LOOP
FETCH my_cursor INTO my_ename , my_sal ;
EXIT WHEN my_cursor%NOTFOUND ; -- nothing returned
INSERT INTO new_table VALUES ( my_ename , my_sal ) ;
END LOOP ;
CLOSE my_cursor ;
COMMIT ;
END ;
. 69
Explicit Cursors -FOR Loops
Cursor FOR Loops specify a sequence of statements to be repeated once for
each row that is returned by the cursor.
Cursor FOR Loop Syntax
FOR <record _name> IN <cursor_name> LOOP
--- statements to be repeated go here
END LOOP;
Numeric FOR Loop Similarities
1. Specify a set of rows from a table by using the cursor’s name vs. specifying a
set of integers (i.e. 1…10)
2. Index takes on the values of each row vs. index taking on integer values (i.e. 1
through 10)
Implicitly Declared <record_name>
record_name cursor _name%ROWTYPE;
To reference an element of the record, use the record_name.column_name
notation.
. 70
Explicit Cursors -FOR Loops
Conceptual Cursor Loop Model
. 71
Explicit Cursors - FOR Loops
E.g.
DECLARE
sal_limit NUMBER ( 4 ) := 0 ;
total_sal NUMBER (9,2 ) := 0;
CURSOR my_cursor IS SELECT ename , sal FROM emp
WHERE sal > sal_limit ;
BEGIN
sal_limit := 1200 ;
-- implicitly OPEN done next
FOR cursor_row IN my_cursor LOOP
-- an implicit fetch done here
INSERT INTO new_table VALUES (cursor_row.ename ,cursor_row.sal ) ;
total_sal := total_sal + cursor_row.sal;
END LOOP ; --an implicit close done here.
COMMIT ;
END ;
. 72
Implicit Cursors - FOR Loops
An Implicit Cursor is automatically associated with any SQL
DML statement that does not have an explicit cursor associated
with it.
This includes :
1. ALL INSERT statements
2. ALL UPDATE statements
3. ALL DELETE statements
4. ALL SELECT…INTO statements
QuickNotes - Implicit Cursors
1. Implicit cursor is called the “SQL” cursor --it stores
information concerning the processing of the last SQL
statement not associated with an explicit cursor.
2.OPEN, FETCH, AND CLOSE don’t apply.
3. All cursor attributes apply.
. 73
Implicit Cursors
SQL %NOTFOUND
E.g.
. 74
Implicit Cursors
SQL%ROWCOUNT
E.g.
DELETE FROM baseball_team
WHERE batting _avg. < .100;
. 75
PL/SQL
Exception Handling
. 76
Exception Overview
. 77
Exception Overview
. 78
Predefined Internal Exceptions
Any ORACLE error “raises” an exception automatically; some of the
more common ones have names.
TOO_MANY_ROWS ORA-(01427)
- a single row SELECT returned more than one row
NO_DATA_FOUND ORA-(01403)
- a single row SELECT returned no data
INVALID_CURSOR ORA-(01001)
- invalid cursor was specified
VALUE_ERROR ORA-(06502)
- arithmetic ,numeric, string , conversion,or constraint error occurred.
ZERO_DIVIDE ORA-(01476)
- attempted to divide by zero
DUP_VAL_ON_INDEX ORA-(00001)
- attempted to insert a duplicate value into a column that has a unique index
specified.
. 79
Exception Handlers
Syntax
WHEN <exception_name [OR <exception_name…]> then <sequence of statements>
OR
WHEN OTHERS THEN -- if used , must be last handler <sequence of statements>
E.g.
DECLARE
employee_num emp.empno%TYPE;
BEGIN
SELECT empno INTO employee_num FROM emp;
WHERE ename = ‘BLAKE’;
INSERT INTO temp VALUES(NULL, empno,Blake's employee_num’);
DELETE FROM emp WHERE ename =‘BLAKE’;
EXCEPTION
WHEN TOO_MANY_ROWS OR NO_DATA_FOUND THEN
ROLLBACK;
INSERT INTO temp VALUES (NULL,’Blake not found, or more than one Blake’);
COMMIT;
. 80
User - Defined Exceptions
User - defined Exceptions must be defined and explicitly raised by the
user.
E.g.
DECLARE
x NUMBER;
my_exception EXCEPTION; -- a new object type.
Raise your_exception;
RAISE my_exception;
. 82
Exceptions Propagation
Step# 1 The current block is searched for a handler. If not found, go to step 2.
Step# 2 If an enclosing block is found, it is searched for it handler.
Step# 3 Step #1 and#2 are repeated until either there are no more enclosing
blocks, or a handler is found .
If there are no more enclosing blocks, the exception is passed back to the
calling environment (SQL *Plus,SQL *Forms, a precompiled program,etc.)
If the handler is found ,it is executed .when done the block in which the
handler was found is terminated, and control is passed to thee enclosing block (if
one exists), or to environment (if there is no enclosing block)
Quick notes
1. Only one handler per block may be active at a time
2. If an exception is raised in a handler, the search for a handler for the new
exception begins in the enclosing block of the current block
. 83
Exceptions Propagation
Example 1
BEGIN
BEGIN
IF X=1 THEN RAISE A:
ELSEIF X=2 THEN RAISE B;
ELSE RAISE C;
Exception A is handled
locally and execution
EXCEPTION resumes in the outer
block
WHEN A THEN
END;
WHEN B THEN
END;
. 84
Exceptions Propagation
Example 2
BEGIN
BEGIN
IF X=1 THEN RAISE A:
ELSEIF X=2 THEN RAISE B;
ELSE RAISE C;
Exception B
PROPAGATES to the
EXCEPTION first outer block with an
appropriate handler
WHEN A THEN
...
END;
END;
. 85
Exceptions Propagation
Example 3
BEGIN
BEGIN
IF X=1 THEN RAISE A:
ELSEIF X=2 THEN RAISE B;
ELSE RAISE C;
EXCEPTION
WHEN A THEN
…..
END;
Exception C has no
handler and will result
WHEN B THEN in runtime unhandled
… .. exception
END;
. 86
Other uses of RAISE
Syntax
RAISE;
. 87
Error Reporting Functions
SQLCODE and SQLERRM
1. Provided information on the exception currently being handled.
2. Especially useful in the OTHERS handler.
SQLCODE
1. Returns the ORACLE error number of the exception or 1 if it was user-
defined exception
SQLERRM
1. Return the ORACLE error message currently associated with the current
value of SQLCODE
2. May also use any ORACLE error number as an argument.
QuickNotes - Error Reporting
1. If no exception is active …
SQLCODE = 0
SQLERRM = “normal , successful completion”
2. SQLCODE and SQLERRM cannot be used within a SQL statement.
. 88
Error Reporting Functions
E.g.
DECLARE
sqlcode_val NUMBER;
sqlcode_val CHAR(70);
BEGIN
…
EXCEPTION
WHEN OTHERS THEN
sqlcode _val := SQLCODE; -- can’t insert directly
sqlerrm_val := SQLERRM ; - -- can’t insert directly
INSERT INTO temp VALUES(sqlcode_val, NULL, sqlerrm_val);
END;
. 89
PL/SQL
. 90
Stored Procedures and Functions
. 91
Uses for Procedures
Define central well-known business functions.
Create an order
Delete a customer
Store batch job in the database
Weekly account rollups
Encapsulate a transaction
Gather and process information from remote nodes
Funnel activity on a table through a single path
All changes to employee salaries should change department
budgets.
. 92
Procedure Arguments
Argument Modes
. 93
Creating a Procedure
Ο E.g.
CREATE PROCEDURE
fire_employee (empid NUMBER)
AS
BEGIN
…
DELETE
FROM emp
WHERE empno=
fire_employee.empid;
END
. 94
Creating a Function
E.g.
CREATE FUNCTION
get_bal (acc_no NUMBER(4))
RETURN NUMBER(11,2);
IS
acc_bal NUMBER(11,2);
BEGIN
SELECT balance
INTO acc_bal
FROM accounts
WHERE account_id_no=acc_no;
RETURN (acc_bal);
END;
. 95
Statements in procedures
Ο Restricted statements
• DDL
• Dynamic SQL
• In trigger, COMMIT, SAVEPOINT and ROLLBACK
. 96
Executing a stored procedure
Ο On a remote node
scott.fire_employee@ny (empno);
. 97
Specifying procedure arguments
Ο E.g.
• CREATE PROCEDURE update_sal
(empno NUMBER,
bonus NUMBER,
sal_incr NUMBER) ….;
Ο Positional Method
• List values in the order they are declared
update_sal (7000,20,500);
Ο Named Method
• List argument names and values in any order, using special syntax
update_sal
(bonus => 20,
sal_incr => 500,
empno => 7000);
. 98
Specifying procedure arguments
Ο Combination method
• Use both positional and named methods
• Once you specify a named parameter, must use named method for all remaining
parameters
update_sal Legal
(7000,sal_incr=>500,bonus=>20);
update_sal Illegal
(empno=>7000,
sal_incr=>500,20);
. 99
How procedures are entered into the database
Ο PL/SQL Engine compiles the source code
. 100
PL/SQL Compilation Errors
. 101
PL/SQL Compilation Errors Executing SHOW
ERRORS
SQLDBA>show errors
ERRORS FOR PROCEDURE TEST1:
LINE/COL ERROR
---------------------------------------------------------------------------------------------
1/0 PL/SQL: Compilation unit
analysis terminated
1/33 PL/SQL-00219:’test2’ is not defined’
2 rows selected
. 102
PL/SQL Compilation Errors
Fields in ERRORS views
Ο TEXT:text of error
. 103
USER-DEFINED System Errors
Ο Any procedure can raise an error and return a user defined error message
and error number
Ο Oracle does not check if user defined error numbers are used uniquely
. 104
USER-DEFINED System Errors
Example
CREATE PROCEDURE
fire_employee (empid NUMBER)
AS
BEGIN
IF empid <=0 THEN
raise_application_error (-20100,’Employee number must be> 0’);
ELSE
DELETE
FROM emp
WHERE EMPNO =EMPID;
END IF;
END;
. 105
Dependencies and Procedures
Ο A procedure is dependent on:
. 106
Recompilation of Dependent procedures
Ο When an object changes, its dependent objects are marked for
recompilation
Ο Any change to definition of referenced object implies new
version of reference object
Ο Dependent objects must be recompiled if referenced object
changes
Ο Recompilation of dependent objects takes place automatically at
runtime
Ο Reasons recompilation could fail
• Changing parameter list in called procedure
• Changing definition of or removing referenced column from referenced table
• Dropping referenced table
. 107
Recompilation
. 108
Manual Recompilation
ALTER PROCEDURE
Procedure COMPILE
schema
Ο Example
ALTER PROCEDURE
add_department COMPILE
. 109
Changing a Procedure
Ο OR REPLACE option:
• Recreates the procedure even if it already exists
• Retains existing grants (need not reissue)
• Creates procedure even if there are syntax errors
• Marks dependent objects for recompilation
• Users executing old procedure finish that call: next invocation gets
new procedure
• Facilitates development (one step)
Ο CREATE without OR REPLACE on existing procedure fails
. 110
Dropping a Procedure
DROP PROCEDURE
Procedure
schema
Example
DROP PROCEDURE fire_employee;
. 111
Privileges for Procedures
Ο Example
GRANT EXECUTE
ON scott.hire_fire
TO mkennedy
WITH GRANT OPTION;
. 112
Privileges for Procedures
. 113
Privileges for Procedures
. 114
Benefits of Procedures
Ο Security
• Executes under security domain of procedure’s owner
• Provides controlled indirect access to database objects to non-
privileged users
Ο Integrity
• Defines allowed operations on data
• Ensures related actions are performed together
Ο Performance
• Reduces number of calls to thedatabase
• Decreases network traffic
• Pre-parses PL/SQL statements
. 115
Benefits of Procedures
Ο Memory savings
• Takes advantages of shared SQL
• Requires only one copy of the code for multiple users
Ο Productivity
• Avoids redundant code for common procedures in multiple applications
• Reduces coding errors: no redundant code written
. 116
Benefits of Procedures
Ο Maintainability
• Enables system wide changes with one update
• Makes testing easier: duplicate testing not needed
• Dependency tracked by ORACLE
Ο High availability
• Allows changing procedured on-line while users execute
previous version
. 117
Package
Ο Package comprises
Specification
Body
. 118
Parts of a Package
Ο Package specification
• Declares (specifies) package constructs, including names and parameters
publicly available procedures and functions
Ο Package body
• May declare additional, private package constructs that are not publicly
available
• Defines all package constructs (public and private)
• May be replaced without affecting package specification (Breaks
dependency chain)
• Each session has own version of state
. 119
Public and Private Package Constructs
. 120
Public and Private Package Constructs
FUNCTION check_num (. . )
Definition of RETURN. .
private IS
function BEGIN . . END;
END;
. 121
Public and Private Package Constructs
Package PK Procedure A
Package
Variable C specification
x :=pk.c;
Variable D
Package
body
Procedure B
y :=d;
z :=c;
. 122
Uses of Packages
Ο Group related constructs
Ο Declare globally accessible variables
Ο Declare variables with persistent state
Ο Organize development activity
• Define modules, collections of procedures known to on team
Ο Minimize name conflicts within a schema
• Personnel.audit inventory.audit
Ο Simplify security
• GRANT EXECUTE on entire package
Ο limit recompilation
• Change body of procedure or function without changing specification
. 123
Creating a Package Specification
Example
/* Package specification declaring procedures and variables for
hiring and firing employees */
CREATE PACKAGE hire_fire
AS
/*Declare procedures */
PROCEDURE hire_employee
(empno NUMBER, ename CHAR,
mgr NUMBER, sal NUMBER,
comm NUMBER, deptno NUMBER);
PROCEDURE fire_employee (empid NUMBER);
/*Global variable declaration*/
valid CHAR(1);
END hire_fire;
. 124
Creating a package Body
Example
/*package body containing procedures to hire and ire employee */
CREATE PACKAGE BODY hire_fire
AS
/*Procedure to hire a employee*/
PROCEDURE hire_employee
(empno NUMBER, ename CHAR,
mgr NUMBER, sal NUMBER,
comm NUMBER, deptno NUMBER);
IS
BEGIN
/*VALID is declared in the package definition*/
valid :=check_sum(empno);
/*IF valid empno then add user*/
IF valid =‘T’ THEN
INSERT INTO EMP VALUES
(empno,ename,mgr,sal,comm,deptno);
END IF;
END; (continued)
. 125
Creating a package body
Example(continued)
/* Procedure to fire an employee number */
PROCEDURE fire_employee (empid NUMBER)
IS
BEGIN
DELETE FROM emp
WHERE empno =empid;
END;
/*function to check that the employee number>0.Local to the package */
FUNCTION check_sum (empno NUMBER)
RETURN CHAR(1) IS
answer CHAR(1);
BEGIN
answer :=‘T’;
IF empno <0 THEN
answer := ‘F’;
END IF;
RETURN (answer);
END;
END hire_fire; /*End of package*/
. 126
Accessing package constructs
PROCEDURE employee_admin
/* The action to perform and the employee ID have been entered previously*/
IF action =“HIRE”THEN
scott.hire_fire.hire_employee
( employee,ename,mgr,sal,comm,deptno);
IF scott.hire_fire.valid =‘T’ THEN
/*sports_club is another package that handles membership to the company
sports club*/
sports_club.add (employee)
END IF;
ELSIF action =“FIRE” THEN
scott.hire_fire.fire_employee
(employee);
sports_club.remove (employee);
END IF;
. 127
Dropping a Package
DROP PACKAGE
Procedure
schema
Example
DROP PACKAGE hire_fire;
. 128
Benefit Of Package
Performance
•Reduces disk I/O for subsequent calls
- First call to package loads whole package into
memory
Persistence state
•Retain values of package constructs for
an entire session
Security
•Access to the package allows access to
public constructs in the package only.
•No need to issue GRANT for every
procedure in package.
. 129
Benefit Of Package
Ο Productivity
•Stores related procedures and function
together
•Easier to manger changing the specification
or definition of a construct.
•Reduces cascading dependencies
. 130
PL/SQL
Triggers
. 131
Triggers
Ο Definition
Ο Creating Triggers
Ο Restrictions on Triggers
Ο Dropping and recompiling
Ο Privileges for creating
Ο Applications
Ο Benefits
. 132
Trigger Definition
Database
Application
UPDATE UPDATE(trigger)
UPDATE tt UPDATE(trigger)
SET
SET….;
….;
Table T
INSERT
INSERT
INSERT(trigger)
INSERT(trigger)
INTO
INTO t…..;
t…..;
DELETE
DELETE
FROM
FROM t…;
t…; DELETE(trigger)
DELETE(trigger)
. 133
What is a Trigger
. 134
E.g. of a Trigger - Keeping salary in range for a job
CREATE TRIGGER scott.salary_check
BEFORE INSERT OR UPDATE sal, job ON scott.emp
FOR EACH ROW
WHEN (NEW .job <> ‘PRESIDENT’)
DECLARE
minsal NUMBER;
maxsal NUMBER;
BEGIN /* get min and max salaries for the employee’s job from the SAL_GUIDE*/
SELECT minsal,maxsal INTO minsal,maxsal FROM sal_guide
WHERE job = :NEW.job;
/* If salary below min or above max,generate an error*/
IF (:NEW.sal < minsal.OR :NEW.sal > maxsal)
THEN raise_application_error ( -20500,’salary’ || :NEW.sal|| ‘out of range for job’||
:NEW.job|| ‘for employee’|| :NEW.ENAME);
ENDIF;
END; /* End of Trigger*/
. 135
Triggers and Stored procedures
Similarities
. 136
Triggers and Stored procedures
Differences
. 137
Triggers vs. SQL*Forms Triggers
Database trigger
• Fires while statement executes
• Fires independently of and in addition to SQL *From Triggers
• Fired by SQL statement from any tool or application
• Can prevent completion of SQL statement
• Fire as each statement is executed
. 138
Types of Triggers
. 139
Types of Triggers
How to use each type
Ο AFTER
• For auditing
row trigger
(by value,by row)
• Used by ORACLE snapshot mechanism
• For auditing
Ο AFTER statement trigger
. 140
Trigger - Firing Sequence
Ο INSERT,UPDATE or DELETE is applied to table statement to execute
Ο Execute BEFORE statement trigger
Ο For each row affected by the SQL statement:
• Execute BEFORE row trigger
• Change row and perform integrity constraint checking
• Execute AFTER row trigger
. 141
Expressions in Triggers
Referring to values in row Triggers
Ο To refer to the old and new values of a column in row Triggers, use
the :OLD and :NEW prefixes:
• IF :NEW.sal < :OLD.sal. THEN
Ο Notes:
. 142
Expressions in Triggers
Conditional Predicates
IF UPDATING (‘columnname’)
. 143
Expressions in Triggers
. 144
Restrictions on Triggers
. 145
Restrictions on Triggers
Mutating tables
Original EMP
ENAME
ENAME SAL
SAL
SMITH
SMITH 1000
1000 UPDATE emp
JONES
JONES 1000
1000 SET sal = sal *1.1;
. 146
Restrictions on Triggers
Changes to updated/inserted values
EMPNO
EMPNO DEPTNO
DEPTNO
0450
0450 20
20 UPDATE emp
0407
0407 10
10 SET deptno=10
WHERE empno =0405;
mutating EMP
EMPNO
EMPNO DEPTNO
DEPTNO GRATE TRIGGER bad
0450
0450 10
10 UPDATE BEGIN
0407 10 NEW.deptno:=30
0407 10 (trigger) END;
• Disabled
•Does not execute its triggered action
. 148
Enabling and disabling Triggers
Reasons for disabling the trigger
. 149
Enabling and disabling Triggers
With ALTER TRIGGER
schema DISABLE
Examples
ALTER TRIGGER reorder DISABLE;
ALTER TRIGGER reorder ENABLE;
. 150
Enabling and disabling Triggers
With ALTER TABLE
schema
DISABLE schema
• Examples
ALTER TABLE INVENTORY
DISABLE TRIGGER REORDER;
ALTER TABLE INVENTORY
ENABLE TRIGGER REORDER;
. 151
Dropping Triggers
schema
Ο Example
DROP TRIGGER reorder;
. 152
Recompiling a trigger
COMPILE
ALTER TRIGGER trigger
schema
. 153
Applications of Triggers
. 154
Examples of using Triggers
Deriving column values
. 155
Examples of using Triggers
Deriving column values
Emp no Ename Uppername Soundexname Job
7329 Smith Smith S530 Clerk
7499 Allen Allen A450 Salesman
7566 Jones Jones J520 Manager
. 156
Examples of using Triggers
Complex Security Authorization
• Examples
- Check for time of day,day of week
- Check for terminal being used
- Permit updates of certain amounts by specific users
. 157
Examples of using Triggers
Complex Security Authorization
CREATE TRIGGER emp_permit_changes
BEFORE INSERT OR DELETE OR UPDATE ON emp
DECLARE dummy INTEGER;
BEGIN
IF(TO_CHAR (sysdate,’DY’) IN(‘SAT,’SUN’))
THEN
raise_application_error(-20504,’cannot change emp table during weekend’);
END IF;
SELECT COUNT(* ) INTO dummy
FROM company_holidays
WHERE day = TRUNC(sysdate);
IF dummy>0 THEN
raise_application_error(-20505,’cannot change emp table during holiday’);
END IF;
IF (TO_NUMBER(sysdate,’HH24’)
NOT BETWEEN 8 AND 18) THEN
raise_application_error (-20506,cannot change emp table in of_hours’);
END IF;
END;
. 158
Examples of using Triggers
Enforcing complex Business Rules
Complex check constraints that are not definable using declarative constraints
. 159
Examples of using Triggers
Enforcing complex Business Rules
. 160
Examples of using Triggers
Enforcing complex Business Rules
CREATE TRIGGER scott.salary_check
BEFORE INSERT OR UPDATE OR UPDATE OF sal,
ON scott.emp
FOR EACH ROW
WHEN (NEW.job <>’PRESIDENT’)
DECLARE minsal NUMBER;
maxsal NUMBER;
BEGIN
SELECT minsal,maxsal
INTO minsal,maxsal
FROM sal_guide
WHERE job= :NEW.job ;
IF (:NEW.sal <minsal OR
:NEW.sal > maxsal)
THEN raise_application_error ( -20503,’salary’ || :NEW.sal|| ‘out of range for
job’||:NEW.job|| ‘for employee’|| :NEW.ENAME);
END IF;
END;
. 161
Examples of using Triggers
Value based auditing
. 162
Examples of using Triggers
Value based auditing
. 163
Examples of using Triggers
Implied data changes
PENDING_ORDERS
PART_NO
PART_NO ORD_QTY
ORD_QTY ORD_DATE
ORD_DATE
00234
00234 15
15 15-JAN-92
15-JAN-92
00342
00342 25
25 15-JAN-92
15-JAN-92
INVENTORY
PART_NO
PART_NO ON_HAND
ON_HAND REORD_PT
REORD_PT REORD_QTY
REORD_QTY
00234
00234 34
34 30
30 15
15
00342
00342 52
52 50
50 25
25
. 164
Examples of using Triggers
Implied data changes
IF x = 0 THEN
INSERT INTO pending_orders
VALUES
(:NEW.part_no,
:NEW.reord_qty,
SYSDATE);
END IF;
END;
. 165
Examples of using Triggers
Synchronous Table Replication
Link identical tables(replicas) on different nodes so when replica is altered,
changes are synchronously reflected in other replicas
Replicas must contain a flag field that is set when they are updated to stop trigger
cascading
EMP_REP1 EMP_REP2
UPDATE... UPDATE...
. 166
Benefits of Triggers
Ο Security
• Allows sophisticated security checking
• Enables customized auditing mechanism to be built
Ο Integrity
• Ensures related operations on data are performed together
• Can be used to enforce complex business rules
. 167
Benefits of Triggers
Ο Performance
• Reduces number of calls to the RDBMS
• Decreases network traffic
Ο Memory savings
• Takes advantage of shared SQL
• Requires only one copy of the code for multiple users
Ο Productivity
• Requires only a single copy of the code be written and
maintained(not multiple copies in client applications)
. 168
Features of Oracle 9i &
PL/SQL
Section 4: ORDBMS
. 169
Object Oriented Concepts
Benefits:
Reusability
Adherence to Standards
Defined access paths
. 170
Types of Objects
Abstract Datatypes
Object Views
Varying Arrays
Nested Tables
References
Large Objects
. 171
Abstract Datatypes
Grouping related columns (subtypes) into objects
create type ADDRESS_TY as object
( street VARCHAR2(50),
city VARCHAR2(25),
state VARCHAR2(2),
zip NUMBER);
. 172
Abstract Datatypes
Table creation:
create table CUSTOMER
( customer_id NUMBER,
person PERSON_TY);
Insert operation:
insert into CUSTOMER values
( 1, PERSON_TY(‘Peter’,
ADDRESS_TY(‘Street S’, ‘City C’, ‘ST’, 11111)));
. 173
Abstract Datatypes
Select operation:
select customer_id, c.person.name
from customer c;
Index creation:
create index I_CUSTOMER_CITY
on CUSTOMER(person.address.city);
. 174
Object Views
The ability to overlay object oriented structures on existing relational tables
create table CUSTOMER
( customer_id NUMBER PRIMARY KEY,
name VARCHAR2(25),
street VARCHAR2(50),
city VARCHAR2(25),
state VARCHAR2(2),
zip NUMBER);
. 175
Object Views
create type PERSON_TY as object
( name VARCHAR2(25),
address ADDRESS_TY);
. 176
Object Views
Relational Insert operation:
insert into CUSTOMER values
(123, ‘Richard’, ’12 Farmside Close’, ‘Lewiston’, ‘NJ’, 4352);
. 177
Object Views
INSTEAD OF Triggers:
update AUTHOR_PUBLISHER
set publisher = ‘MARINER’
where author = ‘HARDY’;
Gives error ORA-01779
. 178
Object Views
create trigger AUTHOR_PUBLISHER_UPDATE /* INSTEAD OF Trigger */
instead of UPDATE on AUTHOR_PUBLISHER
for each row
begin
if :old.publisher <> :new.publisher then
update BOOKSHELF_PUBLISHER
set publisher = :new.publisher
where title = :old.title;
end if;
if :old.author <> :new.author then
update BOOKSHELF_AUTHOR
set author = :new.author
where title = :old.title;
end if;
end;
. 179
Object Views
Methods:
. 180
Object Views
Data Security:
. 181
Object Views
Using Methods:
create table ANIMAL
( Id NUMBER,
animal ANIMAL_TY);
select a.animal.age(a.animal.birthdate)
from animal;
. 182
Varying Arrays
Allows storage of repeating attributes of a record in a single row
. 183
Varying Arrays
Insert Operation:
insert into BORROWER values
(‘AMY’,
TOOLS_VA(‘Hammer’, ‘Sledge’, ‘Axe’));
. 184
Varying Arrays
Select Operation
Using PL/SQL:
declare
cursor borrower_cur is select * from BORROWER;
begin
for borrower_rec in borrower_cur
loop
dbms_output.put_line(‘Contact Name: ‘ || borrower_rec.name);
for i in 1..borrower_rec.tools.count
loop
dbms_output.put_line(‘Contact Name: ‘ || borrower_rec.tools(i));
end loop;
end loop;
end;
. 185
Varying Arrays
Select Operation
Using Table Function:
Output:
NAME COLUMN_VALUE
AMY HAMMER
AMY SLEDGE
AMY AXE
DAVID HAMMER
DAVID AXE
. 186
Nested Tables
A Table within a Table
create type ANIMAL_TY as object
( breed VARCHAR2(25),
name VARCHAR2(25),
birthdate DATE);
. 187
Nested Tables
Insert Operation:
insert into BREEDER values
(‘JANE’,
ANIMALS_NT(
ANIMAL_TY(‘DOG’, ‘SCOOBY’, ’31-MAR-01’),
ANIMAL_TY(‘DOG’, ‘BUZO’, ’05-JUN-01’),
ANIMAL_TY(‘DOG’, ‘KATIE’, ’10-JUL-01’)
));
. 188
Nested Tables
Select Operation:
Using Table Function:
select breedername, n.name, n.birthdate
from BREEDER, TABLE(breeder.animals) n;
. 189
References
Column Objects vs. Row Objects:
Row objects are referenced objects accessible via references from other objects
Used to create references between rows of different tables
Not embedded in main table.
Main table contains a reference to another table
E.g. Object tables
. 190
References
Object Tables and OIDs
Each row is an object
Each row has an Object Identifier (OID) Value assigned by Oracle during creation of the row
Rows can be referenced by other objects within the database using OID
OIDs are not re-used by Oracle
. 191
References
Insert Operation:
insert into ANIMAL values
Select Operation:
select name from ANIMAL;
Update Operation:
update ANIMAL
Delete Operation:
delete from ANIMAL where name = ‘FRANCES’;
. 192
References
REF Function:
Allows reference to existing row objects
Allows selection of OID assigned to each row
Takes as input alias given to the object table and returns reference value (OID)
select REF(a)
from ANIMAL a
where name = ‘FRANCES’;
REF(a)
------------------------------------------------------------------------------------
0000280209FFD8EC317DA111D6B008444456464GF2452525032
. 193
References
DEREF Function:
Opposite of REF
Takes as input a reference value (OID) and returns the value of the row object
. 194
References
DEREF Function:
insert into KEEPER
select ‘CATHERINE’, REF(a)
from ANIMAL a
where name = ‘FRANCES’;
select DEREF(k.animalkept)
from KEEPER k
where keepername = ‘CATHERINE’;
Output:
ANIMAL_TY(‘MULE’, ‘FRANCES’, ’01-APR-02’)
. 195
References
VALUE Function:
To see the same structures from a query of the ANIMAL object table
select VALUE(a)
From ANIMAL a
where name = ‘FRANCES’;
Output:
ANIMAL_TY(‘MULE’, ‘FRANCES’, ’01-APR-02’)
Invalid Reference:
delete from ANIMAL
where name = ‘FRANCES’;
=> Produces a dangling REF
. 196
References
FK relationships vs. References:
create table CUSTOMER
( customer_id NUMBER constraint CUSTOMER_PK PRIMARY KEY,
name VARCHAR2(25),
street VARCHAR2(50),
city VARCHAR2(25),
state VARCHAR2(2),
zip NUMBER);
. 197
References
FK relationships vs. References:
create type CUSTOMER_TY as object
( customer_id NUMBER,
name VARCHAR2(25),
street VARCHAR2(50),
city VARCHAR2(25),
state VARCHAR2(2),
zip NUMBER);
. 198
References
FK relationships vs. References:
create view CUSTOMER_CALL as
select MAKE_REF(CUSTOMER_OV, customer_id) customer_id, call_number, call_date
from CUSTOMER_CALL;
select DEREF(ccov.customer_id)
from CUSTOMER_CALL_OV ccov
where call_date = trunc(sysdate);
. 199
Object PL/SQL
declare
cust1 CUSTOMER_TY;
begin
select VALUE(cov) into cust1 from CUSTOMER_OV cov where customer_id = 1;
dbms_output.put_line(cust1.name);
dbms_output.put_line(cust1.street);
end;
declare
newCust CUSTOMER_TY;
begin
newCust := CUSTOMER_TY(345, ‘NewCust’, ‘Street’, ‘City’, ‘ST’, 0);
insert into CUSTOMER_OV values(newCust);
end;
. 200
Large Objects
LONG – character data, 2 GB
LONG RAW – binary data, 2 GB
CLOB – character LOB, 4 GB
BLOB – binary LOB, 4 GB
NCLOB – CLOB with multi-byte character set support
BFILE – binary file, read-only binary data stored outside database, size OS dependent
. 201
Large Objects
storage(INITIAL 50K NEXT 50K PCTINCREASE 0)
tablespace PROPOSALS
LOB(proposal_text, budget) store as
( tablespace PROPOSAL_LOB
storage(INITIAL 100K NEXT 100K PCTINCREASE 0)
CHUNK 16K PCTVERSION 10 NOCACHE LOGGING);
CHUNK – Space allocated for each LOB manipulation. Default 1K, upto 32 K
PCTVERSION – Max % of overall LOB storage space used for creating new version of the LOB
NOCACHE – Not stored in memory
LOGGING – All operations against the LOB will be recorded in redo log files
. 202
Large Objects
Initialization:
BLOB – EMPTY_BLOB( )
CLOB/NCLOB – EMPTY_CLOB( )
BFILE – BFILENAME(<directory name>, <file name>);
Using Subqueries:
insert into PROPOSAL
select 3, ‘M/S XYZ’, ‘Credit Card Billing System’, NULL, proposal_text, budget, cover_letter
from PROPOSAL
where proposal_id = 1;
. 203
Large Objects
String Functions:
SUBSTR – select SUBSTR(proposal_text, 1, 10) from PROPOSAL where proposal_id = 1;
INSTR – select INSTR(proposal_text, ‘new’, 1, 1) from PROPOSAL where proposal_id = 3;
INITCAP – select INITCAP(proposal_text) from PROPOSAL where proposal_id = 3;
LTRIM/RTRIM – select LTRIM(proposal_text) from PROPOSAL where proposal_id = 1;
DBMS_LOB Package:
READ, WRITE
COPY, APPEND
ERASE
SUBSTR, INSTR, GETLENGTH, TRIM
COMPARE
. 204
Large Objects
READ:
declare
locator_var CLOB;
amount_var number;
offset_var number;
output_var varchar2(10);
begin
amount_var := 10;
offset_var := 1;
select proposal_text into locator_var
from PROPOSAL
where proposal_id = 1;
DBMS_LOB.READ(locator_var, amount_var, offset_var, output_var);
DBMS_OUTPUT.PUT_LINE(‘Start of proposal text: ‘ || output_var);
end;
. 205
Large Objects
WRITE:
declare
locator_var CLOB;
amount_var number;
offset_var number;
buffer_var varchar2(12);
begin
amount_var := 12;
offset_var := 10;
buffer_var := ‘ADD NEW TEXT’;
select proposal_text into locator_var
from PROPOSAL
where proposal_id = 3 for update;
DBMS_LOB.WRITE(locator_var, amount_var, offset_var, buffer_var);
end;
. 206
. 207