SlideShare a Scribd company logo
12/10/2016 OneNote Online
1/11
PL/SQL ­ 
                        ­ It stands for Procedural Language extension of SQL. 
                     ­ It is a combination of SQL along with the procedural features of programming languages. 
 
The PL/SQL Engine :­ 
•  Oracle uses a PL/SQL engine to processes the PL/SQL statements. 
•  PL/SQL code can be stored in the client system (client­side) or in the database (server­side). 
                                                              
Advantages of PL/SQL ‐> 
                                                     PL/SQL is a completely portable, high‐performance transac�on processing language that offers
the following advantages: 
 
• Block Structures ­ PL SQL consists of blocks of code, which can be nested within each other.  
                              Each block forms a unit of a task or a logical module.  
                                          PL/SQL Blocks can be stored in the database and reused. 
 
•  Procedural Language Capability ­ PL SQL consists of procedural language constructs such as   
                                                                            conditional statements (if else statements) and loops like (FOR loops). 
 
•  Better Performance ­ PL SQL engine processes multiple SQL statements simultaneously as a single   
                                                   block, thereby reducing network traffic.  
 
• Error Handling ­ PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL  
                                         program.  
                                        Once an exception is caught, specific actions can be taken depending upon the type of   
                                        the exception or it can be displayed to the user with a message. 
 
OTHER ADVANTAGES ‐     
1. Support for OOP's. 
2. Higher produc�vity. 
3. Full portability. 
4. Tight integra�on with Oracle. 
5.  Security. 
 
Block Structure ‐>  
• PL/SQL is a block‐structured language i.e., (procedures, func�ons, and anonymous blocks ).         
• PL/SQL supports the divide‐and‐conquer approach to problem solving called stepwise refinement.  
 
A PL/SQL block has three parts : 
1. Declara�ve part ‐  Items will be declared. 
2. Executable part ‐ Once declared, Manipula�on of items can only be done in executable part. 
3. Excep�on‐Handling part ‐ PL/SQL makes it easy to detect and process predefined and  
                                                           user‐ defined error condi�ons or Warnings called excep�ons. 
                                            ‐  When an error (excep�on raised ) occurs normal execu�on stops and 
                            control transfers to the excep�on‐handling part of PL/SQL block or subprogram.                  
                             To handle raised excep�ons, you write separate rou�nes called excep�on handlers. 
 
• Nes�ng of sub‐blocks can be done in executable and excep�on handling part of PL/SQL program  
BUT not in Declara�ve part. 
• Calling of local subprogram can be done only from block in which they are defined. 
 
 
PL/SQL 
Monday, November 14, 2016  10:01 AM 
2/11
 
PL/SQL Placeholders ­ 
• Placeholders are temporary storage area.  
• Placeholders can be any of Variables, Constants and Records.  
• Oracle defines placeholders to store data temporarily, which are used to manipulate data during the execution of a PL SQL
block. 
• Datatypes used to define placeholders are ­> 
        Number (n , m) , Char (n) , Varchar2 (n) , Date , Long , Long raw, Raw, Blob, Clob, Nclob, Bfile . 
 
 PLS_INTEGER Datatype 
•  Used to declare an integer variable 
• It is the most efficient numeric type. 
•  PLS_INTEGER values require less storage than INTEGER or NUMBER values  
• represented internally as 22‐byte Oracle numbers.  
• PLS_INTEGER opera�ons use machine arithme�c, so they are faster than BINARY_INTEGER, INTEGER, or NUMBER 
 
COMMIT 
     The COMMIT statement ends the current transac�on and makes permanent any changes made during that transac�on. Un�l you commit the changes, other
users cannot access the changed data; they see the data as it was before you made the changes. 
   
 ROLLBACK  
• The ROLLBACK statement ends the current transac�on and undoes any changes made during that transac�on.  
• Rolling back is useful for two reasons.  
First, if you make a mistake like dele�ng the wrong row from a table, a rollback restores the original data.  
Second, if you start a transac�on that you cannot finish because an excep�on is raised or a SQL statement fails  
• a rollback lets you return to the star�ng point to take correc�ve ac�on and perhaps try again 
 
Variables and Constants ‐> 
• Forward references are not allowed. So, you must declare a constant or variable before referencing it in other statements,
including other declara�ve statements.  
 
 Declaring Variables ‐ 
• Variables can have any SQL datatype, such as CHAR, DATE, NUMBER or any PL/SQL datatype, such as BOOLEAN or
BINARY_INTEGER.  
 
• Syntax 1: 
variable_name datatype(); 
 
• Syntax 2: [Assigning value to var ] 
variable_name:=  value;               [Assignment operator (:=) ‐> a colon followed by an equal sign. ] 
 
REM: Place the variable to the le燝� of the operator and an expression to the right. 
 
• Declaration of two variables, one of which is a not null. 
   Syntax :     
          DECLARE 
          salary number(4); 
              dept varchar2(10) NOT NULL := “HR Dept”; 
 
• Another way to assign values to a variable is to select or fetch database values into it.  
Syntax :           
SELECT column_name INTO variable_name  
FROM table_name [WHERE condition]; 
Eg. SELECT sal * 0.10 INTO bonus  
Variable declaration
Program Execution
Exception handling
END;
DECLARE
How a Sample PL/SQL Block Looks•
FROM emp WHERE empno = emp_id;
12/10/2016 OneNote Online
3/11
       
 
Scope of PL/SQL Variables ­ 
                                                        The variable which is accessible to an outer Block is also  accessible to all nested inner
Blocks. The variables declared in the inner blocks are not accessible to outer blocks.  
Based on their declaration we can classify variables into two types.  
• Local variables ­ These are declared in a inner block and cannot be referenced by outside Blocks. 
• Global variables ­ These are declared in a outer block and can be referenced by its itself and by its inner blocks.  
 
Declaring Constants ‐ 
                                          The word CONSTANT is a reserved word and ensures that the value does not change. 
Assign a value in the execution section will produce an error ,therefore do assigning during declaring. 
Syntax : 
            const_name CONSTANT datatype := VALUE; 
Eg. credit_limit CONSTANT REAL := 5000.00;         { Here, Const_name ‐ credit_limit} 
 
NOTE: You can use also %type to declare variables and constants.  
NOTE: The backward slash '/' in end of the program indicates to execute the PL/SQL Block.  
 
Control Structures ‐> 
                                       { IF‐THEN‐ELSE, FOR‐LOOP , WHILE‐LOOP , EXIT‐WHEN, and GOTO. } 
 
1. Condi�onal Control ‐  [ IF‐THEN‐ELSE ] 
                                                          IF clause checks a condi�on;  
                                                              THEN clause defines what to do if condi�on is true; 
                                                              ELSE clause defines what to do if the condi�on is false or null. 
       Syntax : 
 IF condition THEN  
                          statement 1;  
       ELSE  
                          statement 2;  
       END IF; 
                                            
2. Itera�ve Control ‐  [ FOR‐LOOP , WHILE‐LOOP , EXIT‐WHEN] 
                                   ‐ LOOP statements let you execute a sequence of statements mul�ple �mes 
                               
#.  A FOR LOOP is used to execute a set of statements for a predetermined number of times.  
     Iteration occurs between the start and end integer values given.  
       The counter is always incremented by 1.  
     The loop exits when the counter reaches the value of the end integer. 
=> Syntax :  
          FOR counter IN value(1)...value(last)  
             LOOP statements;  
          END LOOP; 
  
**  Important steps to follow when execu�ng a FOR loop:  
1) The counter variable is implicitly declared in the declara�on sec�on, so it's not necessary to declare     
      it explicitly. 
2) The counter variable is incremented by 1 and does not need to be incremented explicitly. 
3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's not done o燝�enly.  
 
#.  The WHILE‐LOOP statement associates a condi�on with a sequence of statements.  
      Before each itera�on of the loop, the condi�on is evaluated.  
      If the condi�on is true, the sequence of statements is executed, then control resumes at the top   
      of the loop. 
       If the condi�on is false or null, the loop is bypassed and control passes to the next statement  
