Tuesday, 15 December 2015

EXCEPTION HANDLING

In PL/SQL, Exceptions are errors at Runtime.

In PL/SQL Block, If any errors occured at compile time then Oracle will take care.
But Compiler could not find all errors at compile time like ZERO_DIVIDE, NO_DATA_FOUND, TOO_MANY_ROWS, VALUE_ERROR etc..

To Handle Exceptions the following syntax will follow in PL/SQL

DECLARE
--DECLARATION SECTION
BEGIN
--BUSINESS LOGIC
EXCEPTION
WHEN EXCEPTION_NAME THEN
--EXCEPTION SECTION
END

Example:

DECLARE
V_ENAME EMP.ENAME%TYPE;-- It is the Type Declaration of Ename in Emp table
BEGIN
SELECT ENAME INTO V_ENAME FROM EMP WHERE EMPNO=123;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NOT FOUND');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('UNKNOW EXCEPTION');
END;

Note: Here in the above section the NO_DATA_FOUND exception will handle at run time. If the error is not known then OTHERS exception type will handle. And it should be down of all exceptions otherwise compile time error occured.

1) THROWING ERROR BY USER

Using the RAISE statement user can raise the exception if required.

Example:

BEGIN
RAISE; -- OR RAISE NO_DATA_FOUND;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO_DATA_FOUND EXCEPTION');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('UNKNOW EXCEPTION');
END;

2) USER DEFINED EXCEPTION

In PL/SQL, User can create the Exception and can handle at run time as follows.

DECLARE
USER_EXCEPTION EXCEPTION;
BEGIN
RAISE USER_EXCEPTION;
EXCEPTION
WHEN USER_EXCEPTION THEN
DBMS_OUTPUT.PUT_LINE('USER_EXCEPTION');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('UNKNOW EXCEPTION');
END;

CURSORS

In PL/SQL, The Cursors are two types.

1) Implicit Cursors
2) Explicit Cursors

1) Implicit Cursors

To perform the DML operations (update, insert, delete) and select statement which returns one row, the Oracle internally using this type of cursors. User is unaware of this cursor operations.

Example:

BEGIN
    UPDATE EMP
    SET ENAME = 'BLAKE'
    WHERE ENAME LIKE 'B%';
    DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT);
END;

Note: Here the Cursor Attribute ROWCOUNT is used to get the count of rows effected by the update statement using SQL%ROWCOUNT.


2) Explicit Cursors

The Explicit cursors are declared by the user in the PL/SQL Block. The Cursors complete operations can controlled by the user.

For Example if the user want to get the Employee Table all records and want to display Emp Number and Name.
The following steps should follow
i) In Declaration Section Cursor should be declared
ii) If we want to get the Values, Cursor should open
iii) Loop should be started to get all the records from the cursor. Otherwise only one record will be fetched.
iv) using the FETCH keyword the values will be inserted into temporary variable.
v) By using EXIT statement we should control the loop repetetions.
vi) After completion of all operations, Need to close the cursor


Example:

DECLARE
    CURSOR C_EMP IS SELECT *FROM EMP;
    V_EMP C_EMP%ROWTYPE;
BEGIN
    OPEN C_EMP;
        LOOP
            FETCH C_EMP INTO V_EMP;
            EXIT WHEN C_EMP%NOTFOUND;
            DBMS_OUTPUT.PUT_LINE(V_EMP.EMPNO||': '||V_ENAME);
        END LOOP;
    CLOSE C_EMP;
END;

*CURSOR ATTRIBUTES
-----------------------
ROWCOUNT: To Get the Count of records (CursorName%ROWCOUNT)
ISOPEN: It will return Boolean type. If curson opened then true otherwise false (CursorName%ISOPEN)
FOUND: after fetch operation, If the record found then returns true. Otherwise false (CursorName%FOUND)
NOTFOUND: after fetch operation, If the record notfound then returns true. Otherwise false(CursorName%NOTFOUND)

ITERATIVE CONTROLS OR LOOPS

In PL/SQL, If we want to iterate the statements again and again based on the condition the following syntax will be used

