Thursday, 6 December 2018

Case Statement

Case statement Like the IF statement, the CASE statement selects one sequence of statements to execute.  To select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions.

-----------------------------------------------
Simple Case
-----------------------------------------------

DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;
/

-----------------------------------------------
Searched CASE statement
-----------------------------------------------

The searched CASE statement has no selector and its WHEN clauses contain search conditions that give Boolean values.

DECLARE
   grade   CHAR (1) := UPPER (:grade);
BEGIN
   CASE
      WHEN grade = 'A'
      THEN
         DBMS_OUTPUT.PUT_LINE ('Excellent');
      WHEN grade = 'B'
      THEN
         DBMS_OUTPUT.PUT_LINE ('Very Good');
      WHEN grade = 'C'
      THEN
         DBMS_OUTPUT.PUT_LINE ('Good');
      WHEN grade = 'D'
      THEN
         DBMS_OUTPUT.PUT_LINE ('Fair');
      WHEN grade = 'F'
      THEN
         DBMS_OUTPUT.PUT_LINE ('Poor');
   END CASE;
EXCEPTION
   WHEN CASE_NOT_FOUND  ---USE CASE EXCEPTION TO AVOID ELSE CONDITION
   THEN
      DBMS_OUTPUT.put_line (grade || ' Grade does not exists');
      DBMS_OUTPUT.put_line ('Please Enter Valid Grade');
END;