Confidential: Disclose and Distribute Solely To Qwest Employees
Confidential: Disclose and Distribute Solely To Qwest Employees
employees
1
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
- Block structuring
Qwest
Qwest
Variable Declaration over
NUMBER
Count
revenue
second_per_day
running _total
NUMBER;
NUMBER (9,2);
CONSTANT NUMBER := 60 * 60* 24 ;
NUMBER (10,0)
;= 0;
CHAR;
CHAR(10) NOT NULL := PEEBLES;
CONSTANT CHAR(12) := ORACLE;
anniversary
DATE ;= 05-NOV-78;
project_complexion DATE;
next_checkup
DATE NOT NULL ;= 28-JUN-90;
BOOLEAN
over_budget
available
Qwest
Attribute Declaration
PL/SQL objects (such as variables and constants) and
database objects(such as col. and tables )are associated with
certain attributes.
%TYPE attribute
Ex. DECLARE
books_printed
NUMBER (6);
books_sold
books_printed%TYPE ;
maiden_name
emp.ename%TYPE ;
Ex.
%ROWTYPE attribute
DECLARE
dept_row
dept%ROWTYPE ;
Qwest
Variable Assignment
PL/SQL Expressions consist of Variables, Constants,
Literals, and Function Calls.
Operation
ASSIGNMENT Syntax
plsql_variable := plsql_expression;
Quick notes -Assignment
1. := (ASSIGNMENT )= (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.
Qwest
Scoping Variables and Constants.
SCOPE refers to he 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 sub-blocks 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 subblock .However, the newly declared identifier has the
rules of scope defined in rule #1.
Qwest
Scoping Variables and Constants.
DECLARE
credit_limit CONSTANT NUMBER (6,2) : =2000;
account
NUMBER;
BEGIN
DECLARE
account
CHAR(10);
new_balance NUMBER (9,2);
BEGIN
new_balance
account
credit_limit
END;
DECLARE
account
CHAR(10);
new_balance NUMBER (9,2);
BEGIN
new_balance
account
credit_limit
END;
account
credit_limit
END;
Confidential: Disclose and distribute solely to Qwest
employees
11
Qwest
Qwest
SQL & PL/SQL Overview
SQL Data Manipulation Language statement support
1. INSERT
2. UPDATE
3. DELETE
4. SELECT
QuickNotes - SQL DML Support
1. The full ORACLE syntax is supported for these statements
2. A PL/SQL variable may be placed anywhere a constant may
be legally placed.
3. An identifier is first checked to see if it is a column in the
database . If not , it is assumed to be a PL/SQL identifier.
4.These statements may not appear as part of an expression.
Confidential: Disclose and distribute solely to Qwest
employees
13
Qwest
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
7644
TURNER
SAL
1500
EMPNO ENAME
7644
TURNER
7400
ALLEN
SAL
1500
1600
Qwest
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 = EMPOLEE OR TYPE =good_cust ;
END;
EMPNO ENAME
7644
TURNER
7400
ALLEN
SAL
1500
1600
EMPNO ENAME
7644
TURNER
7400
ALLEN
UPDATE
Confidential: Disclose and distribute solely to Qwest
employees
15
SAL
1500
1400
Qwest
SQL & PL/SQL Overview
DELETE
DECLARE
bad_child_type
BEGIN
CHAR(8) := NAUGHTY;
EMPNO ENAME
7644
TURNER
7400
ALLEN
SAL
1500
EMPNO ENAME
7644
TURNER
1600
DELETE
Confidential: Disclose and distribute solely to Qwest
employees
16
SAL
1500
Qwest
SQL & PL/SQL Overview
APPLICATION
EMPNO ENAME
7644
TURNER
7400
VAR1
ALLEN
SAL
1500
1600
VAR2
VAR3
Qwest
SQL & PL/SQL Overview
SELECT Syntax
SELECT col1,col2INTO var1,var2.. FROM table_name WHERE ...
SELECT Ex.
DECLARE
part_name
parts.name%TYPE;
num_in_stock
parts.num%TYPE;
BEGIN
SELECT name, num INTO part_name, num_in_stock FROM PARTS
WHERE part_id = 234;
----manipulate the retrieved data here
Confidential: Disclose and distribute solely to Qwest
employees
18
Qwest
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):
Qwest
Qwest
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.
1. Anything compared with NULL results in a NULL
value.
2. A NULL in an expression evaluates to NULL (except
concatenation)
Ex.
5 + NULL -evaluate to NULL PL/ || NULL ||
SQL evaluate to PL/SQL
PL /SQL Datatypes
NUMBER
CHAR
DATE
BOOLEAN
Operators
<,>
=, !=
<=, >=
Qwest
Logical Comparisons
Boolean Operators: AND ,OR,NOT
AND
TRUE
FALSE
NULL
TRUE
FALSE NULL
N
NOT
TRUE
FALSE
NULL
OR
TRUE
FALSE
NULL
TRUE
FALSE NULL
F
T
N
Qwest
If Statements
If statements are used to conditionally execute the
statement or sequence of statements.
IF Statements syntax
IF <condition> THEN <sequence of statement >
[ELSEIF <condition> THEN <sequence of statement > ]
---ELSEIFs may be repeated
[ELSE <sequence of statements>]
END IF;
QuickNotes -- IF Statements
Qwest
If Statements
Ex.
DECLARE
num_cnt NUMBER;
BEGIN
SELECT COUNT(*) INTO num_cnt FROM emp
WHERE deptno=&&deptno AND job =CLERK;
IF num_jobs> 5 THEN
UPDATE emp SET sal = 2000 WHERE deptno=&&deptno
AND job =CLERK;
ELSE
END IF;
COMMIT;
dbms_output.put_line(emp_cnt ||'employees are present');
END; Confidential: Disclose and distribute solely to Qwest
24
employees
Qwest
If Statements
BLOCK 1
BLOCK 2
IF a >= b THEN
do this ..;
ELSE
do_this.;
END IF;
IF b > a THEN
do that ..;
ELSE
do_this.;
END IF;
Qwest
Loop Statement Overview
Loops repeat a statement or sequence of
statements multiple times.
Four types of loop:
1. Simple Loops.
2. Numeric For Loops.
3. While Loops.
4. Cursor FOR Loops.
Qwest
Loop Statements
Simple Loops repeat sequence of statements multiple times.
Simple Loop syntax
Loop
<sequence of statement>
END LOOP ;---sometimes called an infinite loop
Qwest
Loop Statements Example
DECLARE
ctr NUMBER(4) := 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;
Confidential: Disclose and distribute solely to Qwest
28
employees
Qwest
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>
Qwest
Loop Statement
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
Example
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
i I N 1256 LOOP
x := x + i ;----legal
i := I + 5;----illegal
END LOOP;
Confidential: Disclose and distribute solely to Qwest
employees
30
Qwest
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.
Ex. 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;
Confidential: Disclose and distribute solely to Qwest
employees
31
Qwest
GO TO Statement Overview
GO TO Statements jump to a different place in the
PL/SQL block.
GO TO Statements have 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
Qwest
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
GOTO tour_brothers;
IF a > b THEN
b := b - a;
<<your_brothers>>
b : = b + c;
x := x - 1;
GOTO dinner;
END IF;
END IF;
Confidential: Disclose and distribute solely to Qwest
employees
33
a>b
LOOP
b := b + 1;
<<inner_loop >> WHILE
b>c
LOOP
c := c + 2 ;
EXIT outer_loop WHEN
c > 200 ;
Qwest
Cursor Overview
Every SQL DML statement processed by PL/SQL has an associated
CURSOR.
Two Types of CORSORS
1. EXPLICIT
. Multiple row SELECT STATEMENTS
2. IMPLICIT
All INSERT statements
All UPDATE statements
All DELETE statements
Single row SELECT.INTO Statements
The first column gets assigned to var1 , the second to var2 , etc .
STEP 4 . Close the cursor
Qwest
Explicit Cursors -FOR Loops
Cursor FOR Loops specify a sequence of statement 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 cursors name vs.
specifying a set of integers (i.e. 110)
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.
Confidential: Disclose and distribute solely to Qwest
employees
45
Qwest
Explicit Cursors -FOR Loops
Conceptual Cursor Loop Model
Loops
Loops
Loops
Qwest
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 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.
Confidential: Disclose and distribute solely to Qwest
48
employees
Qwest
Implicit Cursors
SQL %NOTFOUND
SQL %NOTFOUND Example
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 ;
SQL %FOUND
Qwest
Implicit Cursors
SQL%ROWCOUNT
SQL%ROWCOUNT Example
DELETE FROM baseball_team
WHERE batting _avg. < .100;
IF SQL%ROWCOUNT > 5 THEN
INSERT INTO temp(message)
VALUES(Your team needs helps .);
END IF;
SQL %ISOPEN always evaluate to FALSE.
Qwest
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 when a certain exception occurs.
When an exception handler is complete processing of the
block terminates.
Exception Overview
Two Types of Exceptions
1. PREDEFINED INTERNAL EXCEPTIONS
2. USER-DEFINED EXCEPTIONS
PL/SQLs Exception Handlers
vs.
Conventional Error Handling
Example
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
VALUES_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.
Confidential: Disclose and distribute solely to Qwest
54
employees
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>
Example
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
ROLLBACL;
INSERT INTO temp VALUES (NULL,NULL,Blake not found, or more than one Blake);
COMMIT;
WHEN OTHERS THEN
ROLLBACK;
Confidential:
END;
55
Exceptions Propagation
Propagation
Step #1 The current block is searched for a handler .If not found, go to step 2.
Step#2
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 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.
Confidential: Disclose and distribute solely to Qwest
employees
58
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
Exception A is handled
locally and execution
resumes in the outer
block
END;
WHEN B THEN
END;
Confidential: Disclose and distribute solely to Qwest
employees
59
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
...
Exception B
PROPAGATES to the
first outer block with an
appropriate handler
END;
WHEN B THEN
END;
Confidential: Disclose and distribute solely to Qwest
employees
60
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;
WHEN B THEN
..
END;
Exception C has no
handler and will result
in runtime unhandled
exception
EXCEPTION_INIT
Exceptions may only be handled by name (not ORACLE error
number).
EXCEPTION_INIT allows naming of nay ORACLE error.
SYNTAX
PRAGMA EXCEPTION_INIT(<user defined exception_name > ,
<ORACLE_error_number>);
Example
DECLARE
deadlock_detected
exception;
NUMBER;
sqlcode_val
CHAR(70);
BEGIN
EXCEPTION
WHEN OTHERS THEN
sqlcode _val := SQLCODE - - - cant insert
- - - directly.
sqlerrm_val := SQLERRM ; - - ditto
INSERT INTO temp VALUES(sqlcode_val, NULL,sqlerrm_val);
END;
Confidential: Disclose and distribute solely to Qwest
employees
65
Qwest
Creating a procedure
Argument Modes
IN
OUT
IN OUT
Creating a procedure
Example
CREATE PROCEDURE
fire_employee (empid NUMBER)
AS
BEGIN
DELETE
FROM emp
WHERE empno=
fire_employee.empid;
END
Tip:Write each procedure in a text file, and save(both P-code and source
code is saved in the database)
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;
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
fire_employee (:empno);
Confidential: Disclose and distribute solely to Qwest
employees
73
/*EXECUTE*/
NUMBER,
NUMBER,
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);
Confidential: Disclose and distribute solely to Qwest
employees
75
Legal
(7000,sal_incr=>500,bonus=>20);
update_sal
Illegal
(empno=>7000,
sal_incr=>500,20);
analysis terminated
1/33
2 rows selected
Confidential: Disclose and distribute solely to Qwest
employees
79
Debugging methods
Version 6
User INSERTS information into a user defined table, and
examines data
Version 7
PL/SQL will have methods of I/O to system defined
table(TIO$LINES)
TEXT_IO package
Rolls back or commits with transaction
DEBUG_IO package
Writes despite error, rollback,commit
Future
A PL/SQL debugger
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
Manual Recompilation
ALTER PROCEDURE
Procedure COMPILE
schema
Example
ALTER PROCEDURE
add_department COMPILE
Confidential: Disclose and distribute solely to Qwest
employees
87
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
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)
Dropping a procedure
DROP PROCEDURE
Procedure
schema
Example
DROP PROCEDURE fire_employee;
Need either
And
CREATE
CREATE
PROCEDURE or
CRETAE ANY
PROCEDURE
system privilege
ALTER
DROP
To do this
Need either
Execute a
Own the procedure
procedure or access or be granted
a package construct 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)
Benefits of Procedures
Security
Executes under security domain of procedures owner
Provides controlled indirect access to database objects to nonprivileged 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
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
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
Package
A database object that groups related package constructs
Procedures
functions
cursor definitions
variables and constants
exception definitions
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
Definition of
public constructs
PACKAGE hire_fire IS
PROCEDURE hire_employee (. .);
PROCEDURE fire_employee (. .);
valid CHAR(1);
END;
PACKAGE BODY hire_fire IS
PROCEDURE hire_employee (. .);
IS
BEGIN. . . END;
PROCEDURE fire_employee ( . .)
IS
BEGIN . . . END;
Definition of
private
function
FUNCTION check_num (. . )
RETURN. .
IS
BEGIN . . END;
Confidential:
END; Disclose and distribute solely to Qwest
employees
99
Package PK
Variable C
Package
specification
Procedure A
x :=pk.c;
Variable D
Package
Procedure B
body
y :=d;
z :=c;
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
Limit indirect dependencies
(continued)
Dropping a Package
Procedure
schema
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
Benefit Of Package
Productivity
Stores related procedures and function
together
Easier to manger changing the specification
or definition of a construct.
Reduces cascading dependencies
Dependencies are at package ,not
procedure level
Can change package body with
changing or affecting package
specification
Confidential: Disclose and distribute solely to Qwest
employees
108
Qwest
Ref Cursors
A REF CURSOR is majorly used when we want to
execute a dynamic select statement causes to
retrieve more than one record. We can pass Ref
cursor result as a out parameter which can be
used in other subprograms.
CREATE OR REPLACE PACKAGE CURSPKG AS
TYPE T_CURSOR IS REF CURSOR;
PROCEDURE OPEN_ONE_CURSOR (N_EMPNO IN NUMBER,
IO_CURSOR IN OUT T_CURSOR);
PROCEDURE OPEN_TWO_CURSORS(EMPCURSOR OUT T_CURSOR,
DEPTCURSOR OUT T_CURSOR);
END CURSPKG;
/
See Example
Confidential: Disclose and distribute solely to Qwest
employees
110
Ref Cursors
A ref cursor refers to server memory. The memory address
represented by a ref cursor "lives" on the database server, not
on the client machine. Therefore, the client's connection to the
database must be in place during the lifetime of the ref cursor.
If the underlying connection to the database is closed, the ref
cursor will become inaccessible to the client.
A ref cursor involves an additional database round trip.
Because a ref cursor is a pointer to memory on the server that
is returned to the client, the actual data contained in the ref
cursor is not initially returned to the client. The client must
request the data contained in the ref cursor after it has opened
the ref cursor. Note that data will not be retrieved until the
user attempts to read it.
Ref Cursors
A ref cursor is not updatable. The result set represented by the
ref cursor is read-only. You cannot update the database by
using a ref cursor.
A ref cursor is not backward scrollable. The data represented
by the ref cursor is accessed in a forward-only, serial manner.
You cannot position a record pointer inside the ref cursor to
point to random records in the result set.
A ref cursor is a PL/SQL datatype. You create and return a ref
cursor inside a PL/SQL code block.
Collection
PL/SQL offers these collection types:
Index-by tables or Associative arrays, let you look up
elements using arbitrary numbers and strings for subscript
values. (They are similar to hash tables in other programming
languages.)
type my_tab_t is table of number index by pls_integer;
type my_tab_t is table of number index by varchar2(4000);
declare
TYPE phone_no_tab IS TABLE OF VARCHAR2(20) INDEX BY BINARY_INTEGER;
phone_nos phone_no_tab;
begin
phone_nos(1) := '+44 (0) 117 942 2508';
dbms_output.put_line('phone_no(1) is '||phone_nos(1));
end;
Collection
COUNT: This function returns the number of elements (cells) in the collection
DELETE: This procedure with no parameters deletes all the elements in the collection, as
with nested tables, though, we can specify a start and end point to say which element(s)
is (are) to be deleted. After deleting an element or the whole collection, any subsequent
attempt to read that element in the collection generates "ORA-01403: no data found".
However you can write to any element without any errors as this re-creates the element
EXISTS(n) : used to determine if the specified element has been created and not deleted,
returns TRUE if the element exists, FALSE if not. The index variable can be either a
number of type BINARY_INTEGER or a character string of type VARCHAR2
FIRST : returns the subscript of the first element in the PLSQL associative array
LAST : returns the subscript of the last element in the PL/SQL associative array
PRIOR(n): returns the subscript of the previous element in the PL/SQL associative array
or NULL if if no more elements exist
NEXT(n) : returns the subscript of the next element in the PLSQL associative array or
NULL if no more elements exist.
See Example
Collection
PL/SQL offers these collection types:
Nested tables hold an arbitrary number of elements. They
use sequential numbers as subscripts. You can define
equivalent SQL types, allowing nested tables to be stored in
database tables and manipulated through SQL.
Nested table is a table that is stored in database as the data of
a column of the table. Nested
table is like an Index-By table, but the main difference is that
a nested table can be stored in
the database and an Index-by table cannot.
Nested table extends Index-by table by allowing the operations
such as SELECT, DELETE,
UPDATE and INSERT to be performed on nested table.
See example,
create table emp
( empno number(5),
ename varchar2(30),
projects projecttable
)
nested table projects store as projects_nt;
Collection
PL/SQL offers these collection types:
See example
employees
Qwest
Ref Cursors
SELECT
extract(xmldata,
'/DocumentElement/Emp_Details/Emp_Cuid').getStringVal()
"CUIDS"
FROM xml
Ref Cursors
DECLARE
poxml XMLType;
cname varchar2(200);
pono number;
pname varchar2(100);
shipstreet varchar2(100);
shipcity varchar2(30);
shipzip varchar2(20);
BEGIN
-- select the adt instance
SELECT poDoc INTO poxml FROM po_xml_tab p;
cname := poxml.extract('//CUSTOMER/@CUSTNAME').getstringval();
pono := poxml.extract('/PO/PONO/text()').getnumberval();
pname := poxml.extract('/PO/PNAME/text()').getstringval();
shipstreet := poxml.extract('/PO/SHIPADDR/STREET/text()').getstringval();
shipcity := poxml.extract('//CITY/text()').getstringval();
shipzip := poxml.extract('//ZIP/text()').getstringval();
INSERT INTO po_rel_tab
VALUES (pono, pname,
(SELECT custid FROM cust_tab c WHERE custname = cname),
shipstreet, shipcity, shipzip);
END;
/
Confidential: Disclose and distribute solely to Qwest
employees
119
Qwest
Triggers
What a Trigger is
Application
UPDATE
UPDATE tt
SET
SET.;
.;
INSERT
INSERT
Database
UPDATE(trigger)
UPDATE(trigger)
Table T
INSERT(trigger)
INSERT(trigger)
INTO
INTO t..;
t..;
DELETE
DELETE
FROM
FROM t;
t;
DELETE(trigger)
DELETE(trigger)
What a Triggers is
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
Confidential: Disclose and distribute solely to Qwest
employees
123
NUMBER;
maxsal NUMBER;
BEGIN
/* get min and max salaries for the employees job from the SAL_GUIDE*/
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
Types of triggers
How to use each type
BEFORE statement trigger
To initialize global variables used in triggers
To prevent update before it occurs
For auditing
(by value,by row)
AFTER
row trigger
Used by ORACLE snapshot mechanism)
For auditing
AFTER
statement trigger
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. . .
Notes:
Values available in row triggers only
New and old both available for UPDATE
The old value in an INSERT is NULL
T he new value in a DELETE is NULL
BEFORE row trigger can assign values to :NEW if it is not set by UPDATE
SET clause or INSERT VALUES list
Can replace: NEW and :old with other correlation names if desired
Colon dropped in when clauses
Confidential: Disclose and distribute solely to Qwest
employees
131
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)
Expressions in triggers
Restrictions on triggers
Maximum number of 12 triggers for a table
Up to three(INSERT/UPDATE/DELETE)triggers of each type
Restrictions on triggers
Original EMP
Mutating tables
ENAME
ENAME
SAL
SAL
SMITH
SMITH
JONES
JONES
1000
1000
1000
1000
mutating EMP
ENAME
ENAME
SAL
SAL
SMITH
SMITH
JONES
JONES
1100
1100
1000
1000
UPDATE emp
SET sal = sal *1.1;
UPDATE(trigger)
SELECT sal
FROM emp
WHERE
Disabled
Does not execute its triggered action
ALTER TRIGGER
trigger
schema
ENABLE
DISABLE
Examples
ALTER TRIGGER reorder DISABLE;
ALTER TRIGGER reorder ENABLE;
table
ALTER TABLE
schema
ENABLE
trigger
DISABLE
trigger
schema
Examples
ALTER TABLE INVENTORY
DISABLE TRIGGER REORDER;
ALTER TABLE INVENTORY
ENABLE TRIGGER REORDER;
Confidential: Disclose and distribute solely to Qwest
employees
139
Dropping Triggers
trigger
DROP TRIGGER
schema
Example
DROP TRIGGER reorder;
Recompiling a trigger
trigger
ALTER TRIGGER
COMPILE
schema
Applications of triggers
Maintaining derived fields
Implementing complex security rules
Enforcing complex business rules
Performing value-based auditing
Making implied changes
Maintaining table replication
provided by an