Skip to Main Content
Oracle PL/SQL Programming: A Developer's Workbook
book

Oracle PL/SQL Programming: A Developer's Workbook

by Steven Feuerstein, Andrew Odewahn
May 2000
Intermediate to advanced content levelIntermediate to advanced
594 pages
11h 32m
English
O'Reilly Media, Inc.
Content preview from Oracle PL/SQL Programming: A Developer's Workbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Oracle Database 12c PL/SQL Programming

Oracle Database 12c PL/SQL Programming

Michael McLaughlin
Oracle PL/SQL for DBAs

Oracle PL/SQL for DBAs

Arup Nanda, Steven Feuerstein
Oracle PL/SQL For Dummies

Oracle PL/SQL For Dummies

Michael Rosenblum, Paul Dorsey

Publisher Resources

ISBN: 9781449324070Supplemental ContentErrata Page