Professional Documents
Culture Documents
***
By default the IN parameter is passed by reference and the OUT and IN OUT parameters
are passed by value.
NOCOPY : is a compiles hint that can be used with OUT and IN OUT parameter to
request to pass by reference. This improves the performance with OUT and INOUT
parameters.
7 Advantages of stored functions and procedures
* Applications can be modularized.
* Easy maintenance.
- Routines can be modified online without interfering other users.
- One routine can be modified to effect multiple applications.
* Improved data security and integrity.
- Indirect access to database objects can be controlled from non privileged users with
security privileges.
* Improved performance.
- Reparsing for multiple users can be avoided by exploiting the shared SQL area.
- PL/SQL parsing at run-time can be avoided by pursing at compile time.
- Number of calls to the database can be reduced and network traffic decreased by
bundling commands.
* Improved code clarity.
- The clarity of code increases by using appropriate identifier names to describe the
action of the routines which reduces the need for comments.
Functions Procedures
16 About Cursors
- Oracle server uses some private work areas to execute SQL statements and to store
processing information.
* By using PL/SQL cursors these private SQL areas can be named and the stored
information can be accessed.
Two Types:
* Implicit Cursors.
- Implicit cursors are declared by PL/SQL implicitly for all DML and PL/SQL select
statements, including queries that return only one row.
- Oracle Server implicitly opens a cursor to process each SQL statement not associated
with on explicitly declared cursor.
- The most recent implicit cursor can be returned as the SQL cursor.
* Explicit Cursors
- For queries that return more than one row, explicit cursors are declared and named by
the programmes and manipulated through specific statements in the block’s
executable actions.
- Explicit cursors are used to individually process each row returned by a multiple-row
SELECT statement.
- The set of rows returned by a multiple – row query is called as active set.
Cursor Attributes:-
Attribute Type Description
% is open Boolean Evaluates to TRUE if the cursor is open.
% not found Boolean Evaluates to TRUE if the most recent fetch
doesn’t return a row.
% found Boolean Evaluate to TRUE if the most recent fetch
returns a row. Complement of % not found.
% Row Count Number Evaluates the total number of rows returned so
far.
Parameterized Cursors:-
- Parameters can be passed to the cursor in a cursor for loop.
- It allow to open and close an explicit cursor several times in a block, returning a
different active set on each occasion for each execution, the previous cursor is closed
and reopened with a new set of parameters.
- Sizes should not be mentioned for the data types of parameters the parameters names
are for references in the query expression of the cursor.
Parameters
- A parameter is a variable whose value can be set at runtime (from the run time
parameter of the command line).
- User parameters are created by the user and system parameters are created by Report
Builder.
- System parameters cannot be renamed or deleted.
Bind Parameters (Variables)
- Bind references (or Variables) are used to replace a single value in SQL or PL/SQL,
such as a character string, number or date.
- Bind references may be used to replace expressions in SELECT, WHERE, GROUP
BY, ORDER BY, HAVING, CONNECT BY and START WITH clauses of queries.
- Bind references cannot be referenced in FROM clauses.
- Bind variables can be referenced by entering a colon (:) followed immediately by the
column or parameter name.
- If the parameter / column is not created before making a bind reference, report builder
will create a parameter.
About Exceptions
- An exception is an identifier in PL/SQL that is raised during the execution of a black
that terminates its main body of actions.
- A block always terminates when PL/SQL raises an exception so that an exception
handler should be specified to perform final actions.
* Exception can be raised in two ways exception is raised automatically.
1. Ex:- when no rows are retrieved from the database in a SELECT statement, then error
ORA-01403 occurs and the exception NO-DATA-FOUND is raised by PL/SQL.
2. Ex:- Exception can be raised explicitly by issuing the RAISE statement with in the
block.
- The exception being raised may be either.
- If the exception is raised in executable section of the block, processing branches to the
corresponding exception handler in the exception section of the block.
- If PL/SQL successfully handles the exception, then the exception doesn’t propagate to
the enclosing block or calling environment.
- The PL/SQL block terminates successfully.
Propagating an exception:-
- If the exception is raised in the executable section of the block and there is no
corresponding exception handler, the PL/SQL block terminates with failure and the exception
will be propagated to the calling environment.
Types of exceptions:-
A) Pre-Defined Oracle Server Exceptions. - Implicitly Raised.
B) Non-Pre defined Oracle server exceptions. - Implicitly Raised.
C) User-defined exceptions - Explicitly Raised.
Pre-Defined Oracle Server Exceptions:-
- These are the error(20) that occur most often in PL/SQL code.
- These exceptions need not be declared and raised implicitly by Oracle Server, NO-
DATA-FOUND, LOGIN_DENIED, ZERO_DIVIDE.
Non-Pre-Defined Oracle Server Exceptions:-
- These are the other standard Oracle Server errors.
- These exceptions need to be declared ion the declarative section and raised by Oracle
server implicitly.
User Defined Exceptions: -
- These are the conditions that the developer determines as abnormal.
- These need to be declared and raised explicitly.
PRAGMA EXCEPTION_INIT
Statement is used to associate a declared exception with the standard Oracle Server error
number.
Syntax:- PRAGMA EXCEPTION_INIT (exception, error number)
* SQLCODE, SQL ERRM are two functions, which can be used to identify the associated
error code or error message when exception occurs.
- SQLCODE function returns the numeric value for the error code.
- SQLERRM function returns the character data containing the message associated with
the error number.
- SQLCODE f SQLERRM cannot be used directly in SQL statements.
Declare
D_str varchar2 (200);
Val varchar2 (20);
Begin
D_str= insert into table1 values (;val);
Val= ‘ Bye’ Execute Immediate str using val; end;
- The autonomous or child transaction can commit or rollback as applicable with the
execution of the parent transaction being resumed upon its completion.
- The parent may then perform further operations of any operations performed with in
the child transaction.
- By using Autonomous Transactions, modular and reusable components can be
developed more easily.
- In fact Oracle already uses similar functionality internally, known as recu
transactions to handle the updating of system resources.
Ex:- When one application selects ‘nextval’ from a non eached sequence, the value is in
the database.
- Thus a second application will always get the incremented application has committed
or rolled back.
- Autonomous Transaction should be defined in PL/SQL in the following manner.
Syntax
PRAGMA AUTONOMOUS_TRANSACTION;
Input Collections:-
- Input collections are data passed from Pl/SQL engine to the SQL engine to execute
INSERT, UPDATE and DELETE statements.
Syntax:- FORALL index in lower bound.. upper bound sql_statement;
Output Collections:-
- Output collections are the data passed from the SQL engine to the PL/SQL engine as
a result of SELECT or FETCH statements.
- The keyword BULK COLLECT can be used with SLECT INTO, FETCH INTO and
RETURNING INTO clauses.
Syntax:- BULK COLLECT into collection_name, ……
VIEWS
- Views are built using the columns from one or more tables.
- The single table view can be updated, but the view with multiple tables cannot be
updated.
* A snapshot contains a complete or partial copy of a target master table from a single
point in time.
- A snapshot may be read only or up datable.
26. How duplicate rows are deleted?
- Duplicate rows are deleted by using ROWID
Syntax delete from <Table>
Where ROWID not in (Select max (ROWID) from <Table>
Group by <Column_name>);
27. How do you call function and procedure in PL/SQL as well as in SQL prompt?
isql*plus EXECUTE < Function/Procedure name > ;
(SQL prompt)
IN OUT parameter:
- this type of parameter pass a value from the calling environment into the procedure
and a possibly different value from the procedure back to calling environment using
the same parameter.
- IN OUT parameter cannot be assigned a default value. * By default OUT & IN
OUT parameters are passed by value.
- These can be passed by reference by using NOCOPY.
29. Triggers:
Recursive trigger :
- This is a trigger that contains a DML operation changing the very same table.
Cascading Trigger:
- The action of one trigger cascades to another trigger, causing this second trigger to
fire.
- Oracle server allows up to 32 triggers to cascade at any one time.
- This number can be changed by changing the value of the OPEN - CORSORS. Data
bases initialization parameter. ( default value is 50 ).
- * A triggering statement should contain
1 Trigger Timing Before, After (For Table)
Instead of (For View)
- Determines when the trigger needs to be fired in relation to the triggering event.
2 Triggering Event Insert, Update, Delete
- Determines which on the table or view causes the trigger to fire.
3 Trigger Type Statement, Row
- Determines how many times the trigger body executes
4 Table name Table, View
5 Trigger body PL/SQL – block
- Determines what actions the trigger should perform.
* INSTEAD of triggers are used to provide a transparent way to modifying views that
cannot be modified directly through SQL, DML statements because the view is not
modifiable.
- INSTEAD of triggers provide writing of Insert, Update and Delete statements against the
view.
- The INSTEAD if trigger works invisibly in the background performing the action
coded in the trigger body directly on the underlying tables.
- INSTEAD of trigger execute the trigger body instead of the triggering statement.
Statement Triggers
- In this type of triggers, the trigger body executes once for the triggering event.
- This is the default.
- Statement trigger fires once, even if no rows are affected at all.
Row Trigger
- In this type, the trigger body executes once for each row affected by the triggering
event.
- Row trigger is not executed if the triggering event affects no rows.
* A view cannot be modified by normal DML if the view query contains set operators,
group functions, group by, connect By, start with clauses or joins.
Mutating Table
- A Mutating table is a table that is currently being modified by an UPDATE, DELETE
OR INSERT statement, or a table that might need to be updated by the effects of a
declarative DELETE CASCADE referential integrity action.
- A table is not considered mutating for statement triggers.
- A mutating table cannot be changed because the resulting DML could change data
that is in consistent state.
Explain Plan
- Explain plan command generates information that details the execution plan that will
be used on a particular query.
- A uses a pre created table (PLAN_TABLE) in the current schema to store information
about the execution plan chosen by the optimizer.
- This script creates an output table, called PLAN-TABLE for holding the output of the
explain command.
Populating the PLAN TABLE
- PLAN TABLE is populated using the explain plan.
SQL> Explain Plan for select * from emp where emp no = 1000;
- This command inserts the execution plan of the SQL statement into the plan table.
- A name tag can be added to explain information by using the set statement_id clause.
* AUTOTRACE
- The AUTOTRACE facility in SQL* plus allows analysts to view the execution pan d
some useful statistics for a SQL statement within a SQL*plus session.
- AUTOTRACE needs to be initiated in the SQL*Plus session prior to executing the
statement.
SET AUTOTRACE [OPTIONS] [EXPLAIN] [STATISTICS]
- As with the explain plan command, to obtain an execution plan the PLAN-TABLE
must be created in the user’s schema prior to Auto Tracing.
SQL> Set Auto trace trace only explain
SQL> Select * from dual;
- To enable viewing of STATISTICS data, the auto tracing user must have access to
dynamic performance tables.
- To achieve this, grant PLUS TRACE role to the user.
PLUS TRACE role is created by the plus trace. Sql script
$ ORACLE_HOME / sql plus admin
SYS user must run this script.
DBA can them grant the role to the users who wish to use the AUTOTRACE.
TK PROF
- Tk prof facility accepts as input a SQL Trace File and produces a formatted output
file.
- Tk Prof Filename_source filename_output EXPLAIN = [user name / password] sys =
[yes/no] TABLE = [Table Name]
A) How do you add trace to a report?
- By usingthe package SRW.TRACE_ADD_OPTION
B) How do you execute a specified DDL in a report?
- BY using the package PW.DO_SQL
C) How do you generate message in reports?
- By using the packages PW.MESSAGE (Reg Num, );
D) Explain BLOBS of CLOBS?
LOB A LOB is a data type that is used to store large, unstructured data such as text,
graphic images, video, clippings etc.
* Four large object data types.
BLOB : Represents a binary large object
CLOB : Represents a character large object
NCLOB: Represents a multibyte character object.
BFILE: Represents a binary file store of in an os binary file outside the data base.
LOB’S Internal LOBS (CLOB, BLOB, NCLOB)
external Files (BFILE)
- Depending on the storage aspects and their interpretation by Oracle server.
* LONG_TO_LOB API is used to migrate LONG columns to LOB columns.
LOB’S
LOB Locator
Internal LOB’S
- Stored inside the Oracle server.
- BLOB, NCLOB, CLOB.
BFILE
- BFILE’S are external LOB’S.
- These are stored in OS files out side the database table spaces.
- The data type is BFILE.
- BFILE data file stores a locator to the physical file.
- BFILE can be GIF, JPEG, MPEG, text or other formats.
*DBMS_LO.READ of DBMS_lob.WRITE are used to manipulate LOBS.
Types of Joins
1 Equi Join
2 Non-Equi Join
3 Outer Join
4 self Join
Equi Join:-
- Is also called simple or inner join.
- An equi join is a join condition that contains equality sign.
Outer Join:-
- Outer joins are used to also see rows that do not meet the join condition.
- Outer join operator is (+).
- The missing rows can be returned if an outer join operator is used in the join
condition.
- The operator (+) is placed on the side of the join that is deficient in information.
- This operator has the effect of creating one or more null rows to each one or more
rows from the (join condition) non deficient table can be joined.
Self Join
- Self join is used to join a table to itself.
Ex:- to find the name of each employer’s manager.
…….
1
2
……
…
Gopi
Raj
….
BINARY_INTEGER SCALOU
Syntax TYPE ename_table_type IS TABLE OF
Employees.last_name%TYPE
INDEX BY BINARY_INTEGER;
-this can be reterened by
INDEX Bytable_name (primary_key_value);
- The Following methods are used with INDEX BY Tables.
1. EXISTS
2. OUNT
3. FIRST AND LAST
4. PRIOR
5. NEXT
6. TRIM
7. DELETE
INDEX BY Table of Records:_
- At a given point of time. INDEX BY Table can store only the details of any one of
the columns of a database table
- To store al the columns retried by a query,
INDEX BY Table of Records are used.
- Because only the table definition is needed to hold information about all of the fields of a
data base table, the table of records greatly increases the functionality if INDEX BY Table.
*% ROW TYPE attribute can be used to declare a record that represents a row in a database
table.
*The difference between the % ROWTYPE attribute and the composite data type RECORD
is that RECORD allows to specify the data types of fields in the record or to declare new
fields with new data types.
Nested Tables
* Nested Table is an ordered group of items of type TABLE.
Nested Table contain multiple columns and can be used as variables, parameters, results,
attributes and columns.
They can be thought of as one column data base tables.
Rows of a nested table are not stored in any particular order.
The size of a nested table can be increased dynamically i.e. nested tables are unbounded.
Elements in a table initially have consecutive subscripts, but as elements are deleted, they can
have non-consecutive subscripts.
The range of values for nested table subscripts is 1 ..2147483647.
To extend a nested table, the built-in procedure EXTEND must be used.
To delete elements, the built-in procedure DELETE must be used.
An un initialized nested table is automatically null, so the IS NULL comparison operator can
be used to ses if nested table is null.
The operators CAST, THE and MULTISET are used or manipulating nested tables.
3. Create a data base table STORAGE having type ELEMENTS_TAB as one of its
columns.
SQL> Create Table STORAGE
(Saleman number(4),
Elem_id number(6),
Ordered Date,
Items Elements_Tab)
NESTED TABLE ITEMS STORE AS ITEMS_TAB;
VARRAYS:-
Creating a VARRAY:-
1. Defining object type ELEMENTS
SQL> Create TYPE MEDICINES AS OBJECT
(MED_ID NUMBER (6),
MED_NAME Varchar2 (14),
MANF_DATE DATE);
/