Complex chains of IF, ELSIF and ELSE statements should be replaced by the more readable CASE one. A complex IF statement has either several ELSIF clauses, or both an ELSIF and an ELSE clause.


== Noncompliant Code Example

----
DECLARE
  x PLS_INTEGER := 0;
BEGIN
  IF x = 0 THEN                     -- Noncompliant
    DBMS_OUTPUT.PUT_LINE('x = 0');
  ELSIF x = 1 THEN
    DBMS_OUTPUT.PUT_LINE('x = 1');
  ELSIF x = 2 THEN
    DBMS_OUTPUT.PUT_LINE('x = 2');
  END IF;
END;
/

DECLARE
  x PLS_INTEGER := 0;
  y PLS_INTEGER := 0;
BEGIN
  IF x = 0 THEN                     -- Noncompliant
    DBMS_OUTPUT.PUT_LINE('x = 0, y = ?');
  ELSIF y = 1 THEN
    DBMS_OUTPUT.PUT_LINE('x != 0, y = 1');
  ELSE
    DBMS_OUTPUT.PUT_LINE('x != 0, y != 1');
  END IF;
END;
/
----


== Compliant Solution

----
DECLARE
  x PLS_INTEGER := 0;
BEGIN
  CASE x
    WHEN 0 THEN
      DBMS_OUTPUT.PUT_LINE('x = 0');
    WHEN 1 THEN
      DBMS_OUTPUT.PUT_LINE('x = 1');
    WHEN 2 THEN
      DBMS_OUTPUT.PUT_LINE('x = 2');
    ELSE
      -- Do not forget the ELSE to prevent ORA-06592
      NULL;
  END CASE;
END;
/

DECLARE
  x PLS_INTEGER := 0;
  y PLS_INTEGER := 0;
BEGIN
  CASE                              -- Compliant
    WHEN x = 0 THEN
      DBMS_OUTPUT.PUT_LINE('x = 0, y = ?');
    WHEN y = 1 THEN
      DBMS_OUTPUT.PUT_LINE('x != 0, y = 1');
    ELSE
      DBMS_OUTPUT.PUT_LINE('x != 0, y != 1');
  END CASE;
END;
/
----


ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
