PL SQL-4
PL SQL-4
10 April 2012
Course Pre-requisites
A basic understanding of SQL in Oracle Understanding of a procedural language
Course Objectives
To provide an overview of PL-SQL in Oracle
Session Outline
Introduction Variable Declaration SQL in PL/SQL Conditional & Iterative Control Cursors Exception Handling Procedures & Packages Triggers ORDBMS
PL/SQL Introduction
PL/SQL BLOCK DECLARE Procedural Procedural BEGIN Procedural SQL Procedural SQL END;
PL/SQL BLOCK DECLARE Procedural Procedural BEGIN Procedural SQL Procedural SQL END; PROCEDURAL STATEMENT
EXECUTOR
DECLARE
BEGIN
EXCEPTION
END
Quick Notes - Variable Declaration 1. The rules for identifiers are same as for SQL objects. 2. NOT NULL/CONSTANT may be optionally used
10
11
Attribute Declaration
PL/SQL objects (such as variables and constants) and database objects (such as columns and tables ) are associated with certain attributes. %TYPE attribute DECLARE books_printed NUMBER (6); books_sold books.sold%TYPE ; maiden_name emp.ename%TYPE ; %ROWTYPE attribute DECLARE dept_row
dept%ROWTYPE ;
12
Variable Assignment
PL/SQL Expressions consist of Variables, Constants, Literals, and Function Calls. ASSIGNMENT Syntax plsql_variable := plsql_expression; Quick notes -Assignment 1. := (ASSIGNMENT ) whereas = (VALUE EQUALITY)
2. The datatype of the left and right hand side of an assignment must be the same or implicitly convertible to each other.
For ex. , N:=7 is legal because number may be implicitly converted to char.
3. Column or table reference are not allowed on either side of an assignment operator( : = ).
SCOTT.EMP.EMPNO := 1234; location := dept.loc.;
13
Scoping
SCOPE refers to the visibility of identifiers at different points in the PL/SQL block.
SCOPING RULES:
1. An identifier is visible in the block in which it is declared and all its subblocks unless rule #2 applies. 2. If an identifier in an enclosing block is redeclared in a sub-block, the original identifier declared in the enclosing block is no longer visible in the sub-block .However, the newly declared identifier has the rules of scope defined in rule #1.
14
15
16
17
SAL 1500
UPDATE
19
SAL 1500
DELETE
20
VAR3
QuickNotes - SELECT INTO 1. A SELECT statement is the only DML that returns data. You must provide location for this data to be stored via the INTO clause. 2. A SELECT..INTO statement must return exactly one row. Zero or multiple returned rows result in an error. 3. For multi-row SELECTs use cursors.
21
E.g.
DECLARE
part_name num_in_stock parts.name%TYPE; parts.num%TYPE;
BEGIN
SELECT name, num INTO part_name, num_in_stock
FROM PARTS
WHERE part_id = 234; -- manipulate the retrieved data here
22
Transaction processing
SAVEPOINT Syntax
SAVEPOINT <marker_name>;
ROLLBACK TO Syntax
ROLLBACK [WORK] TO SAVEPOINT <marker_name>;
23
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) INSERT INTO phonebook (lastname) VALUES (UPPER(my_lastname)); Other SQL Functional Support (outside of a SQL Statement):
MOST ORACLE SQL functional are available (except for group functions).
X := SQRT(y); lastname := UPPER (lastname); age_diff := MONTHS_BETWEEN(birthday1,birthday2)/12;
24
25
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.
<,>
=, != <=, >=
26
IF Statements
IF Statements are used to conditionally execute the statement or sequence of statements.
IF Statement Syntax IF <condition> THEN <sequence of statements > [ELSEIF <condition> THEN <sequence of statements> ] -- ELSEIFs may be repeated [ELSE <sequence of statements>] END IF;
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
27
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;
28
IF Statements
BLOCK 2 . IF a < b THEN do_that ..; ELSE
IF a >= b THEN
do_this ..; ELSE do_that.; END IF;
do_this.;
END IF;
Given any pair of non-NULL values for a andb, will Block 1 and Block 2 do the same thing? What if either a orb (or both) is NULL?
29
30
Loop Statements
Simple Loops repeat sequence of statements multiple times.
Simple Loop Syntax Loop <Sequence of Statements> END LOOP ; -- sometimes called an infinite loop
Exit statements exit any type of loop immediately Exit Syntax EXIT [WHEN <condition >]; -- infinite loop insurance
31
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;
32
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;
33
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 2130 LOOP /* redeclare s my_index*/ INSERT INTO temp(coll.)VALUES (my_index); /* insert the numbers 30 through 21*/ END LOOP; END;
FOR
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; QuickNotes - WHILE Loops 1. The term <condition> may be any legal PL/SQL condition (i.e. it must return a Boolean value of TRUE, FALSE or NULL) 2. The sequence of statements will be repeated as long as <condition> evaluates to TRUE 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;
35
GO TO Statement Overview
GO TO Statements jump to a different place in the PL/SQL block. GO TO Statements have 2 parts 1. The GOTO statement itself. 2. A statement label
GO TO Statement Syntax
<<label_name >> X :=X+1 ; - - statement label GOTO LABEL_NAME - - JUMPS TO x := x +1
36
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)
<<dinner>>
x := x + 1 ; y := y + 1; IF a >= b THEN
b : = b + c;
GOTO dinner; END IF;
END IF;
37
40
<< compute_loop >> For i IN 110 LOOP < statements . > DECLARE i NUMBER := 0 ; BEGIN INSERT INTO temp VALUES (i, compute_loop.i, COMPLETE ); END; END LOOP compute_loop; - must include loop name here
41
c := c + 2 ;
EXIT outer_loop WHEN c > 200 ; END LOOP inner_loop;
42
PL/SQL Cursors
43
Cursor Overview
Every SQL DML statement processed by PL/SQL has an associated CURSOR. Two Types of CURSORS 1. EXPLICIT Multiple row SELECT STATEMENTS 2. IMPLICIT All INSERT statements All UPDATE statements All DELETE statements Single row SELECT.INTO Statements
44
Cursor Declaration Example DECLARE X NUMBER ( 7, 2 ) ; total NUMBER ( 5 ) lower_sal_limit CONSTANT NUMBER ( 4 ) := 1200 ; CURSOR c1 IS SELECT ename FROM emp WHERE sal > lower_sal_limit ; BEGIN ...
45
1. Retrieves one row of data from the cursor and stores it in the specified variables (similar to how a single-row select works) 2. There must be exactly one INTO variable for each column selected by the SELECT statement 3. The first column gets assigned to var1 , the second to var2 , etc .
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 ;
47
49
50
Loops
Loops
Loops
When there are no more rows left to FETCH, an implicit CLOSE cursor_name is executed and the loop is exited.
51
This includes : 1. ALL INSERT statements 2. ALL UPDATE statements 3. ALL DELETE statements 4. ALL SELECTINTO 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 dont apply. 3. All cursor attributes apply.
53
Implicit Cursors
SQL %NOTFOUND E.g. UPDATE emp SET sal = sal * 10.0 WHERE ename =WARD ; IF SQL %NOTFOUND THEN -- WARD wasnt found INSERT INTO emp (empno, ename ,sal) VALUES ( 1234,WARD 99999 ); END IF ;
54
Implicit Cursors
SQL%ROWCOUNT
E.g. DELETE FROM baseball_team
55
56
Exception Overview
In PL/SQL error are called exceptions
When an exception is raised, processing jumps to the exception handlers An exception handler is a sequence of statements to be processed
57
Exception Overview
Two Types of Exceptions 1. PREDEFINED INTERNAL EXCEPTIONS 2. USER-DEFINED EXCEPTIONS
58
59
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;
Exception Handlers
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
63
Exceptions Propagation
Example 1
BEGIN ...
BEGIN IF X=1 THEN RAISE A: ELSEIF X=2 THEN RAISE B; ELSE RAISE C; EXCEPTION WHEN A THEN ... END; EXCEPTION ... END;
WHEN B THEN
Exception A is handled locally and execution resumes in the outer block
64
Exceptions Propagation
Example 2
BEGIN ...
BEGIN IF X=1 THEN RAISE A: ELSEIF X=2 THEN RAISE B; ELSE RAISE C; EXCEPTION WHEN A THEN ... END; EXCEPTION ... END;
WHEN B THEN
Exception B handled and control is passed back to the calling environment Exception B PROPAGATES to the first outer block with an appropriate handler
65
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
WHEN B THEN ..
Exception C has no handler and will result in runtime unhandled exception
END;
66
67
DECLARE
sqlcode_val sqlcode_val NUMBER; CHAR(70);
BEGIN
EXCEPTION WHEN OTHERS THEN sqlcode _val := SQLCODE; -- cant insert directly sqlerrm_val := SQLERRM ; - -- cant insert directly INSERT INTO temp VALUES(sqlcode_val, NULL, sqlerrm_val); END;
69
70
Collections of SQL and PL/SQL statements Stored in complied from in the database Can call other procedures
71
Procedure Arguments
Argument Modes
IN OUT
Data value comes in from the calling process and is not changed No data value comes in from the calling process; on normal exit ,value of argument is passed back to caller Data value comes in from the calling process, and another value is returned on normal exit
IN OUT
73
Creating a Procedure
E.g.
CREATE PROCEDURE fire_employee (empid NUMBER) AS BEGIN DELETE FROM emp WHERE empno= fire_employee.empid; END
74
Creating a Function
E.g.
CREATE FUNCTION
get_bal (acc_no NUMBER(4)) RETURN IS acc_bal NUMBER(11,2); NUMBER(11,2);
BEGIN
SELECT balance INTO acc_bal FROM accounts WHERE account_id_no=acc_no; RETURN (acc_bal); END;
75
Statements in procedures
Valid statements in a procedure or function
SQL DML or PL/SQL statements
Calls to other procedures and functions stored in the database Calls to other procedures and functions in a remote database Restricted statements
DDL
Dynamic SQL In trigger, COMMIT, SAVEPOINT and ROLLBACK
76
77
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);
78
79
80
81
analysis terminated
2 rows selected
82
PACKAGE BODY
LINE:line number where error occurs TEXT:text of error
83
sys.standard_utilities.
raise_application_error
84
85
86
87
Recompilation
Procedure/function can be recompiled be either
RDBMS automatically, when next accessed (only if marked for recompilation) Manually by the user, using ALTER PROCEDURE command
88
Manual Recompilation
ALTER PROCEDURE
Procedure COMPILE
schema
Example
ALTER PROCEDURE
add_department COMPILE
89
Changing a Procedure
To modify a procedure, replace it:
CREATE OR REPLACE PROCEDURE fire_employee AS . . . END;
OR REPLACE option:
Recreates the procedure even if it already exists
90
Dropping a Procedure
DROP PROCEDURE
Procedure
schema
Example
DROP PROCEDURE fire_employee;
91
Procedure executes under the authority of owner, not user executing procedure User of procedure need not have access to objects inside procedure Can only GRANT privileges on an entire package, not a procedure, function, or variable defined in the package
92
ALTER
DROP
93
Need either Own the procedure or be granted EXECUTE PRIVILEGE or EXECUTE ANY PROCEDURE system privilege
And Procedure owner must be explicitly granted access to all database objects in the procedure(not through roles)
94
Benefits of Procedures
Security
Executes under security domain of procedures owner Provides controlled indirect access to database objects to non- privileged users
Integrity
Defines allowed operations on data
Performance
Reduces number of calls to thedatabase
95
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
96
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
97
Package
A database object that groups related package constructs
Procedures functions cursor definitions variables and constants exception definitions
98
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
99
100
101
Package specification
Procedure A x :=pk.c;
102
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
103
104
(continued)
106
sports_club.add (employee)
END IF; ELSIF action =FIRE THEN scott.hire_fire.fire_employee (employee); sports_club.remove (employee); END IF;
107
Dropping a Package
DROP PACKAGE
PROCEDURE
schema
Example
DROP PACKAGE hire_fire;
108
Benefit Of Package
Performance Reduces disk I/O for subsequent calls - First call to package loads whole package into memory
Benefit Of Package
Productivity
Stores related procedures and function together
110
PL/SQL Triggers
111
Triggers
Definition
Creating Triggers
Restrictions on Triggers Dropping and recompiling
112
Trigger Definition
Application UPDATE t SET .; INSERT INTO t..; Table T
INSERT(trigger)
Database
UPDATE(trigger)
DELETE
FROM t;
DELETE(trigger)
113
What is a Trigger
A user-defined PL/SQL block associated with a specific table, and implicitly fired (executed) when a triggering statement is issued against the table Made up of parts - Triggering event (INSERT/UPDATE/DELETE) - Trigger type (BEFORE/AFTER, per statement or per row) - Trigger restriction (optional) * WHEN clause - Trigger action * PL/SQL BLOCK Not the same as a SQL * Forms trigger
114
115
116
117
Types of Triggers
Type of a trigger determines
The time when the trigger fires
BEFORE trigger: before the triggering action AFTER trigger: after the triggering action The item the trigger fires on Row trigger: once for each row affected by the triggering statement Statement trigger: once for the triggering statement, regardless of the number rows affected
Types of Triggers
How to use each type BEFORE statement trigger
To initialize global variables used in Triggers
To prevent update before it occurs
120
121
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: Values available in row Triggers only
122
Expressions in Triggers
Conditional Predicates
If a trigger can fire on more than one type of DML operation use pre defined PL/SQL boolean variables to determine which caused the trigger to fire: IF INSERTING . . . IF UPDATING . . . IF DELETING . . . To detect which column is being updated: IF UPDATING (columnname)
123
Expressions in Triggers
CREATE TRIGGER total_salary
END IF;
END;
124
Restrictions on Triggers
Maximum number of 12 Triggers for a table
Up to three (INSERT/UPDATE/DELETE) Triggers of each type
125
Restrictions on Triggers
Original EMP
ENAME
SMITH JONES
Mutating tables
SAL
1000 1000
mutating EMP
ENAME
SMITH JONES
SAL
1100 1000
A table that is being modified by an UPDATE, DELETE, or INSERT in a single user statement
A trigger cannot SELECT from or change a mutating table (except current row, using :NEW and :OLD)
126
Restrictions on Triggers
Changes to updated/inserted values
EMPNO
0450 0407
DEPTNO
20 10
UPDATE (trigger)
A trigger cannot change values explicitly referenced in the UPDATE statement SET clause or INSERT statement
127
Executes its triggered action if both: an appropriate statement is issued. trigger WHEN clause evaluates to TRUE(if present). Disabled
Does not execute its triggered action
128
Have to load a large amount of data, and want to proceed quickly without firing Triggers
Example: SQL*Loader using direct path automatically disables Triggers
Want to INSERT, UPDATE or DELETE on a table whose trigger references a database object that is not available
129
trigger
ENABLE DISABLE
Examples
ALTER TRIGGER reorder DISABLE;
130
ALTER TABLE
SCHEMA ENABLE TRIGGER SCHEMA
TABLE
TRIGGER
DISABLE
Examples
ALTER TABLE INVENTORY
DISABLE TRIGGER REORDER; ALTER TABLE INVENTORY ENABLE TRIGGER REORDER;
131
Dropping Triggers
DROP TRIGGER SCHEMA TRIGGER
Example
DROP TRIGGER reorder;
132
Recompiling a trigger
ALTER TRIGGER SCHEMA TRIGGER COMPILE
Example
ALTER TRIGGER reorder COMPILE;
133
Applications of Triggers
Maintaining derived fields
134
135
CREATE TRIGGER upper_soundex BEFORE INSERT OR UPDATE OF ename, uppername, soundexname ON emp ; FOR EACH ROW BEGIN :NEW.uppername := UPPER (:NEW.ename); :NEW.soundexname := :SOUNDEX(:NEW.ename); END;
136
137
138
139
140
141
Logons
142
143
PENDING_ORDERS
PART_NO
00234 00342
ORD_QTY
15 25
ORD_DATE
15-JAN-92 15-JAN-92
INVENTORY
PART_NO ON_HAND
00234 00342 34 52
REORD_PT
30 50
REORD_QTY
15 25
Transparently perform an action when a triggering is executed Example: Inventory check generates a new order
144
145
EMP_REP1
EMP_REP2
UPDATE...
UPDATE...
146
Benefits of Triggers
Security
Allows sophisticated security checking Enables customized auditing mechanism to be built
Integrity
Ensures related operations on data are performed together
147
Benefits of Triggers
Performance
Reduces number of calls to the RDBMS Decreases network traffic
Memory savings
Takes advantage of shared SQL
Productivity
Requires only a single copy of the code be written and maintained(not multiple copies in client applications)
148
PL/SQL ORDBMS
149
Benefits:
Reusability Adherence to Standards
150
Types of Objects
Abstract Datatypes
Object Views
Varying Arrays Nested Tables
References
Large Objects
151
Abstract Datatypes
Grouping related columns (subtypes) into objects create type ADDRESS_TY as object
( street
city state zip
VARCHAR2(50),
VARCHAR2(25), VARCHAR2(2), NUMBER);
address ADDRESS_TY);
Owner needs to grant EXECUTE privilege on the Datatype to other users for them to use it
152
Abstract Datatypes
Table creation: create table CUSTOMER
( customer_id
person
NUMBER,
PERSON_TY);
Table can be described using set describe depth to 2, 3 etc. in order to view the attributes for abstract datatypes Insert operation: insert into CUSTOMER values ( 1, PERSON_TY(Peter, ADDRESS_TY(Street S, City C, ST, 11111)));
153
Abstract Datatypes
Select operation: select customer_id, c.person.name from customer c; select c.person.name, c.person.address.city from customer c
154
Object Views
The ability to overlay object oriented structures on existing relational tables
create table CUSTOMER ( customer_id name street city NUMBER VARCHAR2(25), VARCHAR2(50), VARCHAR2(25), PRIMARY KEY,
state
zip ( street city state zip
VARCHAR2(2),
NUMBER); VARCHAR2(50), VARCHAR2(25), VARCHAR2(2), NUMBER);
155
Object Views
create type PERSON_TY as object ( name address VARCHAR2(25), ADDRESS_TY);
from customer
where state = DE; /* optional */
156
Object Views
Relational Insert operation:
insert into CUSTOMER values (123, Richard, 12 Farmside Close, Lewiston, NJ, 4352);
157
Object Views
INSTEAD OF Triggers:
BOOKSHELF_AUTHOR (title, author);
BOOKSHELF_PUBLISHER (title, publisher); create view AUTHOR_PUBLISHER as
update AUTHOR_PUBLISHER
set publisher = MARINER where author = HARDY; Gives error ORA-01779
158
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
Object Views
Methods:
create type ANIMAL_TY as object ( breed VARCHARE2(25),
name
VARCHAR2(25),
end;
end;
160
Object Views
Data Security:
create type ANIMAL_TY as object ( breed VARCHARE2(25),
name
VARCHAR2(25),
birthdate DATE, member function age(birthdate IN DATE) return NUMBER, PRAGMA RESTRICT_REFERENCES(age, WNDS)); WNDS = Write No Database State RNDS = Read No Database State WNPS = Write No Package State
161
Object Views
Using Methods:
create table ANIMAL ( Id animal NUMBER, ANIMAL_TY);
insert into ANIMAL values (11, ANIMAL_TY(Cow, Mimi, TO_DATE(01-JAN-1998, DD-MM-YYYY))); select a.animal.age(a.animal.birthdate) from animal;
162
Varying Arrays
create type TOOLS_VA as varray(5) of TOOL_TY; /* Using abstract datatype */ create type TOOLS_VA as varray(5) of VARCHAR2(25); /* Using base datatype */ create table BORROWER ( name tools VARCHAR2(25) TOOLS_VA); PRIMARY KEY,
USER_COLL_TYPES
163
Varying Arrays
Insert Operation:
insert into BORROWER values (AMY, TOOLS_VA(Hammer, Sledge, Axe)); insert into BORROWER values (DAVID, TOOLS_VA(Hammer, Axe, NULL, NULL, NULL));
164
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;
165
Varying Arrays
Select Operation Using Table Function:
select b.name, n.*
NAME
AMY AMY AMY
COLUMN_VALUE
HAMMER SLEDGE AXE
DAVID
DAVID
HAMMER
AXE
166
Nested Tables
A Table within a Table
create type ANIMAL_TY as object ( breed name birthdate VARCHAR2(25), VARCHAR2(25), DATE);
create type ANIMAL_NT as table of ANIMAL_TY; create table BREEDER ( breedername animals VARCHAR2(25), ANIMAL_NT)
167
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)
));
168
Nested Tables
Select Operation: Using Table Function:
select breedername, n.name, n.birthdate
from BREEDER, TABLE(breeder.animals) n; select breedername, n.name, n.birthdate
169
References
Column Objects vs. Row Objects:
Column objects are embedded objects represented as columns in tables Based on extensions of features already in database
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
170
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
name
birthdate
VARCHAR2(25),
DATE);
171
References
Insert Operation:
insert into ANIMAL values ( ANIMAL_TY(MULE, FRANCES, 01-APR-02));
Select Operation:
select name from ANIMAL;
Update Operation:
update ANIMAL set birthdate = 01-MAY-01 where name = FRANCES;
Delete Operation:
delete from ANIMAL where name = FRANCES;
172
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)
REF(a) -----------------------------------------------------------------------------------0000280209FFD8EC317DA111D6B008444456464GF2452525032
173
References
DEREF Function:
Opposite of REF Takes as input a reference value (OID) and returns the value of the row object create type ANIMAL_TY as object
( breed
name birthdate create table KEEPER ( keepername animalkept
VARCHAR2(25),
VARCHAR2(25), DATE);
174
References
DEREF Function:
insert into KEEPER select CATHERINE, REF(a) from ANIMAL a where name = FRANCES; select * from KEEPER; Output: CATHERINE 0000280209FFD8EC317DA111D6B008444456464GF2452525032
select DEREF(k.animalkept) from KEEPER k where keepername = CATHERINE; Output: ANIMAL_TY(MULE, FRANCES, 01-APR-02)
175
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
176
References
FK relationships vs. References:
create table CUSTOMER ( customer_id name NUMBER constraint CUSTOMER_PK PRIMARY KEY, VARCHAR2(25),
street
city state zip
VARCHAR2(50),
VARCHAR2(25), VARCHAR2(2), NUMBER);
constraint CUSTOMER_CALL_PK PRIMARY KEY(customer_id, call_number), constraint CUSTOMER_CALL_FK FOREIGN KEY(customer_id) REFERENCES CUSTOMER(customer_id));
177
References
FK relationships vs. References:
create type CUSTOMER_TY as object ( customer_id name street NUMBER, VARCHAR2(25), VARCHAR2(50),
city
state zip
VARCHAR2(25),
VARCHAR2(2), NUMBER);
178
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
179
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;
180
Large Objects
LONG character data, 2 GB LONG RAW binary data, 2 GB
proposal_name
short_description proposal_text budget
VARCHAR2(25),
VARCHAR2(1000), CLOB, BLOB,
cover_letter
BFILE)
181
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
182
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;
183
String Functions:
Large Objects
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;
DBMS_LOB Package:
READ, WRITE COPY, APPEND ERASE
184
Large Objects
READ:
declare locator_var amount_var 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; CLOB; number;
185
Large Objects
WRITE:
declare locator_var amount_var 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;
186
CLOB; number;
Summary
Introduction Variable Declaration SQL in PL/SQL Conditional & Iterative Control Cursors Exception Handling Procedures & Packages Triggers ORDBMS
187
References
PL-SQL programming Scott Urman, et al http://www.orafaq.com/faqplsql.htm
188