1) SIMPLE LOOP
2) WHILE LOOP
3) FOR LOOP

1) SIMPLE LOOP

Creating simple loop is as follows

LOOP
 -- STATEMENTS
 EXIT WHEN <CONDITION>; -- WHEN CONDITION IS TRUE THEN LOOP WILL BE EXIT.
END LOOP;

Note: Like other programming language, In PL/SQL we don't use the Break statement. In Oracle 11g version the CONTINUE Statement is introduced.

2) WHILE LOOP

WHILE <CONDITION>  -- LOOP repeats untis the CONDITION becomes false
LOOP
--STATEMENT
CONTINUE WHEN <CONDITION1>; -- STOPS the current loop if CONDITION1 is true
EXIT WHEN <CONDITION2>; ---- WHEN CONDITION2 IS TRUE THEN LOOP WILL BE EXIT.

END LOOP;

3) FOR LOOP

i) FOR VAR IN 1 .. 10
LOOP
    -- LOOP REPEATS 10 TIMES. VAR VARIABLE STARTS FROM 1 AND INCREASED by 1 for each iteration.
END LOOP;

ii) FOR VAR IN REVERSE 1 .. 10
LOOP
    -- LOOP REPEATS 10 TIMES. VAR VARIABLE STARTS FROM 10 AND DECREASED by 1 for each iteration.
    EXIT WHEN <CONDITION>; -- If CONDITION is true then the loop will be stopped.
END LOOP;

iii)
FOR REC IN (SELECT EMPNO,ENAME FROM EMP) -- We can use the select statement in for Loop. It will get all the records
LOOP
DBMS_OUTPUT.PUT_LINE('EMPNO: '||REC.EMPNO||' '||'EMP NAME: '||REC.ENAME);
END LOOP;

CONDITIONAL CONTROLS

In PL/SQL, the conditional controls are

1) IF
2) CASE
3) GOTO AND LABEL

1) IF CONDITIONAL CONTROL

The IF syntax is as follows


i) Simple IF

IF <CONDITION>
    THEN   
    -- If Condition True Then This statements will be executed    
END IF;
   
ii) IF - ELSE

IF <CONDITION>
    THEN
    -- If Condition True Then This statement will be executed
ELSE
    -- If the above Condition false Then This statement will be executed
END IF;

iii) IF - ELSIF

IF <CONDITION1>
    THEN
    -- If Condition1 True Then This statement will be executed
ELSIF <CONDITION2>
    -- If Condition2 True Then This statement will be executed
END IF;

iv) IF - ELSIF - ELSE

IF <CONDITION1>
    THEN
    -- If Condition1 True Then This statement will be executed
ELSIF <CONDITION2>
    -- If Condition2 True Then This statement will be executed
ELSE
    -- If the above 2 Conditions false Then This statement will be executed
END IF;

v) NESTED IF

IF <CONDITION1>
    THEN   
    -- If Condition1 True Then This statements will be executed    
    IF <CONDITION2>
        THEN
        -- If Condition2 True Then This statements will be executed    
    END IF;
END IF;

Example:

DECLARE
V_NUM1 NUMBER:= 100;
V_NUM2 NUMBER:= 200;
BEGIN
    IF V_NUM1 > V_NUM2 THEN
        DBMS_OUTPUT.PUT_LINE('NUM1 IS BIGGER THAN NUM2');
    ELSE
        DBMS_OUTPUT.PUT_LINE('NUM2 IS BIGGER THAN NUM1');
    END IF;
END;

2) CASE