=> Syntax : 
       WHILE <condition>  
4/11
         LOOP statements;  
       END LOOP;  
 
** Important steps to follow when executing a while loop:  
1) Initialise a variable before the loop body. 
2) Increment the variable in the loop. 
3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not done oftenly.  
     
#. The EXIT‐WHEN statement lets you complete a loop if further processing is impossible/ undesirable.   
    When the EXIT statement is encountered, the condi�on in the WHEN clause is evaluated.  
    If the condi�on is true, the loop completes and control passes to the next statement 
 
=> Syntax :  
 LOOP  
   statements;  
 EXIT;  
           {or EXIT WHEN condition;} 
 END LOOP;  
 
** Important steps to be followed while using Simple Loop. 
1) Initialize a variable before the loop body. 
2) Increment the variable in the loop. 
3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without WHEN condition, the statements
in the loop is executed only once. 
 
 
3. Sequen�al Control ‐  [ GOTO ] 
                                   ‐ The GOTO statement lets you branch to a label uncondi�onally. 
                                        ‐   When executed , the GOTO statement transfers control to the labeled  
                                                         statement or block, 
Syntax: 
             GOTO label_name; 
                    where label_name is the name of a label iden�fying the target statement 
 
There are several restric�ons on the GOTO statement: 
• At least one executable statement must follow a label. 
• The target label must be in the same scope as the GOTO statement. 
 
PL/SQL Records ­            
•  Records are another type of datatypes which oracle allows to be defined as a placeholder.                           
•  Records contain uniquely named fields, which can have different datatypes like char ,  
varchar , number etc.   
• Each scalar data types in the record holds a value.  
• A record can be visualized as a row of data. It can contain all the contents of a row.  
 
Define and declare a PL/SQL record ­> 
Syntax   Usage  
TYPE record_type_name IS RECORD (column_name1
datatype, column_name2 datatype, ...);  
Define a composite datatype, where each field is scalar.  
col_name table_name.column_name%type;   Dynamically define the datatype of a column based on a database column.  
record_name record_type_name;   Declare a record based on a user­defined type.  
record_name table_name%ROWTYPE;   Dynamically declare a record based on an entire row of a table. Each column in
the table corresponds to a field in the record. 
 
5/11
1)  You do not need to explicitly declare variables for all the columns in a table.  
2. If you alter the column specification in the database table, you do not need to update the code.  
 
The disadvantage of declaring the record as a ROWTYPE is: 
1) When u create a record as a ROWTYPE, fields will be created for all the columns in the table and    
      memory will be used to create the datatype for all the fields. So use ROWTYPE only when you are     
      using all the columns of the table in the program. 
 
Assign values to and from a Record ­> 
 
Syntax   Usage  
record_name.col_name := value;   To directly assign a value to a specific column of a record.  
record_name.column_name := value;   To directly assign a value to a specific column of a record, if the
record is declared using %ROWTYPE.  
SELECT col1, col2 INTO record_name.col_name1,
record_name.col_name2 FROM table_name [WHERE clause];  
To assign values to each field of a record from the database table.  
SELECT * INTO record_name FROM table_name [WHERE clause];   To assign a value to all fields in the record from a database table. 
variable_name := record_name.col_name;   To get a value from a record column and assigning it to a variable.  
  
Packages ‐                  
                          A package is a collec�on of PL/SQL objects , grouped together under one package name.  
Packages provide a means , to collect related procedures, func�ons, cursors, declara�ons, types, and variables into a single, named
database object that is more flexible than the related database objects. 
 
Packages usually have two parts: Specifica�on and  Body.  
‐> The specifica�on is the interface to your applica�ons which declares the types, constants, variables,      
       excep�ons, cursors, and subprograms available for use.  
‐> The body defines cursors and subprograms and so implements the specifica�on. 
 
