Instruction IF (PL/SQL)

Utilisez l'instruction IF dans des contextes PL/SQL pour exécuter des instructions SQL sur la base de certains critères.

Les quatre formes de l'instruction IF sont les suivantes:
  • Si...then...End If
  • Si...then...ELSE ...End If
  • Si...then...IF ELSE ...End If
  • Si...then...ELSIF ...then...ELSE ...End If

Si...then...End If

La syntaxe de cette instruction est la suivante:
IF boolean-expression THEN
  statements
END IF;
Si...Les instructions THEN sont la forme la plus simple de IF. Les instructions entre THEN et END IF ne sont exécutées que si la condition a pour résultat TRUE. Dans l'exemple suivant, une instruction IF ...La déclaration THEN est utilisée pour tester et afficher les employés qui ont une commission.
DECLARE
    v_empno         emp.empno%TYPE;
    v_comm          emp.comm%TYPE;
    CURSOR emp_cursor IS SELECT empno, comm FROM emp;
BEGIN
    OPEN emp_cursor;
    DBMS_OUTPUT.PUT_LINE('EMPNO    COMM');
    DBMS_OUTPUT.PUT_LINE('-----    -------');
    LOOP
        FETCH emp_cursor INTO v_empno, v_comm;
        EXIT WHEN emp_cursor%NOTFOUND;
--
--  Test whether or not the employee gets a commission
--
        IF v_comm IS NOT NULL AND v_comm > 0 THEN
            DBMS_OUTPUT.PUT_LINE(v_empno || '  ' ||
            TO_CHAR(v_comm,'$99999.99'));
        END IF;
    END LOOP;
    CLOSE emp_cursor;
END;
Ce programme génère l'exemple de sortie suivant:
EMPNO    COMM
-----    ------- 
7499     $300.00 
7521     $500.00 
7654    $1400.00

Si...then...ELSE ...End If

La syntaxe de cette instruction est la suivante:
IF boolean-expression THEN
  statements
ELSE
  statements
END IF;
Si...then...Les instructions ELSE spécifient un autre ensemble d'instructions qui doivent être exécutées si la condition a pour résultat FALSE. Dans l'exemple suivant, l'exemple précédent est modifié de sorte qu'un IF ...then...L'instruction ELSE est utilisée pour afficher le texte Non-commission si un employé n'a pas de commission.
DECLARE
    v_empno         emp.empno%TYPE;
    v_comm          emp.comm%TYPE;
    CURSOR emp_cursor IS SELECT empno, comm FROM emp;
BEGIN
    OPEN emp_cursor;
    DBMS_OUTPUT.PUT_LINE('EMPNO    COMM');
    DBMS_OUTPUT.PUT_LINE('-----    -------');
    LOOP
        FETCH emp_cursor INTO v_empno, v_comm;
        EXIT WHEN emp_cursor%NOTFOUND;
--
--  Test whether or not the employee gets a commission
--
        IF v_comm IS NOT NULL AND v_comm > 0 THEN
            DBMS_OUTPUT.PUT_LINE(v_empno || '  ' ||
            TO_CHAR(v_comm,'$99999.99'));
        ELSE
            DBMS_OUTPUT.PUT_LINE(v_empno || '     ' || 'Non-commission');
        END IF;
    END LOOP;
    CLOSE emp_cursor;
END;
Ce programme génère l'exemple de sortie suivant:
EMPNO    COMM
-----    -------
7369     Non-commission
7499  $   300.00
7521  $   500.00
7566     Non-commission
7654  $  1400.00
7698     Non-commission
7782     Non-commission
7788     Non-commission
7839     Non-commission
7844     Non-commission
7876     Non-commission
7900     Non-commission
7902     Non-commission
7934     Non-commission

Si...then...IF ELSE ...End If

La syntaxe de cette instruction est la suivante:
IF boolean-expression THEN
  IF boolean-expression THEN
    statements
ELSE
  IF boolean-expression THEN
    statements
END IF;
Vous pouvez imbriquer des instructions IF de sorte que des instructions IF alternatives soient appelées, selon que les conditions d'une instruction IF externe ont pour résultat TRUE ou FALSE. Dans l'exemple suivant, l'instruction IF externe ...then...La déclaration ELSE vérifie si un employé a ou non une commission. L'intérieur de l'IF ...then...Les déclarations ELSE véri­tent ensuite si la rémunération totale de l'employé est supérieure ou inférieure à la moyenne de l'entreprise. Lorsque vous utilisez cette forme de l'instruction IF, vous imbriquez une instruction IF dans la partie ELSE d'une instruction IF externe. Vous avez donc besoin d'un END IF pour chaque IF imbriquée et d'un pour le IF parent ...ELSE. (Notez que la logique de ce programme peut être considérablement simplifiée en calculant la rémunération annuelle de chaque employé à l'aide d'une fonction NVL dans l'instruction SELECT de la déclaration du curseur ; cependant, le but de cet exemple est de montrer comment les instructions IF peuvent être utilisées.)
DECLARE
    v_empno         emp.empno%TYPE;
    v_sal           emp.sal%TYPE;
    v_comm          emp.comm%TYPE;
    v_avg           NUMBER(7,2);
    CURSOR emp_cursor IS SELECT empno, sal, comm FROM emp;