The Case syntax is as follows
 i)
 CASE V_VALUE
 WHEN VAL1 THEN
    -- IF V_VALUE = VAL1 THEN THIS STATEMENT WILL BE EXECUTED
 WHEN VAL2
    -- IF V_VALUE = VAL2 THEN THIS STATEMENT WILL BE EXECUTED
 ELSE
    -- OTHERWISE THIS STATEMENT WILL BE EXECUTED
 END CASE;

 ii)
 CASE
 WHEN VAL1= V_VALUE THEN
    -- If VAL1 = V_VALUE is true then this statement will be executed
 WHEN VAL2= V_VALUE THEN
    -- If VAL1 = V_VALUE is true then this statement will be executed
 ELSE
    -- OTHERWISE THIS STATEMENT WILL BE EXECUTED
 END CASE;

 Example:

 DECLARE
 V_VALUE NUMBER := 10;
 V_VAL1 NUMBER := 20;
 V_VAL2 NUMBER := 10;
 BEGIN
 CASE
 WHEN V_VALUE=V_VAL1 THEN
    DBMS_OUTPUT.PUT_LINE('V_VALUE = V_VAL1 IS TRUE');
 WHEN V_VALUE=V_VAL2 THEN
    DBMS_OUTPUT.PUT_LINE('V_VALUE = V_VAL2 IS TRUE');
 ELSE
    DBMS_OUTPUT.PUT_LINE('V_VALUE EQUAL VALUE VARIABLE NOT FOUND');
 END CASE;

 3) GOTO AND LABEL

 To declare the label in the PL/SQL block is as follows

 <<Label_Name>>

 That's it.

 If we want to go to the lable location just need to use the following statement

 GOTO Lable_name;

BASIC PL/SQL BLOCK

In Oracle PL/SQL, The Blocks are two types.

1) Anonymous Block
2) Named Block

For the above two blocks the structure is as follows

DECLARE
-- DECLARATION SECTION

BEGIN -- BEGINNING THE PL/SQL BLOCK
--MAIN LOGIC OR BUSINESS LOGIC
    BEGIN   
    --INNER BLOCK OR NESTED BLOCK
    END
EXCEPTION SECTION
--ERROR HANDLING SECTION

END -- END OF THE BLOCK

Note: In the above structure we have used -- (two hyphen symbols used to comment the line. For multiline commenting we need to use /*   */ )

1) ANONYMOUS BLOCK

In this block the PL/SQL block do not have name. So, The Oracle Engine could not store the Block for the future use.
In realtime environment we mostly do not use the anonymous blocks.
For testing the result manually (Not Recommended for testing We use debugging feature for testing)
or For one time operation we will use the anonymous blocks in PL/SQL.

Example for Anonymous Block:

SQL> SET SERVEROUTPUT ON;
The above statement will enable the console to show the result in commandline.

SQL>
DECLARE
NAME VARCHAR2(30) := 'KIRAN';
BEGIN
DBMS_OUTPUT.PUT_LINE('NAME IS: ' || NAME);
EXCEPTION WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('ERROR OCCURED IN THE PL/SQL BLOCK');
END;

2) NAMED BLOCK

As the name suggests the Named block has identified with a name in Oracle. To create the named block we use functions, Triggers, Procedures, Packages etc.
So, The named block have one name and it will be stored permanantly in oracle database. In future we can retrieve the block by identifying with the name
and change the logic.

Example for Named Block: Creating Function

SQL>
CREATE OR REPLACE FUNCTION SUM_FUN(P_NBR1 IN NUMBER,P_NBR2 IN NUMBER)
RETURN NUMBER
AS
V_SUM NUMBER(10);
BEGIN
V_SUM := P_NBR1 + P_NBR2;
RETURN V_SUM;
END;

SQL> SELECT SUM_FUN(10, 20) AS TWO_NUM_SUM FROM DUAL;

In the above select statement we are using the named block i.e Function with the name SUM_FUN by passing two input parameters 10 and 20.
So the result is 30 ( i.e 10 + 20)

Note: The named blocks i.e functions, procedures, packages and triggers will be discussed in future tutorials.

PL/SQL CONCEPTS


1) BASIC PL/SQL BLOCK
2) CONDITIONAL CONTROLS
3) ITERATIVE CONTROLS OR LOOPS
4) CURSORS
5) EXCEPTION HANDLING
6) TRIGGERS
7) FUNCTIONS
8) PROCEDURES
9) PACKAGES
10) DYNAMIC SQL
11) BULK COLLECT
12) FORALL
13) RECORDS
14) COLLECTIONS
15) ORACLE SUPPLIED PACKAGES