• Syntax for a package is: 
CREATE [OR REPLACE PACKAGE[ <package name> {AS|IS} 
    <variable declara�ons>; 
    <cursor declara�ons>; 
    <procedure and func�on declara�ons>; 
END <package name>; 
 
 
Subprograms ‐ 
                             PL/SQL has two types of subprograms called procedures and func�ons, which can take parameters and be
invoked (called). 
 
Benefits/Advantages of Subprograms ‐ 
 
1. Improved Data Security – controls access to  database objects while enabling non‐privileged   
                                                           applica�on  users to access just the data needed.  
2. Improved Data Integrity – Related ac�ons on database tables are performed as a unit enforcing          
                                                            transac�on integrity – all updates are executed or none are executed. 
3. Improved App Performance – Avoids reparsing obj used by mul�ple users through shared use of SQL by                                        
              Oracle  – reduces number of database calls thus reducing network traffic. 
4. Improved Maintenance – procedures and func�ons that perform common tasks can be modified  
                                                           without having to directly work on mul�ple apps – eliminates duplicate tes�ng. 
5. Provide Extensibility. 
6. Provide Modularity. { Break program into manageable , well defined logic modules } 
7. Subprograms promote Reusability and Maintainability. 
The advantages of declaring the record as a ROWTYPE are:
8. Subprograms aid Abstractionon. { Mental separation from particulars}
6/11
 
2. Func�ons  
 
 
 
 
 
                          PROCEDURES                           FUNCTIONS 
1. Coded to perform a specific ac�on.  1. Coded  to perform some type of
calcula�ons. 
2. A Procedure has two parts:  
The Specifica�on and The Body.  
The procedure spec begins with the keyword
PROCEDURE and ends with the procedure
NAME or Parameter list 
2. A Func�on has two parts:  
The Specifica�on and The Body.  
The Func�on spec begins with the keyword
FUNCTION and ends with the RETURN clause. 
3. [OR REPLACE] op�on allows modifying an
exis�ng procedure. 
3. [OR REPLACE] op�on allows modifying an
exis�ng func�on 
4. Procedure are called with PL/SQL
statement. 
4. Func�ons are called as part of an
expression. 
5. Procedures are named PL/SQL blocks.   
6. Created/Owned by par�cular schema.   
 
SIMILIARITIES IN PROCEDURES & FUNCTIONS ‐> 
• Both procedures and func�ons can take mul�ple parameters. 
• Can be programmed to perform a data processing task. 
• Can be stored as individual database objects.   
• Are named PL/SQL blocks, and both can be coded to take parameters to generalize the code.  
• Can be wri눚�en with declara�ve, executable, and excep�on sec�ons. 
 
PASSING PARAMETER TO PROCEDURES AND FUNCTIONS ‐> 
 
1. IN – Pass value to a procedure as a read‐only value that cannot be changed within the procedure – this is the default mode. 
2. OUT – this parameter type is write‐only, and can only appear on the le燝� side of an assignment statement in the procedure – it
is assigned an ini�al value of NULL. 
3. IN OUT – this parameter type combines both IN and OUT; Pass & get value from stored procedures. 
 
 
CURSORS ‐>                
• A cursor is a temporary work area created in the system memory when a SQL statement is executed.  
• A cursor contains information on a select statement and the rows of data accessed by it.  
• This temporary work area is used to store the data retrieved from the database, and manipulate this data.  
• A cursor can hold more than one row, but can process only one row at a time.  
• The set of rows the cursor holds is called the active set. 
 
Cursor Variables ‐ 
               Like a cursor, a cursor variable points to the current row in the result set of a mul�‐row query.   
            
1. Cursor var can be opened for any type­compatible query.    
2. It is not tied to a specific query. 
3. Cursor var are true PL/SQL variables, in which we can pass or assign new values to subprogram of DB. 
4. Provide convenient way of data retrieval 
1. Procedures and
TYPES OF SUBPROGRAMS ‐>
DIFFERENCES B/W PROCEDURES & FUNCTIONS ‐>
5. It's more flexible.
OneNote Online
7/11
 
TYPES OF CURSOR ‐> 
1. Implicit Cursor ‐ PL/SQL implicitly declares a cursor for all SQL data manipula�on statements,   
                                      including queries  that return only one row.  
• These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed.   
• They are also created when a SELECT statement that returns just one row is executed. 
 
APPLICATION OF IMPLICIT ‐> 
                                                                  When you execute DML statements like DELETE, INSERT, UPDATE and SELECT
statements, implicit statements are created to process these statements. 
 
Implicit Cursor Attributes to check status of the DML statement ­ 
  
Attributes  Return values   Example 
%FOUND  TRUE, if fetch statement returns at least one row.  Cursor_name%FOUND 
  FALSE, if fetch statement doesn’t return a row.   
%NOTFOUND  TRUE, , if fetch statement doesn’t return a row.  Cursor_name%NOTFOUND 
  FALSE, if fetch statement returns at least one row.   
%ROWCOUNT  The number of rows affected by INSERT,DELETE, or
UPDTAE statement, or returned by select into
statement. 
Cursor_name%ROWCOUNT 
  If no row is returned / affected, the PL/SQL statement
returns an error. 
 
%ISOPEN  TRUE, if the cursor is already open in the program  Cursor_name%ISNAME 
  FALSE, if the cursor is not opened in the program.   
 
2. Explicit Cursor ‐ For queries that return more than one row, you can explicitly declare a cursor to  
                                     process the rows individually.  
• They must be created when you are executing a SELECT statement that returns more than one row.  
• Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row.  
• When you fetch a row the current row position moves to next row. 
• Both implicit and explicit cursors have the same functionality, but they differ in the way they accessed.  
 
APPLICATION OF EXPLICIT ‐> 
▪ An explicit cursor is defined in the declaration section of the PL/SQL Block. 
▪ It is created on a SELECT Statement which returns more than one row.  
▪ We can provide a suitable name for the cursor. 
 
Syntax for Crea�ng a Cursor : 
CURSOR cursor_name IS select_statement;      
                   // select_statement – A select query which returns multiple rows. 
 
Explicit Cursor Attributes to check status of the DML statement ­ 
 
Attributes   Return Value   Example 
%FOUND  The return value is TRUE, if the DML statements like INSERT, DELETE and
UPDATE affect at least one row and if SELECT ….INTO statement return at least
one row. 
SQL%FOUND 
   
12/10/2016
12/10/2016 OneNote Online
8/11
The return value is FALSE, if DML statements like INSERT, DELETE and
UPDATE do not affect row and if SELECT….INTO statement do not return a row. 
%NOTFOUND  The return value is FALSE, if DML statements like INSERT, DELETE and
UPDATE at least one row and if SELECT ….INTO statement return at least one
row. 
SQL%NOTFOUND 
  The return value is TRUE, if a DML statement like INSERT, DELETE and
UPDATE do not affect even one row and if SELECT ….INTO statement does not
return a row. 
 
%ROWCOUNT   Return the number of rows affected by the DML operations INSERT, DELETE,
UPDATE, SELECT  
SQL%ROWCOUNT 
 
How to use Explicit Cursor? 
        There are four steps in using an Explicit Cursor. 
• DECLARE the cursor in the declara�on sec�on. 
• OPEN the cursor in the Execu�on Sec�on.  [ OPEN cursor_name;] 
• FETCH the record in cursor one at a �me in the Execu�on Sec�on. 
FETCH cursor_name INTO record_name; 
                'OR'  
FETCH cursor_name INTO variable_list; 
• CLOSE the cursor in the Execu�on Sec�on before you end the PL/SQL Block.    
 [ CLOSE cursor_name;] 
 
NOTE­ Last 3 underlined steps of above Q is Ans of how to access Explicit cursor with syntax. 
 
General Form of using an explicit cursor is: 
DECLARE 
     variables; 
  records; 
  create a cursor; 
BEGIN  
OPEN cursor; 
FETCH cursor; 
  process the records; 
   CLOSE cursor; 
END; 
 
 
 
Code become simplified by using FOR loop instead of the OPEN, FETCH, and CLOSE statements 
 
Points to remember while fetching a row: 
• We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the PL/SQL Block.  
• If you are fetching a cursor to a PL/SQL Record, the record should have the same structure as the cursor. 
• If you are fetching a cursor to a list of variables, the variables should be listed in the same order in the fetch statement as the
columns are present in the cursor. 
 
What are Explicit Cursor A꓌�ributes? 
Oracle provides some attributes known as Explicit Cursor Attributes to control the data processing while using cursors. We
use these attributes to avoid errors while accessing cursors through OPEN, FETCH and CLOSE Statements. 
 
When does an error occur while accessing an explicit cursor? 
  a)  When we try to open a cursor which is not closed in the previous operation. 
  b)  When we try to fetch a cursor after the last operation. 
 
Result set ‐ The set of rows returned by a mul�‐row query is called the result set. 
                           ‐ Mul�‐row query processing is somewhat like file processing. 
                                  ‐ Cursor marks the current posi�on in a result set. 
 
 
12/10/2016 OneNote Online
9/11
Triggers ‐> 
                      A database trigger is a stored subprogram associated with a table. 
• A trigger is a PL/SQL block structure is fired (executed) , when a DML statements like Insert, Delete, Update is executed
on a database table. 
• A trigger is triggered automatically when an associated DML statement is executed. 
• By default, triggers are enabled. 
• A disabled trigger does not execute the trigger body even if the triggering statement is issued. 
• SYNTAX to Enable & disable triggers : 
ALTER TRIGGER trigger_name ENABLE; 
ALTER TABLE table_name ENABLE ALL TRIGGERS;   // Enable all triggers associated with a table. 
ALTER TRIGGER trigger_name DISABLE; 
• The WHEN clause only applies to ROW triggers. 
 
Database triggers can be used to perform any of the following tasks: 
1. Audit data modification. 
2. Log events transparently. 
3. Enforce complex business rules. 
4. Derive column values automatically.  
5. Implement complex security authorizations.  
6. Maintain replicate tables. 
 
Types of PL/SQL Triggers ­ 
                                                     
1) Row level trigger ­ An event is triggered for each row updated, inserted or deleted.  
2) Statement level trigger ­ An event is triggered for each sql statement executed. 
3) Instead of Trigger ‐ 
 
Syntax for Creating a Trigger ­> 
CREATE [OR REPLACE ] TRIGGER trigger_name  
{BEFORE | AFTER | INSTEAD OF }  
{INSERT [OR] | UPDATE [OR] | DELETE} 
[OF col_name] ON table_name  
[REFERENCING OLD AS o NEW AS n]  
[FOR EACH ROW]  
WHEN (condition)  
BEGIN  
 ­­ sql statements  
END;  
 
• CREATE [OR REPLACE ] TRIGGER ­ Creates a trigger with the given name or overwrites an existing                                        
                              trigger with the same name.  
 
• {BEFORE | AFTER | INSTEAD OF } ­ Indicates at what time should the trigger get fired.  
                                                              i.e., For Eg. Before or After updating a table.  
▪ INSTEAD OF is used to create a trigger on a view.  
▪ Before and After cannot be used to create a trigger on view. 
 
• {INSERT [OR] | UPDATE [OR] | DELETE} ­ Determines the triggering event.  
                                                                        ­ More than one triggering events can be used together separated by OR keyword.
The trigger gets fired at all the specified triggering event.  
 
• [OF col_name] ­ This clause is used with update triggers. This clause is used when you want to trigger an                              
 event only when a specific column is updated.  
 
• CREATE [OR REPLACE ] TRIGGER ­ This clause creates a trigger with the given name or overwrites an                                    
                              existing trigger with the same name.  
 
• [ON table_name] ­This clause identifies the name of the table or view to which the trigger is associated.  
 
12/10/2016 OneNote Online
10/11
• [REFERENCING OLD AS o NEW AS n] ­ This clause is used to reference the old and new values of the                                      
                                   data being changed.  
▪ By default, you reference the values as :old.column_name or :new.column_name.  
▪ The reference names can also be changed from old (or new) to any other user­defined name.  
▪ You can not reference old values when inserting a record, or new values when deleting a record, because they don't exist.  
 
• [FOR EACH ROW] ­ This clause is used to determine whether a trigger must fire when each row gets  
                                        affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is executed (i.e. statement
level Trigger).   
 
