Vous êtes sur la page 1sur 7

Cursor: is a memory structure (used in PL/SQL programming) that stores the results of an executed

SQL statement.They are extremely useful for performing operations on each row returned from a select
statement.

Types of cursors:
 Implicit- Every SQL statement executes in an implicit cursor (including update, delete, insert and
select statements which returns a single row and that do not execute in explicit cursor).
- It is written inside executable section of PL/SQL block.
- Does not have a name.
- Cannot be opened or closed by user.
- Cannot select/return more than one row.
 Explicit-When the developer wants to perform manipulation on multiple rows returned by select
operation, she will use explicit cursor.
- It has a name
- must be declared
- query returns one or multiple rows
- used in executable section of PL/SQL block, explicit open, fetch and close statements
required (except for in cursor for loop)
- used with a loop to fetch all the multiple rows one by one.

Cursor Attributes: properties of cursors used to manipulate behavior of loops, records, and cursors
themselves.
 Cursorname%found: true if select statement returns a row.
 Cursorname%notfound
 Cursorname%isopen:true if cursor is open
 Cursorname%rowcount: gives the no. of rows processed by this cursor.

Loops: are needed to execute a set of statements repeatedly.


Simple/Basic loops:code block start with keyword LOOP and has an exit condition inside the block which tells loop when to
stop.
In a While loop: the exiting condition is evaluated at the beginning of the statement, while in
basic loop it is evaluated whereever the EXIT WHEN statement is placed. While loop does not
need an EXIT statement.

Difference between anonymous PL/SQL blocks and stored procedure and function:
1) Stored procedure and function has a name while anonymous P/SQL block has no name, thus being anonymous.
You simply submit the anonymous block and oracle runs it, while a stored subprogram is stored in the database and
can be called upon to do its thing without having to be resubmitted by the user.
2) Second key difference is that stored procedures an functions allow us to pass in parameters, while anonymous
PL/SQL blocks allow no parameter passing. This feature makes stored subprograms flexible and usable again and
again without the need to recompile the code.

Difference between Stored Procedure and Funtion:


1) A stored procedure can accept one or more values as parameters(or none at all), and can return one or many
values(or none at all).
In contrast, a function accepts one or more values as parameters(or none at all), but always returns one value.
[A function can return more than one value by OUT or INOUT parameters but it is considered a poor style].
2) A procedure call is a PL/SQL statement by itself. It is not called as part of an expression.
while a function call is called as part of an expression. (See down also).

When to use a procedure and when function:


The rule of thumb is that if there is more than one return value, use a procedure. If there is only one return value, a
function can be used.
[Although, a function can return more than one value by OUT or INOUT parameters but it is considered a poor
style. A function should return only the value specified in the RETURN statement (last line of function) in order to
conform to the higher purity level for optimization and prevention of ill side effects. Thus use of OUT or INOUT
parameter should be avoided in a function though it is legal.]

RETURN command is the last statement in function. It is used to return control to the caller with a value. There can
be more than one RETURN statemnet in a function, although only one will be executed. It is an error for a function
to end without executing a RETURN.

Privileges:

A system privilege called CREATE PROCEDURE (granted by DBA usually) is needed by the user to be able
compile and store the stored procedures and functions.
eg:
GRANT create procedure to Pawan;

Once developed, anyone who has the object privilege called EXECUTE can run/ call a stored
subprogram.
eg:
GRANT execute on delete_employee to pawan; (where delete_employee() is the name of a
function owned by poonam).

Use of IS/AS : signifies the start of declaration section to declare variables other than the
procedure parameters.
IS: used if there is no additional variables to declare.
AS: If variables have to be declared.

Parameter modes:
IN parameter variable: Values must be passed in for this parameter when subprogram is called, but not
returned. The IN parameter cannot be assigned a value inside the procedure
(eg: v_ INparameter:= 7). Inside the procedure, the formal parameter is considered as READ
only, it cannot be changed.

