Expert

Q:

3-16.

No. The IF statement is the only native PL/SQL conditional syntax.

Q:

3-17.

There are two basic possibilities:

  • Use the SQL DECODE function inside a SELECT FROM dual (or other table with just one row). Here is a demonstration of the DECODE solution:

    eypBEGIN
       SELECT DECODE (friend_type,
                'B', 'BEST',
                'K', 'BACKSTABBING',
                'C', 'CLOSE',
                'L', 'LIKE A BROTHER',
                'ACQUAINTANCE')
         INTO friend_descrip
         FROM dual;
  • Structure the IF statement to look and act as much like a CASE statement as possible. Here is an example of an IF statement posing as a CASE statement:

    BEGIN
       IF    friend_type      =  'B'
          THEN friend_descrip =  'BEST'
            ;
       ELSIF friend_type      =  'K'
          THEN friend_descrip =  'BACKSTABBING'
            ;
       ELSIF friend_type      =  'C'
          THEN friend_descrip =  'CLOSE'
            ;
       ELSIF friend_type      =  'L'
          THEN friend_descrip =  'LIKE A BROTHER';
            ;
       ELSE                      'ACQUAINTANCE';
       END IF;

Q:

3-18.

Here is a function that implements an inline IF-ELSE statement, returning one of two strings:

CREATE OR REPLACE FUNCTION ifelse
   (bool_in IN BOOLEAN, tval_in IN VARCHAR2, fval_in IN VARCHAR2)
    RETURN VARCHAR2
IS
BEGIN
   IF bool_in
   THEN
      RETURN tval_in;
   ELSE
      RETURN fval_in;
   END IF;
END;
/

And here is an example of the ifelse function put to use:

BEGIN
   emp_status :=
       ifelse (
          hiredate > ADD_MONTHS (SYSDATE, -216),
          'TOO YOUNG',
          'OLD ENOUGH');

This example is equivalent to this code:

BEGIN
   IF hiredate > ADD_MONTHS (SYSDATE, -216)
   THEN
      emp_status := 'TOO YOUNG';
   ELSE
      emp_status := 'OLD ENOUGH';
   END IF;

If you like this technique (it comes in especially handy when you want ...

Get Oracle PL/SQL Programming: A Developer's Workbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.