• WHEN (condition) ­ This clause is valid only for row level triggers. The trigger is fired only for rows that  
                                       satisfy the condition specified.  
 
 
 
 
 
  
1) BEFORE statement trigger fires first. 
2) Next BEFORE row level trigger fires, once for each row affected.  
3) Then AFTER row level trigger fires once for each affected row. This events will alternates between  
       BEFORE and AFTER row level triggers. 
4) Finally the AFTER statement level trigger fires. 
 
How To know Information about Triggers. 
We can use the data dictionary view 'USER_TRIGGERS' to obtain information about any trigger. 
 
 
CYCLIC CASCADING in a TRIGGER ­> 
                                                                 This is an undesirable situation where more than one trigger enter            into an
infinite loop. while creating a trigger we should ensure the such a situation does not exist.  
• The below example shows how Trigger's can enter into cyclic cascading. 
Let's consider we have two tables 'abc' and 'xyz'. Two triggers are created. 
1)  The INSERT Trigger, triggerA on table 'abc' issues an UPDATE on table 'xyz'. 
2) The UPDATE Trigger, triggerB on table 'xyz' issues an INSERT on table 'abc'. 
    In such a situa�on, when there is a row inserted in table 'abc', trigger A fires and will update table 'xyz'.  
     When the table 'xyz' is updated, triggerB fires and will insert a row in table 'abc'. 
     This cyclic situa�on con�nues and will enter into a infinite loop, which will crash the database 
 
Trigger Limita�ons ‐> 
1. Triggers cannot contain the COMMIT, ROLLBACK, and SAVEPOINT statements.  
2. Trigger body – cannot  exceed 32K in size.  
3. No limit on the number of triggers defined for a DML statement for a table.  In fact, you can define two triggers of the same
type for a table. When this occurs, the triggers of the same type fire sequen�ally. 
 
Facts About Triggers ‐> 
Triggers: 
• are named PL/SQL blocks with declara�ve, executable, and excep�on handling sec�ons.   
• are stand‐alone database objects – they are not stored as part of a package and cannot be local to a block.   
• do not accept arguments.  
 
 
 Excep�on Handling ‐> 
                        PL/SQL provides a feature to handle the Excep�ons which occur in a PL/SQL Block known as excep�on Handling.
Using Excep�on Handling we can test the code and avoid it from exi�ng abruptly. 
 
The following hierarchy is followed when a trigger is fired.
PL/SQL Trigger Execution Hierarchy
11/11
 
DECLARE  
   <declarations section>  
BEGIN  
   <executable command(s)>  
EXCEPTION  
   <exception handling goes here >  
   WHEN exception1 THEN   
       exception1­handling­statements   
   WHEN exception2  THEN   
      exception2­handling­statements   
   ........  
   WHEN others THEN  
      exception2­handling­statements  
END; 
 
Predefined Excep�ons ‐> 
                                     An internal excep�on is raised implicitly whenever your PL/SQL program violates an Oracle rule or
exceeds a system‐dependent limit.  
▪ Every Oracle error has a number, but excep�ons must be handled by name. So, PL/SQL predefines some common Oracle errors
as excep�ons.  
▪ For example, PL/SQL raises the predefined excep�on NO_DATA_FOUND if a SELECT INTO statement returns no rows 
 
User‐Defined Excep�ons ‐> 
                                          PL/SQL lets you define excep�ons of your own. 
Syntax: 
DECLARE  
   my‐excep�on EXCEPTION; 
• Must be declared in declara�on sec. 
• Must be raised explicitly by RAISE statements in execu�on sec. 
• You cannot declare an excep�on twice in the same block.  
• However, you can declare the same excep�on in two different blocks. 
• Excep�ons cannot appear in assignment statements or SQL statements but variables can. 
 
Advantages of Excep�ons 
1. Can handle errors conveniently without the need to check code mul�ple �mes. 
2. Error processing is not clearly separated from normal processing. 
3. Excep�ons improve readability. 
 
 
SYNTAX :•

More Related Content

What's hot

SQL Commands
SQL Commands SQL Commands
SQL Commands
Sachidananda M H
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
rehaniltifat
 
SQL commands
SQL commandsSQL commands
SQL commands
GirdharRatne
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
Sharad Dubey
 
Leftist heap
Leftist heapLeftist heap
Leftist heap
Shuvro Roy
 
Relational database
Relational database Relational database
Relational database
Megha Sharma
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
kuldeep100
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
Amrit Kaur
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
ammarbrohi
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
Ankit Rai
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
Dharita Chokshi
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
Nick Buytaert
 
DBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCLDBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCL
Sreedhar Chowdam
 
Normalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NF
Normalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NFNormalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NF
Normalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NF
Biplap Bhattarai
 
Sql ppt
Sql pptSql ppt
Sql ppt
Anuja Lad
 
Database language
Database languageDatabase language
Stored procedure
Stored procedureStored procedure
SQL select clause
SQL select clauseSQL select clause
SQL select clause
arpit bhadoriya
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
Nilt1234
 
Sql injection
Sql injectionSql injection
Sql injection
Mehul Boghra
 

What's hot (20)

SQL Commands
SQL Commands SQL Commands
SQL Commands
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
SQL commands
SQL commandsSQL commands
SQL commands
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
Leftist heap
Leftist heapLeftist heap
Leftist heap
 
Relational database
Relational database Relational database
Relational database
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
DBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCLDBMS Notes: DDL DML DCL
DBMS Notes: DDL DML DCL
 
Normalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NF
Normalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NFNormalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NF
Normalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NF
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Database language
Database languageDatabase language
Database language
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
SQL select clause
SQL select clauseSQL select clause
SQL select clause
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Sql injection
Sql injectionSql injection
Sql injection
 

Similar to PL-SQL, Cursors & Triggers

Chapter 1
Chapter 1Chapter 1
Chapter 1
pooja_123
 
PLSQL Notes.pptx
PLSQL Notes.pptxPLSQL Notes.pptx
PLSQL Notes.pptx
SHRISANJAY4
 
Plsql overview
Plsql overviewPlsql overview
Plsql overview
Gagan Deep
 
Bn 1018 demo pl sql
Bn 1018 demo  pl sqlBn 1018 demo  pl sql
Bn 1018 demo pl sql
conline training
 
PL/SQL
PL/SQLPL/SQL
Pl sql-ch1
Pl sql-ch1Pl sql-ch1
Pl sql-ch1
Mukesh Tekwani
 
Pl sql
Pl sqlPl sql
Pl sql
Mahfuz1061
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
PLSql.pptx
PLSql.pptxPLSql.pptx
PLSql.pptx
Sreenivas R
 
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
shivanikaale214
 
Pl sql chapter 1
Pl sql chapter 1Pl sql chapter 1
Pl sql chapter 1
PrabhatKumar591
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_material
gayaramesh
 
pl_sql.ppt
pl_sql.pptpl_sql.ppt
pl_sql.ppt
Prabhat106214
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
suresh
 
Les01
Les01Les01
Oracle Intro.ppt
Oracle Intro.pptOracle Intro.ppt
Oracle Intro.ppt
DevilPurkhasiya
 
1. In a 200 words or less explain the differences between SQL and .docx
1. In a 200 words or less explain the differences between SQL and .docx1. In a 200 words or less explain the differences between SQL and .docx
1. In a 200 words or less explain the differences between SQL and .docx
SONU61709
 
SQL EXCLUSIVE NOTES .pdf
SQL EXCLUSIVE NOTES .pdfSQL EXCLUSIVE NOTES .pdf
SQL EXCLUSIVE NOTES .pdf
NiravPanchal50
 
Oracle ADF Architecture TV - Design - Architecting for PLSQL Integration
Oracle ADF Architecture TV - Design - Architecting for PLSQL IntegrationOracle ADF Architecture TV - Design - Architecting for PLSQL Integration
Oracle ADF Architecture TV - Design - Architecting for PLSQL Integration
Chris Muir
 