Actual value that can be passed can be a constant, literal, initialized variable or expression.
eg: declare
v_variable1 number;
v_variable2 number;
begin
Modetest(12, v_variable1, v_variable2)
IN OUT INOUT parameter in procedure.
Modetest(12, v_variable1, 11)
illegal- since literal cannot be hold any OUT/returned value
OUT parameter: specifies that the procedure returns a value to the calling program, but none
passed in. Formal parameter is considered as WRITE only.
Actual parameter (in the calling program) that corresponds to it must be a variable (so that it can
hold the returned value). It cannot be a literal, constant, or expression.

INOUT: Values are passed into the procedure when called/invoked and when the procedure
finishes a value is returned to the calling program.
A lieral value may not be passed in as a parameter, but rather a variable must be defined at the
procedure caller level that contains a value passed in and can hold a value passed out.

EXCEPTIONS raised inside a procedure or function:

If an error occurs inside a subprogram and it is not handled in the exception handler, control
immediately passes out of the procedure to the calling block in search of code that will handle
that exception (in accordance with exception propogation rules) without returning the values of
OUT and INOUT parameters.

Exceptions: 1) Oracle-defined or pre-defined -built in exceptions such as no_data_found.


-raised automatically whenever they occur but
needs to be handled in the exception handler section (either with specific exception name or with
the WHEN OTHERS THEN clause [catches any kind of exception that may arise] ).
eg:
......
EXCEPTION
When no_data_found Then dbms_output.put_line('NO DATA')
When OTHERS Then dbms_output.put_line('An error occurred')
END;

2) User-defined -exception created by the user by declaring and raising it in


executable section. Code required in all the 3 sections: Declare, Executable and Exception.
3) Internal exceptions- allows us to associate an exception name with an Oracle
numbered error using pragma exeption_init.

RAISE_APPLICATION_ERROR( ) is an important built in procedure used in PL/SQL for


reporting descriptive error messages (eg:see pg 370). This procedure assigns an error number
within the special range 20000-20999 and provides an error message. Triggers as well as stored
procedures and functions can raise errors with the RAISE_APPLICATION_ERROR procedure..

Syntax:
RAISE_APPLICATION_ERROR(error_number, error_message, [keep_errors]);
This procedure accepts 3 variables as parameters:
error_number: between -20,000 and -20,999 that should be unique for each procedure and/ or
error in the application,
error_message -text describing error (max 512 characters).
keep_errors (boolean parameter, optional, default false) (Tells oracle to keep (true) or not to
keep (false) preexisting errors - raised before this).
Advantage: Since we can create unique ID nos. for the subprograms and /or errors, it helps to
detect which procedure or function experienced the error and why which will help to speed up
the resolution time on specific issues when you have dozens or hundreds of PL/SQL programs
working together as an application.
p-code:
When a subprogram is created via CREATE OR REPLACE command, it is stored in the
database in compiled form known as p-code. P-code has all the object referenes in the
subprogram evaluated (thus execution of p-code is comparatively inexpensive operation), and the
source code is translated into a form easily readable by PL/SQL engine. When subprogram is
called p-code is read from the disk and executed.

INVOKING procedures and Functions:


Subprograms can be invoked or called form SQL*PLUS or from other PL/SQL procedures and
functions.

EXECUTE (or EXEC) command is used to execute stored procedures in SQL*PLUS:


eg:
SQL> EXECUTE delete_employee('PERCENT', 12, 11);
PL/SQL procedure successfully complted.

Calling a procedure from an anonymous PL/SQL block:


Begin
delete_employee('PERCENT', 12, 11);
End;

Functions cannot be called directly and independently as with procedure; rather the call is made
usually in reference to a variable (to hold the return value that function must produce), or as a
function in a select statement (as with any other SQL function).

Declare
my_return_value number;
Begin
my_return_value := my_function(3,4); ----name of function
End;

Or,
Select my_function(3,4)
From Dual;

