2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-06-08 14:23:48 +02:00
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.
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-06-08 14:23:48 +02:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-06-08 14:23:48 +02:00
----
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;
/
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-06-08 14:23:48 +02:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-06-08 14:23:48 +02:00
----
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[]
2021-06-08 15:52:13 +02:00
'''
2021-06-08 14:23:48 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== duplicates: S2145
=== on 30 May 2013, 13:48:23 Fabrice Bellingard wrote:
This is originally a TOAD rule.
It could be improve to check only the first case which involves a single variable (because the gain in readability of the 2nd case is not really clear...).
2021-06-08 14:23:48 +02:00
endif::env-github,rspecator-view[]