Java Abs U Portal Education Grid
Java Abs   U Portal   Education GridJava Abs   U Portal   Education Grid
Java Abs U Portal Education Grid
ncct
 

Similar to PL-SQL, Cursors & Triggers (20)

Chapter 1
Chapter 1Chapter 1
Chapter 1
 
PLSQL Notes.pptx
PLSQL Notes.pptxPLSQL Notes.pptx
PLSQL Notes.pptx
 
Plsql overview
Plsql overviewPlsql overview
Plsql overview
 
Bn 1018 demo pl sql
Bn 1018 demo  pl sqlBn 1018 demo  pl sql
Bn 1018 demo pl sql
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 
Pl sql-ch1
Pl sql-ch1Pl sql-ch1
Pl sql-ch1
 
Pl sql
Pl sqlPl sql
Pl sql
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
 
PLSql.pptx
PLSql.pptxPLSql.pptx
PLSql.pptx
 
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
 
Pl sql chapter 1
Pl sql chapter 1Pl sql chapter 1
Pl sql chapter 1
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_material
 
pl_sql.ppt
pl_sql.pptpl_sql.ppt
pl_sql.ppt
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
 
Les01
Les01Les01
Les01
 
Oracle Intro.ppt
Oracle Intro.pptOracle Intro.ppt
Oracle Intro.ppt
 
1. In a 200 words or less explain the differences between SQL and .docx
1. In a 200 words or less explain the differences between SQL and .docx1. In a 200 words or less explain the differences between SQL and .docx
1. In a 200 words or less explain the differences between SQL and .docx
 
SQL EXCLUSIVE NOTES .pdf
SQL EXCLUSIVE NOTES .pdfSQL EXCLUSIVE NOTES .pdf
SQL EXCLUSIVE NOTES .pdf
 
Oracle ADF Architecture TV - Design - Architecting for PLSQL Integration
Oracle ADF Architecture TV - Design - Architecting for PLSQL IntegrationOracle ADF Architecture TV - Design - Architecting for PLSQL Integration
Oracle ADF Architecture TV - Design - Architecting for PLSQL Integration
 
Java Abs U Portal Education Grid
Java Abs   U Portal   Education GridJava Abs   U Portal   Education Grid
Java Abs U Portal Education Grid
 

More from Shalabh Chaudhary

Everything about Zoho Workplace
Everything about Zoho WorkplaceEverything about Zoho Workplace
Everything about Zoho Workplace
Shalabh Chaudhary
 
C Pointers & File Handling
C Pointers & File HandlingC Pointers & File Handling
C Pointers & File Handling
Shalabh Chaudhary
 
C MCQ & Basic Coding
C MCQ & Basic CodingC MCQ & Basic Coding
C MCQ & Basic Coding
Shalabh Chaudhary
 
Database Management System [DBMS]
Database Management System [DBMS]Database Management System [DBMS]
Database Management System [DBMS]
Shalabh Chaudhary
 
Soft Computing [NN,Fuzzy,GA] Notes
Soft Computing [NN,Fuzzy,GA] NotesSoft Computing [NN,Fuzzy,GA] Notes
Soft Computing [NN,Fuzzy,GA] Notes
Shalabh Chaudhary
 
Software Engineering (SE) Notes
Software Engineering (SE) NotesSoftware Engineering (SE) Notes
Software Engineering (SE) Notes
Shalabh Chaudhary
 
Operating System (OS) Notes
Operating System (OS) NotesOperating System (OS) Notes
Operating System (OS) Notes
Shalabh Chaudhary
 
Data Communication & Networking Notes
Data Communication & Networking NotesData Communication & Networking Notes
Data Communication & Networking Notes
Shalabh Chaudhary
 
Java Basics for Interview
Java Basics for InterviewJava Basics for Interview
Java Basics for Interview
Shalabh Chaudhary
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
Shalabh Chaudhary
 
Unified Modeling Language(UML) Notes
Unified Modeling Language(UML) NotesUnified Modeling Language(UML) Notes
Unified Modeling Language(UML) Notes
Shalabh Chaudhary
 
Advanced JAVA Notes
Advanced JAVA NotesAdvanced JAVA Notes
Advanced JAVA Notes
Shalabh Chaudhary
 
Core JAVA Notes
Core JAVA NotesCore JAVA Notes
Core JAVA Notes
Shalabh Chaudhary
 

More from Shalabh Chaudhary (15)

Everything about Zoho Workplace
Everything about Zoho WorkplaceEverything about Zoho Workplace
Everything about Zoho Workplace
 
C Pointers & File Handling
C Pointers & File HandlingC Pointers & File Handling
C Pointers & File Handling
 
C MCQ & Basic Coding
C MCQ & Basic CodingC MCQ & Basic Coding
C MCQ & Basic Coding
 
Database Management System [DBMS]
Database Management System [DBMS]Database Management System [DBMS]
Database Management System [DBMS]
 
Soft Computing [NN,Fuzzy,GA] Notes
Soft Computing [NN,Fuzzy,GA] NotesSoft Computing [NN,Fuzzy,GA] Notes
Soft Computing [NN,Fuzzy,GA] Notes
 
Software Engineering (SE) Notes
Software Engineering (SE) NotesSoftware Engineering (SE) Notes
Software Engineering (SE) Notes
 
Operating System (OS) Notes
Operating System (OS) NotesOperating System (OS) Notes
Operating System (OS) Notes
 
Data Communication & Networking Notes
Data Communication & Networking NotesData Communication & Networking Notes
Data Communication & Networking Notes
 
Java Basics for Interview
Java Basics for InterviewJava Basics for Interview
Java Basics for Interview
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Unified Modeling Language(UML) Notes
Unified Modeling Language(UML) NotesUnified Modeling Language(UML) Notes
Unified Modeling Language(UML) Notes
 
Advanced JAVA Notes
Advanced JAVA NotesAdvanced JAVA Notes
Advanced JAVA Notes
 
Core JAVA Notes
Core JAVA NotesCore JAVA Notes
Core JAVA Notes
 

Recently uploaded

Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
SakkaravarthiShanmug
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
TaghreedAltamimi
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
Madan Karki
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
gaafergoudaay7aga
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
architagupta876
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 

Recently uploaded (20)

Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 