Or Even,
Declare
my_return_value number;
Begin
Select my_function(3,4)
INTO my_return_value
From Dual;
End;

To Recompile existing procedure and function use:


SQL> ALTER PROCEDURE proc_name COMPILE;
SQL> ALTER FUNCTION function_name COMPILE;
TRIGGERS
A trigger is a database object directly associated with a table and fires automatically whenever a triggering event
happens.
(act of executing a trigger is called firing).
Triggering event is a DML operation like INSERT, UPDATE or DELETE on a database table. (eg: see pg 318-319).

Triggers are similar to procedures and functions, in that they are named PL/SQL blocks with declarative, executable,
and exception handling sections. Like packages, triggers must be stored in database and cannot be local to a block.

Difference between a database trigger, stored procedure and forms trigger: Imp. Question.
A procedure/function is executed explicitly when it is called from another block or by execute command and can be
passed arguments. While a trigger is executed automatically(implicitly) whenever the triggering event happens, and
also it does not accept arguments.
Forms trigger similarly to a database trigger consists of PL/SQL code that runs when a specific action takes place.
The difference is that a forms trigger is stored in forms application, in turn stored on the client machine and not the
database. The forms trigger also fires when a specific event occurs on the application GUI, such as button being
pressed. In contrast, the database trigger fires when a database event happens, such as a new row of data being
inserted in the table.

SYNTAX:

CREATE [OR REPLACE] TRIGGER trigger_name


{BEFORE/AFTER} triggering event [ON reference_column] ON reference_table
[FOR EACH ROW [WHEN trigger_condition]]
Declare
trigger_body (Main code of trigger);
Required components of a trigger are trigger name, trigger evnt and the body.
triggering_event : specifies when a trigger fires (before or after any DML operation)
eg: CREATE OR REPLACE TRIGGER update_majorstats
AFTER INSERT OR DELETE OR UPDATE ON students
Means after a insert or a delete or a update on the students table this trigger will be fired.

trigger_condition in the WHEN clause (optional) if present is evaluated first. The body of the
trigger will be executed only when this condition evaluates to true.

Naming triggers: Trigger can have the same name (although not recommended) as a table or procedure since triggers
exist in a separate namespace (set of legal identifiers available for naming objects) than procedures, functions,
packages and tables( which share same namespace). But within one schema a given name can be used for only one
trigger.
Eg: We can create a trigger emp on emp table, but it is illegal to create a procedure called emp.

Statement level trigger: The basic type of trigger is a statement trigger. It fires once either before
or after the triggering statement.
Row level trigger: trigger is fired once for each row affected by the triggering statement.
Identified by FOR EACH ROW clause.

TYPES of TRIGGERS: determined by triggering event (insert, update, delete), timing


(before/after) and level (row or statement). (see pg 322).
12 types of triggers:
 Before update statement trigger
 After update statement trigger
 Before delete statement trigger
 After delete statement trigger
 Before insert statement trigger
 After insert statement trigger
 Before update row trigger
 After update row trigger
 Before delete row trigger
 After delete row trigger
 Before insert row trigger
 After insert row trigger

Restrictions on triggers: (pg:323)


Cannot issue transaction control statements- COMMIT, ROLLBACK, or SAVEPOINT.
Similarly, any procedure or function that are called by the trigger body cannot issue tran. Control
statements.

ALTER TRIGGER trigger_name disable/enable;


DROP TRIGGER trigger_name;

Data dictionary views:


DBA_triggers, ALL_triggers, USER_TRIGGERS:
Tells about
Trigger_name, trigger_type (statement or row), triggering_event (insert, update, delete),
table_name (table to which it is attached), referencing_name (old or new referencing name if
choosen for row level trigger, null for statement), STATUS (enabled or disabled), trigger_body
(code), etc.

USER_TRIGGER_COLS: information about specific columns used in triggers.

Vous aimerez peut-être aussi