You are on page 1of 24

********************************************************************************

*******
DML := (Data Manipulation Language).
A Slash (/) sign at the end of the code indicates the termination of the code.
********************************************************************************
*******
Partition Applications
(The process of separating code and placing individual program units on
a server or client)
You can store program units on the server or the clients depending on you needs.
(A program unit stored on an Oracle server is accessible to all the appl
ications on client nodes).
(When the program unit is stored on a client node, the unit can referenc
e program units on the same client node as well as program unit on the server).
A program unit is stored on the server when:
-The code is SQL-intensive and contains a large number of DML and SELECT stateme
nts.
(Typically you store database triggers on the server).
(Can be a procedure, a function, a package, or a database trigger).
-The program unit does not need to reference Developer applications objects or b
uilt-in subprograms.
-The program unit is needed by many applications on the server and client nodes.
-You need to implement system-wide rules.
(Such as database trigger on the Oracle server).
-The program unit needs to use features not available in Oracle application tool
s.
When you store a program unit on the server:
-The program unit is processed by the PL/SQL engine within the Oracle server.
-Client/server traffic is reduced.
(Program units stored on the client are transfered to the server for par
sing and execution, this resutls in client/server traffic, to reduce that traffi
c place program units on the server).
-The program unit can only reference server-side objects.
(Client-side objects are inaccessible to the program units stored on the
database server).
-Users must have the EXECUTE privilege on the program unit, unless the user is t
he owner.
(When a user is not the owner of a program unit, the user needs the EXEC
UTE privilege to access and use the program unit sotred on the database server).
A program unit stored on a client-side:
-Needs a database connection only if SQL calls or server-side call are made.
-Can reference server-side and Developer objects.
(Server-side objects such as tables, views, sequences, and packages).
(Developer objects such as form variables and form built-in packages).
-Sends SQL statements for parsing and execution.
-Is processed by the PL/SQL engine in the client application.
(The Oracle Developer Forms and Procedure Builder are examples of client
applications processes).
-Can call both server-side and other client-side program units.
(This includes Developer built-in programs stored on the same client nod
e).
_______________________________________________________________________
Exceptions
1.-Predefined Oracle server exceptions.
2.-Non-predefined Oracle server exceptions.
3.-User-defined exceptons.
Predefined exceptions examples:
-NO_DATA_FOUND
-TOO_MANY_ROWS
-INVALID_CURSOR
-ZERO_DIVIDE
-DUP_VAL_ON_INDEX
Non-Predefined exceptions features:
-Unnamed Oracle server exceptions.
-20000 exceptions.
-Server raises the exception implicitly.
Trapping Non-predefined Oracle server exceptions:
DECLARE
<name> EXCEPTION;
PRAGMA_EXCEPTION_INIT (<name>,<Oracle error number>);
--Any further declarations
BEGIN
--Statements
EXCEPTIONS
WHEN <name> THEN
-Statements for handler
END;
Example use of a User-Defined Exception
DECLARE
<name> EXCEPTION;
--Any further declarations
BEGIN
--Statements
IF SQL%NOTFOUND THEN
RAISE <name>;
END IF;
--Statements
EXCEPTIONS
WHEN <name> THEN
--Statements for handler
END;
__________________________________________________________________
Trapping Exceptions
-Exception handled by current block
-Exception handled by enclosing blocks
-Exception propagates to calling environment
The oracle server error number must be between -20000 and -20999, together with
a user-specified error message.
__________________________________________________________________
___________
/-Procedures
/
/-Functions
/
/-Cursors
Stored Package<
\-Constants
\
\-Exceptions
\
\-Variables
-----------
__________________________________________________________________
Benefits of User-Defined Functions
-Increase data independence
(Perform complex data analysis within the Oracle server instead of perfo
rming the calculations on the client application.
-Enable parallel query execution
(You can run two queries in parallel by using the Parallel Query option
in SQL statements).
User-Defined Function in a SQL Statement
-Must be a stored function.
(You cannot use a function defined within a PL/SQL block or subprogram i
n a SQL statement).
-Must have only IN type arguments.
(You cannot use the OUT and IN OUT type arguments in a stored function t
hat is called in a SQL statement).
(The user-defind functions can use either a row function or aggregate fu
nction).
-Must have Oracle server internal datatypes for arguments
-Must have an Oracle server internal datatype for the return value.
(It must not be a PL/SQL datatype).
Restrictions on the user-defined function in a SQL statement.
-The function used in the SQL statement cannot modify the database tables.
(You cannot use an INSERT, UPDATE, or a DELETE statement in the user-def
ined function when used in a SQL statment).
-Cannot call a subprogram that modifies database tables.
_________________________________________________________________
Supplied Packages
-DBMS_ALERT Provides notification of database events.
-DBMS_APPLICATION_INFO Enables application tools to indicate the DB of
actions and tracks the performance of various modules.
-DBMS_DDL Allows you to recompile your modified stored cod
e. Analyze and compute statics for the DB objects.
(Provides you with the ability to embed
Data Definition Language (DDL) statements in PL/SQL block).
-DBMS_DESCRIBE Return a description of the parameters of a stor
ed PL/SQL procedure of function.
(When a function is specifed, also retur
ns information about the return datatype).
-DBMS_JOB Acts as an interface for the Oracle server job q
ueue.
(Enables you to schedule tasks, invoke p
rocedures, and alter the jobs that have been scheduled).
(You use this package to schedule admini
strative procedures at periodic intervals).
-DBMS_LOB Provides a mechanism for accessing and manipulat
ing Large Objects (LOBs). LOBs were introduced in Oracle8
(As well as Binary Objects (BLOBs), Char
acter Large Objects (CLOBs), National Language Support Character Large Objects (
NCLOBs), External Binary Files (BFILEs)).
-DBMS_LOCK Perform operations such as requesting, convertin
g, and releasing userlocks.
(Enables you to change the lock mode).
-DBMS_OUTPUT Displays values and messages from triggers, stor
ed procedures, and functions.
(This package accumulates information in
a buffer so that the information can be retrieved later).
-DBMS_PIPE Allows messages to be sent from one database ses
sion to another in the same instance.
(Communication is asynchronous, nontrans
actional, and persists beyond a session's lifetime).
-DBMS_SESSION Provides facilites to alter session settings and
enable or disable roles.
(You also use this package to manage ses
sion resoruces).
-DBMS_SHARED_POOL You use it to keep objects in shared memory to e
nsure that they are not removed with the Least Recently Used (LRU) mechanism.
(Also enables you to display the sizes o
f objects in the shared pool).
-DBMS_SQL Is used to enable the execution of Data Definiti
on Language (DDL) statements within a PL/SQL block.
(Allows you to build DML statements dyna
mically).
-DBMS_TRANSACTION Controls logical transactions and improves the p
erformance of short, nondistributed transactions.
-DBMS_UTILITY Analyzes objects in a particular schema and chec
ks whether the server is running in parallel mode.
-UTL_FILE Allow PL/sQL subprograms to write to operating s
ystem files that are stored on the server where the Oracle database is running.
(Also allows content to be read from ope
rating system files).
__________________________________________________________________
DBMS_PIPE
-Allows you to send information from one session in an Oracle DB to another sess
ion in the same instance.
-The information has to be packed into the local message buffer before the messa
ge is sent, and unpacked once the message is received.
-Mimics UNIX pipes, Pipes work asynchronously, Use a public pipe or a private pi
pe, Once read empties the buffered information.
Common procedures:
-PACK_MESSAGE Packs a message of the VARCHAR2, NUMBER, or DATE
datatype into the local message buffer.
-UNPACK_MESSAGE Unpacks a message of the VARCHAR2, NUMBER, or DA
TE datatype from the local message buffer.
-PACK_MESSAGE_RAW Packs a RAW datatype message into the local mess
age buffer.
-UNPACK_MESSAGE_RAW Unpacks a RAW datatype message from the local me
ssage buffer.
-PACK_MESSAGE_ROWID Packs a ROWID datatype message into the local me
ssage buffer to be sent by the SEND_MESSAGE function.
-UNPACK_MESSAGE_ROWID Unpacks a ROWID datatype message from the local
buffer.
-SEND_MESSAGE Sends a message contained in the local message b
uffer to a named pipe.
-RECEIVE_MESSAGE Retrieves a message into the local message buffe
r from the named pipe.
-NEXT_ITEM_TYPE Specifies the datatype of the next item in the l
ocal message buffer.
-UNIQUE_SESSION_NAME Returns the unique name of the session.
-PURGE Deletes all messages in the named pipe.
______________________________________________________________________
DBMS_DDL
-Enables you to embed some DDL statements into your PL/SQL subprograms.
(Normally DDL statements are not allowed in a PL/SQL subprogram).
/-DBMS_DDL.ALTER_COMPILE
DBMS_DDL<
\-DBMS_DDL.ANALYZE_OBJECT
-The use is not allowed in triggers and in procedures called from Form Builder,
you cannot use it also in remote sessions.
DBMS_DDL.ALTER_COMPILE
Invoking: DBMS_DDL.ALTER_COMPILE(<Object Type>, <Owner>, <Object Name>)
('PROCEDURE', 'A_USER', 'QUERY_EMP')
DBMS_DDL.ANALYZE_OBJECT
Invoking: DBMS_DDL.ANALYZE_OBJECT(<Object Type>, <Owner>, <Object Name>, <Method
>)
( 'TABLE' ,'A_USER', 'JOBS' ,'COMPUTE
')
_______________________________________________________________
DBMS_OUTPUT
-While testing a stored subprogram, the subprogram may encounter an unhandled ru
n-time error and end abruptly, when debugging it locating the error-causing stat
ement in the subprogram code is difficult.
Procedures:
-PUT Appends text from the procedure to the current line of the outpu
t buffer without adding a new line.
(When your line exceeds the buffer limit, you receive an
error message).
-NEW_LINE Places an end_of_line marker in the output buffer.
-PUT_LINE Combines the action of PUT and NEW_LINE.
-GET_LINE Retrieves the current line from the output buffer into the proce
dure.
(It places the line in an OUT parameter character variab
le).
-GET_LINES Extracts a number of lines from the output buffer.
(The retrieved lines are stored in an PL/SQL table).
-ENABLE Enable calls to the DBMS_OUTPUT package.
(This procedure enables calls to PUT, PUT_LINE, NEW_LINE
, GET_LINE and GET_LINES).
-DISABLE Disable calls to the DBMS_OUTPUT package.
(This procedure disables calls to PUT, PUT_LINE, NEW_LIN
E, GET_LINE and GET_LINES, and purges the buffer of any remaining information).
Debugging Stored Procedures
-You have to issue the SET SERVEROUTPUT ON command.
DBMS_OUTPUT.PUT_LINE('<something>')
-To show the message
DBMS_OUTPUT.NEW_LINE
__________________________________________________________________
OS Files Interaction Package
UTL_FILE.- Read and write to operating system files.
(extends I/O to text files within PL/SQL. Open files, get text,
write text, close files).
DBMS_LOB.- Interact with opearting system files.
(Read-only operations on external BFILEs).
(Read and Write operations on internal LOBs).
Observers can only read LOB values.
Mutators can modify LOB values.
__________________________________________________________________
DBMS_JOB
Provides access to the Oracle server job queue, the job queue allows automated,
unattended scheduling and execution of PL/sQL subprogrms.
(This package enables you to change execution parameters and to sumbit,
invoke, remove, and suspend jobs).
Enables you to interact with the Oracle server job queue to schedule task, invok
e procedures, and alter the jobs that have been scheduled.
(You can run tasks at a different time than the original scheduled time)
.
Enables you to batch jobs during nonpeak hours
Enables you to run maintance programs during times of low usage.
Parameters:
-JOB Returned Job id.
-WHAT The PL/SQL code to run as a job. (Must be enclosed in single quo
tes and must end with a semicolon).
-NEXT_DATE Next execution date of the parameter.
-INTERVAL Specifies the date function, used to compute the next execution
date of a job.
-NO_PARSE Whether to parse the job during the job submission.
Subprograms
DBMS_JOB.CHANGE Changes the WHAT, NEXT_DATE, AND INTERVAL parameters.
DBMS_JOB.INTERVAL Changes the date function, and the INTERNAL parameter.
DBMS_JOB.NEXT_DATE Changes the next execution date.
DBMS_JOB.WHAT Changes the WHAT parameter, allows you to change the PL/
SQL code to run as a job.
DBMS_JOB.RUN Runs a job inmediately. \ THEY NEE
D THE NUMBER OF THE JOB
DBMS_JOB.REMOVE Removes a submitted job from the queue. / THEY NEE
D THE NUMBER OF THE JOB
DBMS_JOB.BROKEN Indicates that a submitted job is broken.
DBMS_JOB.SUBMIT Add a new job to the queue.
DBA_JOBS \ DATA DICTIONARY VIEWS - Verify the status of the submitt
ed jobs.
DBA_JOBS_RUNNING/ DATA DICTIONARY VIEWS - Enables you to display jobs that
are currently running.
__________________________________________________________________
UTL_FILE
Is avilable for both, server-side and client-side PL/SQL. Client-side security i
s automatically implemented because the server uses the normal operating system
file permission validation.
(You implement server-side security by placing access restrictions on th
e directories that can be accessed).
UTL_FILE_DIR This parameter is set to the accessible directories that are needed
before using the UTL_FILE package, the directory set must be on the same system
as the database server.
(You can set a value * to the UTL_FILE_DIR initialization parameter, thi
s setting gives all operating system directories that have access to the DB serv
er processes access to the UTL_FILE package).
-Extends I/O to text files.
-Similar to standard operating system I/O.
-Opens files, gets and writes text, and closes files.
-Accounts for possible errors during execution.
Subprograms
FOPEN Opens a file for input or output and returns a file handle that
must be used in all subsequent I/O operations on the file.
(Needs 3 parameters, location, filename, and open_mode p
arameters).
IS_OPEN Returns a Boolean value whenever a file handle refers to an open
ed file.
(You use it to test whether the file handle identifies a
n opened file).
GET_LINE Reads a line of text from the opened file and places the text in
the output buffer parameter.
(Text is read up to the line terminator or up to the end
of the file, the maximum size of an input record is 1023 bytes unless you speci
fy a larger size in the FOPEN function).
PUT, PUT LINE Writes a text string stored in the buffer parameter to the opene
d file.
(No line terminator is appended by the PUT procedure, in
contrast PUT_LINE writes a complete line with a terminator).
PUTF Formatted PUT procedure with two format specifiers.
(You use %s to substitue a value into the output string)
.
(You use \n to substitute for an appropiate platform-spe
cific line terminator).
NEW_LINE Writes one or more line terminators to the file identified by th
e input file handle.
(Writes line terminators that are platform-specific char
acters).
FFLUSH Writes all data buffered in memory to a file.
(Debugging messages can be flushed to the file so that t
he messages can be read immediately.
FCLOSE Closes an opened file identified by a file handle.
(When you close a file and there is buffered data that i
s to be written during the runtime of the FCLOSE procedure, a WRITE_ERROR except
ion is raised).
FCLOSE_ALL Close all opened file handles for the session.
(Must be used as an emergency cleanup procedure, i.e. wh
en a PL/SQL program exists on an exception).
Exceptios
INVALID_PATH The file location or file name is invalid.
INVALID_MODE The open_mode parameter in the FOPEN function is invalid
.
(You use it to specify how the file is to be ope
ned).
INVALID_FILEHANDLE The file handle is invalid.
INVALID_OPERATION The file cannot be opened or operated on as requested.
READ_ERROR An operating system error occurs during the read operati
on.
WRITE_ERROR An operating system error occurs during the write operat
ion.
INTERNAL_ERROR An unspecified error occurs in PL/SQL.
UTL_FILE processing steps.
1.- Identify whether the text file is open by using IS_OPEN function.(Use FOPEN
if its not open).
2.- Read from or write the the file, read by getting lines with GET_LINE and wri
te by using PUT, PUT_LINE and PUTF).
3.- Identify whether there are more lines to process, if so, you must read from
or write to the file as needed.
4.- Close the file by using the FCLOSE procedure, when there ar no more lines to
process.
_________________________________________________________________
UTL_HTTP
-Makes HTTP callouts from SQL and PL/sQL. You can with this package access data
on the internet over HTTP.
-Enables HTTP requests directly from the database which allows you to access dat
a on the internet.
(You can couple the UTL_HTTP and DBMS_JOBS packages to schedule the recu
rring requests from your DB server to the web).
-contains the REQUEST and REQUEST_PIECES functions.
(Accept a string Uniform resource Locator (URL) as a parameter, contact
the site and return the HTML data from the site.
(REQUEST returns up to the first 2000 bytes of data retrieved from the g
iven URL).
(REQUEST_PIECES returns a PL/SQL table of 2000 bytes of data retreived f
rom the given URL).
-Requires a proxy parameter to be specified when the client is behind a firewall
.
(Report an HTML error message when the specified URL is not accessible).
-Raises REQUEST_FAILED or INIT_FAILED exceptions when the HTTP call fails.
(REQUEST_FAILED when the URL is not properly specified in HTTP syntax).
(INIT_FAILED when there is a lack of available memory).
_________________________________________________________________
UTL_TCP
-Provides Transmission Control Protocol/Internet Protocol (TCP/IP) client-side a
ccess in PL/SQL
-Enables PL/SQL applications to communicate with external TCP/IP-based servers b
y using TCP/IP.
-Contains functions to open and close connections and functions to read and writ
e data from a service on an open connection.
(Include OPEN_CONNECTION, CLOSE_CONNECTION, READ_BINARY and WRITE_BINARY
).
-Needs a remote host and port as well as a local host and port as arguments for
functions.
-Raises exceptions.
(When the buffer size is too small or when no more data is available to
read from a connection).
__________________________________________________________________
Dynamic SQL
-Contain variables that can change during run-time.
-SQL statements can be created at run-time by using variables.
(You would use dynamic SQL to create a procedure that operates on a tabl
e whose name is not know until run-time).
Statementes:
-Are not embedded in source code.
-Enables SQL statement to be stored as character strings.
-Enable data-definition, data-control or session-control statements to be writte
n and invoked from PL/SQL.
-Allow general purpose code to be written.
-You can use DBMS_SQL or EXECUTE IMMEDIATE for single-row queries.
-If its multi-row query you can use DBMS_SQL or the OPEN-FOR, FETCH, or CLOSE st
atements.
DBMS_SQL
-Write stored procedures and anonymous PL/SQL blocks that use dynamic SQL.
-Issue DDL statements in PL/sQL
-The operations provided are performed under the current user, not under the pac
kage owner SYS.
(If the call is by an anonymous block, the operations are performed acco
rding to the privileges of the current user).
(If the call is by a stored procedure, the privileges of the owner of th
e stored procedure are used).
-Using DBMS_SQL package to run DDL statements can result in a deadlock.
(i.e. if a PL/SQL block tries to drop a stored procedure by using the DB
MS_SQL prackage while youre using that procedure).
Functions and procedures
-OPEN_CURSOR Opens a new cursor and assigns a cursor ID number.
(Establish an area in memory to process a SQL st
atement).
-PARSE Parses the procedure to establish the validity of the SQ
L statement.
(DDL statements are immediately run when parsed)
.
-BIND_VARIABLE Binds the given value to the named variablein the parsed
statement in the given cursor.
-EXECUTE Executes the SQL statement and returns the number of row
s processed.
(Returns the number of rows processed).
-FETCH ROWS Retrieves a row for the specified cursor.
(For multiple rows you can call the FETCH_ROWS f
unction in a loop).
-CLOSE_CURSOR Closes the specified cursor.
(Releases the area of memory allocated to the cu
rsor).
_____________________________________________________________________
LOB Datatypes
-BLOB Binary large objects.
-CLOB Character large objects.
-NCLOB Fixed-width multibyte character large objects.
-BFILE Binary file stored outside the database.
LOBs are characterized in two methods.
1.- How Oracle server interprets the LOBs
-Binary Data
-Character Data
2.- How they are stored.
-Inside the database
-Externally in host files.
+-----------------------+-----------------------+
| Internal LOBs | External LOBs |
+-----------------------+-----------------------+
| CLOB | BFILEs |
| NCLOB |(Can only be accessed |
| BLOB |in read-only mode) |
+-----------------------+-----------------------+
-The Oracle server does not convert data between the different types of LOB.
(i.e. If you create a table T with a CLOB column an a table S with a BLO
B colum, data is not directly transferable between them).
/-LOB locator-Is stored in the database and indicates the location of the LO
B value.
LOB<
\-LOB value -Is the data that constitutes the real object that is stored.
-When you create a large internal LOB, the value is stored in the LOB segment in
the database. A locator to this out-of-line LOB value is placed in the LOB colu
mn of the corresponding row in the table.
-For small internal LOB of less than 4000 bytes, the LOB value is stored in-line
with the other row data.
-LOB datatypes are distinct from LONG and LONG RAW datatypes and they are not in
terchangeable.
Contrasting LONG and LOB Datatype
+---------------------------------------+---------------------------------------
+
| LONG, LONG RAW | LOB
|
+---------------------------------------+---------------------------------------
+
|Single column per table |Multiple columns per table
|
+---------------------------------------+---------------------------------------
+
|Up to 2 GB. |Up to 4 GB.
|
+---------------------------------------+---------------------------------------
+
|SELECT returns data |SELECT returns locator
|
+---------------------------------------+---------------------------------------
+
|Data stored in-line |Data stored in-line or out-of-line
|
+---------------------------------------+---------------------------------------
+
|Cannot be object type attributes |Can be object type attributes
|
+---------------------------------------+---------------------------------------
+
|Sequential access to data |Random access to data
|
+---------------------------------------+---------------------------------------
+
________________________________________________________________
BFILEs
Oracle SQL allows you to define BFILE objects, associate BFILE objects with corr
esponding external files, and access the security aspects of BFILEs.
-A BFILE column stores a BFILE locator which is a pointer to a file in the file
system.
(The locator contains the directory alias and the file name).
(The directory object is created by the DBA and identifies the placement
of the BFILE on you server machine.
-The Oracle server acts as a security mechanism to shield the operating system f
rom unsecured access.
(You can read a BFILE in the same way as you read an internal LOB).
(However the file may have access permissions).
-A directory object specifies an alias for a directory on the file system of the
server.
(Granting the READ privilege you can provide secured access to files in
the corresponding directories on a user-by-user basis.
(You can make certain directories read-only or inaccessible).
A directory object:
-Is a nonschema database object.
-Is owned by SYS.
-Is created by the DBA.
-Has object privileges
Working with BFILEs:
1.- Create the OS directory as the Oracle user and set permission to enable the
Oracle server to read the contents of the OS directory.
2.- Load the files into the OS directory.
3.- Create a table that contains the BFILE datatype on the Oracle server.
4.- Create the DIRECTORY object and grant the READ privilege to the DIRECTORY ob
ject.
5.- Insert rows into the table by using the BFILENAME function, associating the
OS files with the corresponding row column intersection.
6.- Declare and initialize the LOB locator in your code.
7.- Insert the row and column that contains the BFILE into the LOB locator.
8.- Read the BFILE with OCI DBMS_LOB functions, using the LOB locator as a refer
ence to the file.
Use a BFILE within an Oracle Table.
1.- Use a BFILE to create a table with a BFILE column or alter an existing table
to add a BFILE column.
ALTER TABLE <table name> ADD <bfile column name> BFILE;
2.- Create a DIRECTORY object by using the CREATE DIRECTORY command.
CREATE DIRECTORY <directory name> AS <OS path>;
3.- Grant users the read privileges for the DIRECTORY object.
GRANT READ ON DIRECTORY <directory name> TO user|role| PUBLIC;
BFILENAME function
-Initalizes a BFILE column to point to an external file.
-You use the BFILENAME function as a part of an INSERT statement to initialize a
BFILE column.
-You assign the BFILE column to a physical file in the server file system.
FUNCTION BFILENAME (directory_alias IN VARCHAR2, filename IN VARCHAR2) R
ETURN BFILE;
(It needs two IN parameters, directory alias and file name).
(Returns a BFILE locator that is associated with the physical fi
le on the server file system).
A BFILE can be initialized to NULL and later updated by using the BFILENAME func
tion.
(You can use the UPDATE statement to change the reference target of the
BFILE).
____________________________________________________________________________
FILEEXISTS
-Verify whether a given BFILE locator points to a file that exists on the server
's file system.
-Return 0 when the file does not exist.
-Return 1 when the file does exist.
FUNCTION DBMS_LOB.FILEEXISTS (<BFILE locator stored in a BFILE column> IN BFILE)
RETURN INTEGER;
EXCPETIONS:
NOEXIST_DIRECTORY - Is raised when the directory does not exist.
NO_PRIV_DIRECTORY - Is raised when you do not have privileges for the directory.
INVALID_DIRECTORY - Exception is raised when the directory is invalidated after
the file is opened.
___________________________________________________________________________
LONG to LOB Migration
ALTER TABLE [<schema>.] <table_name> MODIFY (<long_col_name> CLOB|BLOB|NCLOB )
All constraints for the LONG columns are maintained for the new LOB columns.
If you do not specify a default value, the default value for the LONG column is
copied to the new LOB column.
Syntax for DBMS_LOB.READ
PROCEDURE READ( lobscr IN BFILE|BLOB|CLOB,
amount IN OUT BINARY_INTEGER,
offset IN INTEGER,
buffer OUT RAW|VARCHAR2)
-An exception is raised when no more data is to be read.
-The value returned in AMOUNT variable is less than that specified if the end of
the LOB is reached before the specified number of bytes or characters could be
read.
-PL/SQL allows a maximum value of 32767 for RAW and VARCHAR2 parameters.
(You must ensure that the allocated system resources are adequate to sup
port these buffer sizes for the given number of user sessions).
(Otherwise, the Oracle server raises the appropriate memory exce
ptions).
PROCEDURE WRITE(lobdst IN OUT BLOB|CLOB,
amount IN OUT BINARY_INTEGER,
offset IN INTEGER :=1,
buffer IN RAW|VARCHAR2)
-Must ensure that the amount in bytes corresponds to the amount of buffer data.
-Has no means of verifying whether the sizes match and writes AMOUNT bytes of th
e buffer contents into the LOB.
__________________________________________________________________
LOBs manipulating using SQL
CREATE TABLE employee (emp_id NUMBER,
emp_name VARCHAR2(35),
resume CLOB,
picture BLOB);
The content of a LOB column is stored in the LOB segment while the column in the
table only contains a reference to that specific storage area, called LOB locat
or.
To declare a LOB locator.
lobloc CLOB;
The function EMPTY_CLOB() and EMPTY_BLOB() used in an INSERT initialize an LOB o
bject but not populate it with data.
You can use UPDATE statement to populate the LOB column.
If you use NULL as the value for the LOB column, the LOB is not initialized, whe
n is it you cannot populate the values using an UPDATE statement.
To erase part of an internal LOB you can use a DBMS_LOB.ERASE.
__________________________________________________________________
Types of Privileges
Privileges that contain the keyword CREATE or ANY are system privileges.
Privileges are assigned by the user SYSTEM or SYS.
CREATE <ANY> PROCEDURE - Alter, drop or invoke PL/SQL subprograms, Create proced
ures, functions and packages.
ALTER ANY PROCEDURE
You must have to EXECUTE ANY PROCEDURE and DROP ANY PROCEDURE privileges to invo
ke and drop subprograms.
GRANT <SQL function> ON <object/table name> TO <user name>;
You must have the EXECUTE object privilege to invoke a PL/SQL subprogram.
You need the EXECUTE object privilege if you do not have the EXECUTE ANY system
privilege.
__________________________________________________________________
Stored Subprograms Management
You can view information about a stored subprogram by using the USER_OBJECTS and
USER_SOURCE Oracle data dictionary views.
You can use the USER_ERRORS data dictionary view to display any PL/SQL syntax er
rors after compiling a stored subprogram.
USER_OBJECTS - Display the names of all the stored procedures and functions in y
ou database schema.
ALL_OBJECTS and DBA_OBJECTS contains the additional column OWNER which represent
s the owner of the PL/SQL object.
USER_SOURCE - Display the text of a subprogram in you schema.
(If you have lost a script file, you can regenerate the file fro
m USER_SOURCE).
DESCRIBE - Display mode and datatype information related to the parameters accep
ted by a subprogram in your schema.
USER_ERRORS, SHOW ERRORS - View any PL/SQL syntax errors associated with compili
ng a stored subprogram.
DBMS_OUTPUT - User-specified debug variables and messages from stored subprogram
s can be displayed at run-time.
The data dictionary contains information about the stored subprograms.
USER_OBJECTS Data Dictionary View
+---------------------------------------+---------------------------------------
+
|Column (object_name) | Column Description
|
+---------------------------------------+---------------------------------------
+
|OBJECT_NAME |Name of the object
|
+---------------------------------------+---------------------------------------
+
|OBJECT_ID |Internal identifier
|
+---------------------------------------+---------------------------------------
+
|OBJECT_TYPE |Type of object i.e. PROCEDURE, FUNCTION
|
+---------------------------------------+---------------------------------------
+
|CREATED |Date of creation
|
+---------------------------------------+---------------------------------------
+
|LAST_DDL_TIME |Date of last modification
|
+---------------------------------------+---------------------------------------
+
|TIMESTAMP |Date and time of last recompilation
|
+---------------------------------------+---------------------------------------
+
|STATUS |VALID or INVALID
|
+---------------------------------------+---------------------------------------
+
USER_SOURCE Data Dictionary View
+---------------------------------------+---------------------------------------
+
|Column (object_name) | Column Description
|
+---------------------------------------+---------------------------------------
+
|NAME |Name of the object
|
+---------------------------------------+---------------------------------------
+
|TYPE |Type of object i.e. PROCEDURE, FUNCTION
|
+---------------------------------------+---------------------------------------
+
|LINE |Line number of the source code
|
+---------------------------------------+---------------------------------------
+
|TEXT |Text of the source code
|
+---------------------------------------+---------------------------------------
+
______________________________________________________________________
Compile Time Errors
To view the errors generated while compiling a stored subprogram you use the USE
R_ERRORS data dictionary.
USER_ERRORS Data Dictionary View
+---------------------------------------+---------------------------------------
+
|Column (object_name) | Column Description
|
+---------------------------------------+---------------------------------------
+
|NAME |Name of the object
|
+---------------------------------------+---------------------------------------
+
|TYPE |Type of object i.e. PROCEDURE, FUNCTION
|
+---------------------------------------+---------------------------------------
+
|SEQUENCE |Sequence number, for ordering
|
+---------------------------------------+---------------------------------------
+
|LINE |Line number of where the error occurs
|
+---------------------------------------+---------------------------------------
+
|POSITION |Position in line wher the error ocrrurs
|
+---------------------------------------+---------------------------------------
+
|TEXT |Text of the error
|
+---------------------------------------+---------------------------------------
+
Any compile time errors encountered when compiling a subprogram can also be disp
layed by using SHOW_ERRORS command.
_______________________________________________________________________
Debug Methods
You use DBMS_OUTPUT package to output values and messages from a PL/SQL block.
(This package accumulates information into a buffer and then allows retr
ieval of information form the buffer).
You can use Autonomous procedure calls. You assign the output of the autonomous
programs as values of columns in a log table.
DBMS_DEBUG package, you used it to debug the server-side code.
Status of schema objects
+---------------------------------------+---------------------------------------
+
|Status |Significance
|
+---------------------------------------+---------------------------------------
+
|VALID |The object has been compiled and can
|
| |be immediately used when referenced
|
+---------------------------------------+---------------------------------------
+
|INVALID |The object must be compiled
|
| |before it can be used
|
+---------------------------------------+---------------------------------------
+
You can view the status using the USER_OBJECTS data dictionary view.
Local Dependencies
With local dependencies, the objects are on the same nodein the same database.
The oracle server automatically manages all local dependencies using an internal
database.
When a referenced object is modified, the dependent objects are invalidated.
When an invalidated object is called, the Oracle server recompiles the object.
Remote Dependencies
With remote dependencies, the objects are on separate nodes.
The Oracle server does not manage dependencies among remote schema objects other
than involving local-to-remote procedures.
The local procedure and dependet objects are invalidated.
_______________________________________________________________________
Local Dependencies Tracking
When an object is invalidated due to changes in the definition of the referenced
object, you manually recompile the dependent object.
You use the Oracle server data dictionary views DEPTREE, IDEPTREE, and USER_DEPE
NDENCIES to identify the dependent objects to be recompiled in case of dependenc
y failure.
USER_DEPENDENCIES Data Dictionary View
+---------------------------------------+---------------------------------------
+
|Column (object_name) | Column Description
|
+---------------------------------------+---------------------------------------
+
|NAME |Name of dependent object
|
+---------------------------------------+---------------------------------------
+
|TYPE |Type of dependent object (PROCEDURE,
|
| |FUNCTION, PACKAGE BODY, TRIGGER, VIEW)
|
+---------------------------------------+---------------------------------------
+
|REFERENCED_OWNER |Schema of referenced object
|
+---------------------------------------+---------------------------------------
+
|REFERENCED_NAME |Name of referenced object
|
+---------------------------------------+---------------------------------------
+
|REFERENCED_TYPE |Type of referenced object
|
+---------------------------------------+---------------------------------------
+
|REFERENCED_LINK_NAME |Database link used to access
|
| |referenced object
|
+---------------------------------------+---------------------------------------
+
Displaying All Dependencies
Execute the utldtree.sql script
Populate teh DEPTREE_TEMPTAB table invoking the deptree_fill procedure.
EXECUTE deptree_fill (object_type, object_owner, object_name)
Query the DEPTREE view.
SELECT nested_level,type,name FROM deptree ORDER BY seq#;
IDEPTREE displays an independent representation of the dependent objects.
(You can also create this view by runnig the utldtree.sql script).
Guidelines to Minimize Dependency Failures
-Declare records by using the %ROWTYPE attribute.
-Query with the SELECT * notation.
-Declare variables with the %TYPE attribute.
-Include a column list with the INSERT statement.
_______________________________________________________
Remote Dependency Modes
-TIMESTAMP checking - Each program unit carries a timestamp that is set when it
is created of recompiled.
When you alter a program unit, all dependent program units
are marked as invalid and must be recompiled before execution.
The timestamp comparision occurs when a statement in the l
ocal procedure calls a remote procedure.
-SIGNATURE checking - When the program unit timestamp doesnt match the called re
mote program unit timestamp the Remote Procedure Calls (RPCs) layer compares the
signature.
If the signatures are the same, execution continues. Other
wise an error is returned.
Signature includes:
-Name of the construct(procedure, function, package)
-Base types of the parameters of the construct
-Modes of the parameters (IN, OUT, IN OUT)
-Number of the parameters
-Datatype of the return value for a function
________________________________________________________
Trigger
A DB trigger is a named PL/SQL block that is fired automatically when certain op
erations are perfomed.
The size of a trigger cannot be more than 32 kilobytes.
The DML operations fire a trigger.
Improve Data Security
-Value-based security checks.
-value-based auditing.
Mantain Data Integrity
-Dynamic data integrity constraints
-Referential integrity constraints
-Related operations performed together implicitly
Parts of a DB trigger
-Trigger timing -BEFORE and AFTER for a table and INSTEAD OF for a view.
-Triggering event -INSERT, UPDATE or DELETE.
-Table name -Table or view.
-Trigger type -Number of times a trigger body runs for a particular ev
ent. (row or statement-level trigger (By default statement)).
(row level fires once for every row affected)
(statemente level fires once, even if no rows ar
e affected)
-WHEN clause -Restricting condition.
-Trigger body -Complete PL/SQL block.
Guidelines for designing triggers
-Use triggers to perform related actions.
-Use triggers only for centralized global operations.
-Avoid using triggers to duplicate or replace the built-in functionality.
-When the logic for a trigger is lengthy, you must create and invoke stored proc
edures from a trigger.
-Use triggers only when necessary.
CREATE [OR REPLACE] TRIGGER <trigger name>
timing --When is it fire.
event1 [OR event2 OR event3] --DML operation that cause the t
rigger to fire.
ON <table name> --The table associated with trig
ger.
THEN <trigger_body> --The action performed by trigge
r.
END IF;
END;
timing - BEFORE | AFTER | INSTEAD OF <SQL statement>
Row-statement trigger
[REFERENCING OLD AS old / NEW AS new]
FOR EACH ROW
+---------------+-----------------------+-----------------------+
|Data operation |Old value |New value |
+---------------+-----------------------+-----------------------+
|INSERT |NULL |Inserted value |
+---------------+-----------------------+-----------------------+
|UPDATE |Value before update |Value after update |
+---------------+-----------------------+-----------------------+
|DELETE |Value before delete |NULL |
+---------------+-----------------------+-----------------------+
The table that is currently being modified by an UPDATE, DELETE, or INSERT state
ment is called a mutanting table.
(This table also needs to be updated by the effects of a declarative DEL
ETE CASCADE referential integrity action).
(A table is not considered mutating for statement-level triggers).
INSTEAD OF TRIGGERS
INSTEAD OF triggers can only be row triggers, therefore the FOR EACH ROW clause
is optional.
You cannot specify the WHEN clause of INSTEAD OF triggers.
If a view is inherently updatable, and has INSTEAD OF triggers, the INSTEAD OF t
riggers take preference.
INSTEAD OF trigger cannot use the BEFORE or AFTER timing option.
FORM BUILDER TRIGGERS
-Fired only within a particular Form Builder application.
-Can be either statement-level or row-level.
-Upon failure, causes the cursor to freeze.
-Can fire independently or in addition to database triggers.
-Runs under the security domain of the Form Builder user.
+-----------------------------------------------+-------------------------------
----------------+
|Database Trigger |Stored Procedure
|
+-----------------------------------------------+-------------------------------
----------------+
|Use CREATE TRIGGER |Use CREATE PROCEDURE
|
+-----------------------------------------------+-------------------------------
----------------+
|Invoke implicitly |Invoke explicitly
|
+-----------------------------------------------+-------------------------------
----------------+
|Data dictionary contains source and p-code |Data dictionary contains source
and p-code |
+-----------------------------------------------+-------------------------------
----------------+
|Does not need any special privilege |Needs EXECUTE permission
|
+-----------------------------------------------+-------------------------------
----------------+
|Documented in the USER_OBJECTS and |Documented in the USER_OBJECTS
and |
|USER_TRIGGERS data dictionary views |USER_SOURCE data dictionary vie
ws |
+-----------------------------------------------+-------------------------------
----------------+
|Contains only DML statementes |Can contain the COMMIT, ROLLBAC
K, and |
| |SAVEPOINT statements
|
+-----------------------------------------------+-------------------------------
----------------+
USER_TRIGGERS data dictionary
+-----------------------+-----------------------------------------------+
|Column |Column Description |
+-----------------------+-----------------------------------------------+
|TRIGGER_NAME |Name of the trigger |
+-----------------------+-----------------------------------------------+
|TRIGGER_TYPE |The type is either BEFORE, AFTER, or INSTEAD OF|
+-----------------------+-----------------------------------------------+
|TRIGGERING_EVENT |The DML operation firing the trigger |
+-----------------------+-----------------------------------------------+
|TABLE_NAME |Name of the database table |
+-----------------------+-----------------------------------------------+
|REFERENCING_NAMES |Name used for :OLD and :NEW |
+-----------------------+-----------------------------------------------+
|WHEN_CLAUSE |The text of the WHEN clause used |
+-----------------------+-----------------------------------------------+
|STATUS |The status of the trigger |
+-----------------------+-----------------------------------------------+
|TRIGGER_BODY |The code of the action to take |
+-----------------------+-----------------------------------------------+
Disable a trigger
ALTER TRIGGER <trigger name> DISABLE;
Enable a trigger
ALTER TRIGGER <trigger name> ENABLE;
Disable all triggers referencing a table
ALTER TABLE <table name> DISABLE ALL TRIGGERS;
Enable all triggers referencing a table
ALTER TABLE <table name> ENABLE ALL TRIGGERS;
Trigger Test Cases
-Test each triggering data operation.
-Test nontriggering data oprations.
-Test each case of the WHEN clause.
-Test the effect of the trigger upon other triggers and vice versa.
Drop a trigger
You must have the DROP ANY TRIGGER system privilege.
(When a table is dropped all the triggers on the table are also dropped)
.
Syntax:
DROP TRIGGER <trigger_name>;
The oracle server first invokes all the BEFORE statements triggers.
A single SQL statement fires for all of the BEFORE and AFTER statementes and row
triggers.
Loops for each row affected by the SQL statement.
Invokes the DML statement and performs integrity constraint checking.
Invokes all AFTER statement triggers.
Implementation of Triggers
-Security Determines user access to tables
-Auditing Captures all successful attempts to access a dat
abase
-Data integrity Provides default values to variable
-Referential integrity Sets column to a default value for a delete or u
pdate operation
-Table replication Copies a table synchronously, in real time
-Derived data Computes inherited columns synchronously, in rea
l time
-Event logging Performs data modification and dependent operati
ons in one step
Use triggers to implement Nonstandard referntial integrity
-Cascade updates
-Set to NULL on updates and deletes
-Set to a default value on updates and deletes
-Enforce referential integrity in distributed systems
-Enable and disable triggers dynamically
-Incorporate referential integrity constraints within table definitions
You can use snapshot to replicate a table on the server
CREATE SNAPSHOT <name> AS SELECT * FROM <table name>@<DB name>;
Replicating tables using server snapshots
-Copy tables asynchronously, at user-defined intervals
-Base snapshots on multiple master tables
-Read-only from snapshots
-Improve the performance of data manipulation on the master tables
Replicating tables using triggers
-Copy tables asynchronously
-Usually base replicas on a single master table
-Read from and write to replicas
-Impair the performance of data manipulation on the master table
Computing Derived Data within the Server
-Compute derived column values asynchronously
-Stored derived values only within database tables
-Modify data in one pass and calculate derived data in a second pass
Computing Derived Values Using a Trigger
-Compute derived columns synchronously
-Stored derived values within database tables or within package global variables
-Modify and calculate derived data in a single pass
Using tiggers to Log Events
-Implicitly perform the operation transparent to the user
-Modify data and perform the dependent operation in a single step
-Log events automatically while data is changing
Benefits of Database Triggers
-Behave as alternatives to features provided by the Oracle server
-Useful for more complex or simpler requirements than those provided by the Orac
le server
-Useful if your requirements are not provided by the Oracle server at all
Data Dictionary Views
-USER_OBJECTS Stores the object information
-USER_TRIGGERS Displays the text of the trigger
-USER_ERRORS Contains the details of the compilation errors

You might also like