BEGIN
--
--  Calculate the average yearly compensation
--
    SELECT AVG((sal + NVL(comm,0)) * 24) INTO v_avg FROM emp;
    DBMS_OUTPUT.PUT_LINE('Average Yearly Compensation: ' ||
        TO_CHAR(v_avg,'$999,999.99'));
    OPEN emp_cursor;
    DBMS_OUTPUT.PUT_LINE('EMPNO    YEARLY COMP');
    DBMS_OUTPUT.PUT_LINE('-----    -----------');
    LOOP
        FETCH emp_cursor INTO v_empno, v_sal, v_comm;
        EXIT WHEN emp_cursor%NOTFOUND;
--
--  Test whether or not the employee gets a commission
--
        IF v_comm IS NOT NULL AND v_comm > 0 THEN
--
--  Test whether the employee's compensation with commission exceeds
--  the company average
--
            IF (v_sal + v_comm) * 24 > v_avg THEN
                DBMS_OUTPUT.PUT_LINE(v_empno || '  ' ||
                    TO_CHAR((v_sal + v_comm) * 24,'$999,999.99') ||
                    ' Exceeds Average');
            ELSE
                DBMS_OUTPUT.PUT_LINE(v_empno || '  ' ||
                    TO_CHAR((v_sal + v_comm) * 24,'$999,999.99') ||
                    ' Below Average');
            END IF;
        ELSE
--
--  Test whether the employee's compensation without commission exceeds
--  the company average
--
            IF v_sal * 24 > v_avg THEN
                DBMS_OUTPUT.PUT_LINE(v_empno || '  ' ||
                    TO_CHAR(v_sal * 24,'$999,999.99') || ' Exceeds Average');
            ELSE
                DBMS_OUTPUT.PUT_LINE(v_empno || '  ' ||
                    TO_CHAR(v_sal * 24,'$999,999.99') || ' Below Average');
            END IF;
        END IF;
    END LOOP;
    CLOSE emp_cursor;
END;
Ce programme génère l'exemple de sortie suivant:
Average Yearly Compensation: $  53,528.57
EMPNO    YEARLY COMP
-----    -----------
7369  $  19,200.00 Below Average
7499  $  45,600.00 Below Average
7521  $  42,000.00 Below Average
7566  $  71,400.00 Exceeds Average
7654  $  63,600.00 Exceeds Average
7698  $  68,400.00 Exceeds Average
7782  $  58,800.00 Exceeds Average
7788  $  72,000.00 Exceeds Average
7839  $ 120,000.00 Exceeds Average
7844  $  36,000.00 Below Average
7876  $  26,400.00 Below Average
7900  $  22,800.00 Below Average
7902  $  72,000.00 Exceeds Average
7934  $  31,200.00 Below Average

Si...then...ELSIF ...then...ELSE ...End If

La syntaxe de cette instruction est la suivante:
IF boolean-expression THEN
  statements
[ ELSIF boolean-expression THEN
  statements
[ ELSIF boolean-expression THEN
  statements ] ...]
[ ELSE
  statements ]
END IF;
Si...then...ELSIF ...Les instructions ELSE permettent de vérifier de nombreuses alternatives dans une seule instruction. Formellement, cette instruction est équivalente à l'instruction IF imbriquée ...then...ELSE ...Si...Instructions THEN, mais une seule instruction END IF est nécessaire. L'exemple suivant utilise une instruction IF ...then...ELSIF ...Déclaration ELSE pour compter le nombre d'employés par rémunération, par étapes de 25 000 $.
DECLARE
    v_empno         emp.empno%TYPE;
    v_comp          NUMBER(8,2);
    v_lt_25K        SMALLINT := 0;
    v_25K_50K       SMALLINT := 0;
    v_50K_75K       SMALLINT := 0;
    v_75K_100K      SMALLINT := 0;
    v_ge_100K       SMALLINT := 0;
    CURSOR emp_cursor IS SELECT empno, (sal + NVL(comm,0)) * 24 FROM emp;
BEGIN
    OPEN emp_cursor;
    LOOP
        FETCH emp_cursor INTO v_empno, v_comp;
        EXIT WHEN emp_cursor%NOTFOUND;
        IF v_comp < 25000 THEN
            v_lt_25K := v_lt_25K + 1;
        ELSIF v_comp < 50000 THEN
            v_25K_50K := v_25K_50K + 1;
        ELSIF v_comp < 75000 THEN
            v_50K_75K := v_50K_75K + 1;
        ELSIF v_comp < 100000 THEN
            v_75K_100K := v_75K_100K + 1;
        ELSE
            v_ge_100K := v_ge_100K + 1;
        END IF;
    END LOOP;
    CLOSE emp_cursor;
    DBMS_OUTPUT.PUT_LINE('Number of employees by yearly compensation');
    DBMS_OUTPUT.PUT_LINE('Less than 25,000 : ' || v_lt_25K);
    DBMS_OUTPUT.PUT_LINE('25,000 - 49,9999 : ' || v_25K_50K);
    DBMS_OUTPUT.PUT_LINE('50,000 - 74,9999 : ' || v_50K_75K);
    DBMS_OUTPUT.PUT_LINE('75,000 - 99,9999 : ' || v_75K_100K);
    DBMS_OUTPUT.PUT_LINE('100,000 and over : ' || v_ge_100K);
END;
Ce programme génère l'exemple de sortie suivant:
Number of employees by yearly compensation
Less than 25,000 : 2
25,000 - 49,9999 : 5
50,000 - 74,9999 : 6
75,000 - 99,9999 : 0
100,000 and over : 1