PL-SQL, Cursors & Triggers

  • 1. 12/10/2016 OneNote Online 1/11 PL/SQL ­                          ­ It stands for Procedural Language extension of SQL.                       ­ It is a combination of SQL along with the procedural features of programming languages.    The PL/SQL Engine :­  •  Oracle uses a PL/SQL engine to processes the PL/SQL statements.  •  PL/SQL code can be stored in the client system (client­side) or in the database (server­side).                                                                 Advantages of PL/SQL ‐>                                                       PL/SQL is a completely portable, high‐performance transac�on processing language that offers the following advantages:    • Block Structures ­ PL SQL consists of blocks of code, which can be nested within each other.                                 Each block forms a unit of a task or a logical module.                                             PL/SQL Blocks can be stored in the database and reused.    •  Procedural Language Capability ­ PL SQL consists of procedural language constructs such as                                                                                conditional statements (if else statements) and loops like (FOR loops).    •  Better Performance ­ PL SQL engine processes multiple SQL statements simultaneously as a single                                                       block, thereby reducing network traffic.     • Error Handling ­ PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL                                            program.                                           Once an exception is caught, specific actions can be taken depending upon the type of                                            the exception or it can be displayed to the user with a message.    OTHER ADVANTAGES ‐      1. Support for OOP's.  2. Higher produc�vity.  3. Full portability.  4. Tight integra�on with Oracle.  5.  Security.    Block Structure ‐>   • PL/SQL is a block‐structured language i.e., (procedures, func�ons, and anonymous blocks ).          • PL/SQL supports the divide‐and‐conquer approach to problem solving called stepwise refinement.     A PL/SQL block has three parts :  1. Declara�ve part ‐  Items will be declared.  2. Executable part ‐ Once declared, Manipula�on of items can only be done in executable part.  3. Excep�on‐Handling part ‐ PL/SQL makes it easy to detect and process predefined and                                                              user‐ defined error condi�ons or Warnings called excep�ons.                                              ‐  When an error (excep�on raised ) occurs normal execu�on stops and                              control transfers to the excep�on‐handling part of PL/SQL block or subprogram.                                                To handle raised excep�ons, you write separate rou�nes called excep�on handlers.    • Nes�ng of sub‐blocks can be done in executable and excep�on handling part of PL/SQL program   BUT not in Declara�ve part.  • Calling of local subprogram can be done only from block in which they are defined.      PL/SQL  Monday, November 14, 2016  10:01 AM 
  • 2. 2/11   PL/SQL Placeholders ­  • Placeholders are temporary storage area.   • Placeholders can be any of Variables, Constants and Records.   • Oracle defines placeholders to store data temporarily, which are used to manipulate data during the execution of a PL SQL block.  • Datatypes used to define placeholders are ­>          Number (n , m) , Char (n) , Varchar2 (n) , Date , Long , Long raw, Raw, Blob, Clob, Nclob, Bfile .     PLS_INTEGER Datatype  •  Used to declare an integer variable  • It is the most efficient numeric type.  •  PLS_INTEGER values require less storage than INTEGER or NUMBER values   • represented internally as 22‐byte Oracle numbers.   • PLS_INTEGER opera�ons use machine arithme�c, so they are faster than BINARY_INTEGER, INTEGER, or NUMBER    COMMIT       The COMMIT statement ends the current transac�on and makes permanent any changes made during that transac�on. Un�l you commit the changes, other users cannot access the changed data; they see the data as it was before you made the changes.       ROLLBACK   • The ROLLBACK statement ends the current transac�on and undoes any changes made during that transac�on.   • Rolling back is useful for two reasons.   First, if you make a mistake like dele�ng the wrong row from a table, a rollback restores the original data.   Second, if you start a transac�on that you cannot finish because an excep�on is raised or a SQL statement fails   • a rollback lets you return to the star�ng point to take correc�ve ac�on and perhaps try again    Variables and Constants ‐>  • Forward references are not allowed. So, you must declare a constant or variable before referencing it in other statements, including other declara�ve statements.      Declaring Variables ‐  • Variables can have any SQL datatype, such as CHAR, DATE, NUMBER or any PL/SQL datatype, such as BOOLEAN or BINARY_INTEGER.     • Syntax 1:  variable_name datatype();    • Syntax 2: [Assigning value to var ]  variable_name:=  value;               [Assignment operator (:=) ‐> a colon followed by an equal sign. ]    REM: Place the variable to the le燝� of the operator and an expression to the right.    • Declaration of two variables, one of which is a not null.     Syntax :                DECLARE            salary number(4);                dept varchar2(10) NOT NULL := “HR Dept”;    • Another way to assign values to a variable is to select or fetch database values into it.   Syntax :            SELECT column_name INTO variable_name   FROM table_name [WHERE condition];  Eg. SELECT sal * 0.10 INTO bonus   Variable declaration Program Execution Exception handling END; DECLARE How a Sample PL/SQL Block Looks• FROM emp WHERE empno = emp_id;
  • 3. 12/10/2016 OneNote Online 3/11           Scope of PL/SQL Variables ­                                                          The variable which is accessible to an outer Block is also  accessible to all nested inner Blocks. The variables declared in the inner blocks are not accessible to outer blocks.   Based on their declaration we can classify variables into two types.   • Local variables ­ These are declared in a inner block and cannot be referenced by outside Blocks.  • Global variables ­ These are declared in a outer block and can be referenced by its itself and by its inner blocks.     Declaring Constants ‐                                            The word CONSTANT is a reserved word and ensures that the value does not change.  Assign a value in the execution section will produce an error ,therefore do assigning during declaring.  Syntax :              const_name CONSTANT datatype := VALUE;  Eg. credit_limit CONSTANT REAL := 5000.00;         { Here, Const_name ‐ credit_limit}    NOTE: You can use also %type to declare variables and constants.   NOTE: The backward slash '/' in end of the program indicates to execute the PL/SQL Block.     Control Structures ‐>                                         { IF‐THEN‐ELSE, FOR‐LOOP , WHILE‐LOOP , EXIT‐WHEN, and GOTO. }    1. Condi�onal Control ‐  [ IF‐THEN‐ELSE ]                                                            IF clause checks a condi�on;                                                                 THEN clause defines what to do if condi�on is true;                                                                ELSE clause defines what to do if the condi�on is false or null.         Syntax :   IF condition THEN                             statement 1;          ELSE                             statement 2;          END IF;                                               2. Itera�ve Control ‐  [ FOR‐LOOP , WHILE‐LOOP , EXIT‐WHEN]                                     ‐ LOOP statements let you execute a sequence of statements mul�ple �mes                                  #.  A FOR LOOP is used to execute a set of statements for a predetermined number of times.        Iteration occurs between the start and end integer values given.          The counter is always incremented by 1.        The loop exits when the counter reaches the value of the end integer.  => Syntax :             FOR counter IN value(1)...value(last)                LOOP statements;             END LOOP;     **  Important steps to follow when execu�ng a FOR loop:   1) The counter variable is implicitly declared in the declara�on sec�on, so it's not necessary to declare            it explicitly.  2) The counter variable is incremented by 1 and does not need to be incremented explicitly.  3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's not done o燝�enly.     #.  The WHILE‐LOOP statement associates a condi�on with a sequence of statements.         Before each itera�on of the loop, the condi�on is evaluated.         If the condi�on is true, the sequence of statements is executed, then control resumes at the top          of the loop.         If the condi�on is false or null, the loop is bypassed and control passes to the next statement   => Syntax :         WHILE <condition>  
  • 4. 4/11          LOOP statements;          END LOOP;     ** Important steps to follow when executing a while loop:   1) Initialise a variable before the loop body.  2) Increment the variable in the loop.  3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not done oftenly.         #. The EXIT‐WHEN statement lets you complete a loop if further processing is impossible/ undesirable.        When the EXIT statement is encountered, the condi�on in the WHEN clause is evaluated.       If the condi�on is true, the loop completes and control passes to the next statement    => Syntax :    LOOP      statements;    EXIT;              {or EXIT WHEN condition;}   END LOOP;     ** Important steps to be followed while using Simple Loop.  1) Initialize a variable before the loop body.  2) Increment the variable in the loop.  3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without WHEN condition, the statements in the loop is executed only once.      3. Sequen�al Control ‐  [ GOTO ]                                     ‐ The GOTO statement lets you branch to a label uncondi�onally.                                          ‐   When executed , the GOTO statement transfers control to the labeled                                                            statement or block,  Syntax:               GOTO label_name;                      where label_name is the name of a label iden�fying the target statement    There are several restric�ons on the GOTO statement:  • At least one executable statement must follow a label.  • The target label must be in the same scope as the GOTO statement.    PL/SQL Records ­             •  Records are another type of datatypes which oracle allows to be defined as a placeholder.                            •  Records contain uniquely named fields, which can have different datatypes like char ,   varchar , number etc.    • Each scalar data types in the record holds a value.   • A record can be visualized as a row of data. It can contain all the contents of a row.     Define and declare a PL/SQL record ­>  Syntax   Usage   TYPE record_type_name IS RECORD (column_name1 datatype, column_name2 datatype, ...);   Define a composite datatype, where each field is scalar.   col_name table_name.column_name%type;   Dynamically define the datatype of a column based on a database column.   record_name record_type_name;   Declare a record based on a user­defined type.   record_name table_name%ROWTYPE;   Dynamically declare a record based on an entire row of a table. Each column in the table corresponds to a field in the record.   
  • 5. 5/11 1)  You do not need to explicitly declare variables for all the columns in a table.   2. If you alter the column specification in the database table, you do not need to update the code.     The disadvantage of declaring the record as a ROWTYPE is:  1) When u create a record as a ROWTYPE, fields will be created for all the columns in the table and           memory will be used to create the datatype for all the fields. So use ROWTYPE only when you are            using all the columns of the table in the program.    Assign values to and from a Record ­>    Syntax   Usage   record_name.col_name := value;   To directly assign a value to a specific column of a record.   record_name.column_name := value;   To directly assign a value to a specific column of a record, if the record is declared using %ROWTYPE.   SELECT col1, col2 INTO record_name.col_name1, record_name.col_name2 FROM table_name [WHERE clause];   To assign values to each field of a record from the database table.   SELECT * INTO record_name FROM table_name [WHERE clause];   To assign a value to all fields in the record from a database table.  variable_name := record_name.col_name;   To get a value from a record column and assigning it to a variable.      Packages ‐                                             A package is a collec�on of PL/SQL objects , grouped together under one package name.   Packages provide a means , to collect related procedures, func�ons, cursors, declara�ons, types, and variables into a single, named database object that is more flexible than the related database objects.    Packages usually have two parts: Specifica�on and  Body.   ‐> The specifica�on is the interface to your applica�ons which declares the types, constants, variables,              excep�ons, cursors, and subprograms available for use.   ‐> The body defines cursors and subprograms and so implements the specifica�on.    • Syntax for a package is:  CREATE [OR REPLACE PACKAGE[ <package name> {AS|IS}      <variable declara�ons>;      <cursor declara�ons>;      <procedure and func�on declara�ons>;  END <package name>;      Subprograms ‐                               PL/SQL has two types of subprograms called procedures and func�ons, which can take parameters and be invoked (called).    Benefits/Advantages of Subprograms ‐    1. Improved Data Security – controls access to  database objects while enabling non‐privileged                                                               applica�on  users to access just the data needed.   2. Improved Data Integrity – Related ac�ons on database tables are performed as a unit enforcing                                                                       transac�on integrity – all updates are executed or none are executed.  3. Improved App Performance – Avoids reparsing obj used by mul�ple users through shared use of SQL by                                                       Oracle  – reduces number of database calls thus reducing network traffic.  4. Improved Maintenance – procedures and func�ons that perform common tasks can be modified                                                              without having to directly work on mul�ple apps – eliminates duplicate tes�ng.  5. Provide Extensibility.  6. Provide Modularity. { Break program into manageable , well defined logic modules }  7. Subprograms promote Reusability and Maintainability.  The advantages of declaring the record as a ROWTYPE are: 8. Subprograms aid Abstractionon. { Mental separation from particulars}
  • 6. 6/11   2. Func�ons                                       PROCEDURES                           FUNCTIONS  1. Coded to perform a specific ac�on.  1. Coded  to perform some type of calcula�ons.  2. A Procedure has two parts:   The Specifica�on and The Body.   The procedure spec begins with the keyword PROCEDURE and ends with the procedure NAME or Parameter list  2. A Func�on has two parts:   The Specifica�on and The Body.   The Func�on spec begins with the keyword FUNCTION and ends with the RETURN clause.  3. [OR REPLACE] op�on allows modifying an exis�ng procedure.  3. [OR REPLACE] op�on allows modifying an exis�ng func�on  4. Procedure are called with PL/SQL statement.  4. Func�ons are called as part of an expression.  5. Procedures are named PL/SQL blocks.    6. Created/Owned by par�cular schema.      SIMILIARITIES IN PROCEDURES & FUNCTIONS ‐>  • Both procedures and func�ons can take mul�ple parameters.  • Can be programmed to perform a data processing task.  • Can be stored as individual database objects.    • Are named PL/SQL blocks, and both can be coded to take parameters to generalize the code.   • Can be wri눚�en with declara�ve, executable, and excep�on sec�ons.    PASSING PARAMETER TO PROCEDURES AND FUNCTIONS ‐>    1. IN – Pass value to a procedure as a read‐only value that cannot be changed within the procedure – this is the default mode.  2. OUT – this parameter type is write‐only, and can only appear on the le燝� side of an assignment statement in the procedure – it is assigned an ini�al value of NULL.  3. IN OUT – this parameter type combines both IN and OUT; Pass & get value from stored procedures.      CURSORS ‐>                 • A cursor is a temporary work area created in the system memory when a SQL statement is executed.   • A cursor contains information on a select statement and the rows of data accessed by it.   • This temporary work area is used to store the data retrieved from the database, and manipulate this data.   • A cursor can hold more than one row, but can process only one row at a time.   • The set of rows the cursor holds is called the active set.    Cursor Variables ‐                 Like a cursor, a cursor variable points to the current row in the result set of a mul�‐row query.                 1. Cursor var can be opened for any type­compatible query.     2. It is not tied to a specific query.  3. Cursor var are true PL/SQL variables, in which we can pass or assign new values to subprogram of DB.  4. Provide convenient way of data retrieval  1. Procedures and TYPES OF SUBPROGRAMS ‐> DIFFERENCES B/W PROCEDURES & FUNCTIONS ‐> 5. It's more flexible.
  • 7. OneNote Online 7/11   TYPES OF CURSOR ‐>  1. Implicit Cursor ‐ PL/SQL implicitly declares a cursor for all SQL data manipula�on statements,                                          including queries  that return only one row.   • These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed.    • They are also created when a SELECT statement that returns just one row is executed.    APPLICATION OF IMPLICIT ‐>                                                                    When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit statements are created to process these statements.    Implicit Cursor Attributes to check status of the DML statement ­     Attributes  Return values   Example  %FOUND  TRUE, if fetch statement returns at least one row.  Cursor_name%FOUND    FALSE, if fetch statement doesn’t return a row.    %NOTFOUND  TRUE, , if fetch statement doesn’t return a row.  Cursor_name%NOTFOUND    FALSE, if fetch statement returns at least one row.    %ROWCOUNT  The number of rows affected by INSERT,DELETE, or UPDTAE statement, or returned by select into statement.  Cursor_name%ROWCOUNT    If no row is returned / affected, the PL/SQL statement returns an error.    %ISOPEN  TRUE, if the cursor is already open in the program  Cursor_name%ISNAME    FALSE, if the cursor is not opened in the program.      2. Explicit Cursor ‐ For queries that return more than one row, you can explicitly declare a cursor to                                        process the rows individually.   • They must be created when you are executing a SELECT statement that returns more than one row.   • Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row.   • When you fetch a row the current row position moves to next row.  • Both implicit and explicit cursors have the same functionality, but they differ in the way they accessed.     APPLICATION OF EXPLICIT ‐>  ▪ An explicit cursor is defined in the declaration section of the PL/SQL Block.  ▪ It is created on a SELECT Statement which returns more than one row.   ▪ We can provide a suitable name for the cursor.    Syntax for Crea�ng a Cursor :  CURSOR cursor_name IS select_statement;                          // select_statement – A select query which returns multiple rows.    Explicit Cursor Attributes to check status of the DML statement ­    Attributes   Return Value   Example  %FOUND  The return value is TRUE, if the DML statements like INSERT, DELETE and UPDATE affect at least one row and if SELECT ….INTO statement return at least one row.  SQL%FOUND      12/10/2016
  • 8. 12/10/2016 OneNote Online 8/11 The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE do not affect row and if SELECT….INTO statement do not return a row.  %NOTFOUND  The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE at least one row and if SELECT ….INTO statement return at least one row.  SQL%NOTFOUND    The return value is TRUE, if a DML statement like INSERT, DELETE and UPDATE do not affect even one row and if SELECT ….INTO statement does not return a row.    %ROWCOUNT   Return the number of rows affected by the DML operations INSERT, DELETE, UPDATE, SELECT   SQL%ROWCOUNT    How to use Explicit Cursor?          There are four steps in using an Explicit Cursor.  • DECLARE the cursor in the declara�on sec�on.  • OPEN the cursor in the Execu�on Sec�on.  [ OPEN cursor_name;]  • FETCH the record in cursor one at a �me in the Execu�on Sec�on.  FETCH cursor_name INTO record_name;                  'OR'   FETCH cursor_name INTO variable_list;  • CLOSE the cursor in the Execu�on Sec�on before you end the PL/SQL Block.      [ CLOSE cursor_name;]    NOTE­ Last 3 underlined steps of above Q is Ans of how to access Explicit cursor with syntax.    General Form of using an explicit cursor is:  DECLARE       variables;    records;    create a cursor;  BEGIN   OPEN cursor;  FETCH cursor;    process the records;     CLOSE cursor;  END;        Code become simplified by using FOR loop instead of the OPEN, FETCH, and CLOSE statements    Points to remember while fetching a row:  • We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the PL/SQL Block.   • If you are fetching a cursor to a PL/SQL Record, the record should have the same structure as the cursor.  • If you are fetching a cursor to a list of variables, the variables should be listed in the same order in the fetch statement as the columns are present in the cursor.    What are Explicit Cursor A꓌�ributes?  Oracle provides some attributes known as Explicit Cursor Attributes to control the data processing while using cursors. We use these attributes to avoid errors while accessing cursors through OPEN, FETCH and CLOSE Statements.    When does an error occur while accessing an explicit cursor?    a)  When we try to open a cursor which is not closed in the previous operation.    b)  When we try to fetch a cursor after the last operation.    Result set ‐ The set of rows returned by a mul�‐row query is called the result set.                             ‐ Mul�‐row query processing is somewhat like file processing.                                    ‐ Cursor marks the current posi�on in a result set.     
  • 9. 12/10/2016 OneNote Online 9/11 Triggers ‐>                        A database trigger is a stored subprogram associated with a table.  • A trigger is a PL/SQL block structure is fired (executed) , when a DML statements like Insert, Delete, Update is executed on a database table.  • A trigger is triggered automatically when an associated DML statement is executed.  • By default, triggers are enabled.  • A disabled trigger does not execute the trigger body even if the triggering statement is issued.  • SYNTAX to Enable & disable triggers :  ALTER TRIGGER trigger_name ENABLE;  ALTER TABLE table_name ENABLE ALL TRIGGERS;   // Enable all triggers associated with a table.  ALTER TRIGGER trigger_name DISABLE;  • The WHEN clause only applies to ROW triggers.    Database triggers can be used to perform any of the following tasks:  1. Audit data modification.  2. Log events transparently.  3. Enforce complex business rules.  4. Derive column values automatically.   5. Implement complex security authorizations.   6. Maintain replicate tables.    Types of PL/SQL Triggers ­                                                        1) Row level trigger ­ An event is triggered for each row updated, inserted or deleted.   2) Statement level trigger ­ An event is triggered for each sql statement executed.  3) Instead of Trigger ‐    Syntax for Creating a Trigger ­>  CREATE [OR REPLACE ] TRIGGER trigger_name   {BEFORE | AFTER | INSTEAD OF }   {INSERT [OR] | UPDATE [OR] | DELETE}  [OF col_name] ON table_name   [REFERENCING OLD AS o NEW AS n]   [FOR EACH ROW]   WHEN (condition)   BEGIN    ­­ sql statements   END;     • CREATE [OR REPLACE ] TRIGGER ­ Creates a trigger with the given name or overwrites an existing                                                                       trigger with the same name.     • {BEFORE | AFTER | INSTEAD OF } ­ Indicates at what time should the trigger get fired.                                                                 i.e., For Eg. Before or After updating a table.   ▪ INSTEAD OF is used to create a trigger on a view.   ▪ Before and After cannot be used to create a trigger on view.    • {INSERT [OR] | UPDATE [OR] | DELETE} ­ Determines the triggering event.                                                                           ­ More than one triggering events can be used together separated by OR keyword. The trigger gets fired at all the specified triggering event.     • [OF col_name] ­ This clause is used with update triggers. This clause is used when you want to trigger an                                event only when a specific column is updated.     • CREATE [OR REPLACE ] TRIGGER ­ This clause creates a trigger with the given name or overwrites an                                                                   existing trigger with the same name.     • [ON table_name] ­This clause identifies the name of the table or view to which the trigger is associated.    
  • 10. 12/10/2016 OneNote Online 10/11 • [REFERENCING OLD AS o NEW AS n] ­ This clause is used to reference the old and new values of the                                                                          data being changed.   ▪ By default, you reference the values as :old.column_name or :new.column_name.   ▪ The reference names can also be changed from old (or new) to any other user­defined name.   ▪ You can not reference old values when inserting a record, or new values when deleting a record, because they don't exist.     • [FOR EACH ROW] ­ This clause is used to determine whether a trigger must fire when each row gets                                           affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is executed (i.e. statement level Trigger).      • WHEN (condition) ­ This clause is valid only for row level triggers. The trigger is fired only for rows that                                          satisfy the condition specified.                1) BEFORE statement trigger fires first.  2) Next BEFORE row level trigger fires, once for each row affected.   3) Then AFTER row level trigger fires once for each affected row. This events will alternates between          BEFORE and AFTER row level triggers.  4) Finally the AFTER statement level trigger fires.    How To know Information about Triggers.  We can use the data dictionary view 'USER_TRIGGERS' to obtain information about any trigger.      CYCLIC CASCADING in a TRIGGER ­>                                                                   This is an undesirable situation where more than one trigger enter            into an infinite loop. while creating a trigger we should ensure the such a situation does not exist.   • The below example shows how Trigger's can enter into cyclic cascading.  Let's consider we have two tables 'abc' and 'xyz'. Two triggers are created.  1)  The INSERT Trigger, triggerA on table 'abc' issues an UPDATE on table 'xyz'.  2) The UPDATE Trigger, triggerB on table 'xyz' issues an INSERT on table 'abc'.      In such a situa�on, when there is a row inserted in table 'abc', trigger A fires and will update table 'xyz'.        When the table 'xyz' is updated, triggerB fires and will insert a row in table 'abc'.       This cyclic situa�on con�nues and will enter into a infinite loop, which will crash the database    Trigger Limita�ons ‐>  1. Triggers cannot contain the COMMIT, ROLLBACK, and SAVEPOINT statements.   2. Trigger body – cannot  exceed 32K in size.   3. No limit on the number of triggers defined for a DML statement for a table.  In fact, you can define two triggers of the same type for a table. When this occurs, the triggers of the same type fire sequen�ally.    Facts About Triggers ‐>  Triggers:  • are named PL/SQL blocks with declara�ve, executable, and excep�on handling sec�ons.    • are stand‐alone database objects – they are not stored as part of a package and cannot be local to a block.    • do not accept arguments.        Excep�on Handling ‐>                          PL/SQL provides a feature to handle the Excep�ons which occur in a PL/SQL Block known as excep�on Handling. Using Excep�on Handling we can test the code and avoid it from exi�ng abruptly.    The following hierarchy is followed when a trigger is fired. PL/SQL Trigger Execution Hierarchy
  • 11. 11/11   DECLARE      <declarations section>   BEGIN      <executable command(s)>   EXCEPTION      <exception handling goes here >      WHEN exception1 THEN           exception1­handling­statements       WHEN exception2  THEN          exception2­handling­statements       ........      WHEN others THEN         exception2­handling­statements   END;    Predefined Excep�ons ‐>                                       An internal excep�on is raised implicitly whenever your PL/SQL program violates an Oracle rule or exceeds a system‐dependent limit.   ▪ Every Oracle error has a number, but excep�ons must be handled by name. So, PL/SQL predefines some common Oracle errors as excep�ons.   ▪ For example, PL/SQL raises the predefined excep�on NO_DATA_FOUND if a SELECT INTO statement returns no rows    User‐Defined Excep�ons ‐>                                            PL/SQL lets you define excep�ons of your own.  Syntax:  DECLARE      my‐excep�on EXCEPTION;  • Must be declared in declara�on sec.  • Must be raised explicitly by RAISE statements in execu�on sec.  • You cannot declare an excep�on twice in the same block.   • However, you can declare the same excep�on in two different blocks.  • Excep�ons cannot appear in assignment statements or SQL statements but variables can.    Advantages of Excep�ons  1. Can handle errors conveniently without the need to check code mul�ple �mes.  2. Error processing is not clearly separated from normal processing.  3. Excep�ons improve readability.      SYNTAX :•