IF - (PL/SQL Control Statements)
In PL/SQL, the IF statement is a control statement that allows you to execute a block of code conditionally.
Syntax
The basic syntax of the IF statement in PL/SQL is as follows:
IF condition THEN
statement/s;
ELSEIF condition THEN
statement/s;
ELSE
statement/s;
END IF;
Here, condition
is the expression that you want to test. If the condition is true, then the statement/s inside the block will be executed. If the condition is false, then the statements inside the ELSE block will be executed.
You can also use multiple ELSEIF
blocks to check additional conditions.
Example
Here is an example of using the IF statement in PL/SQL to check if a number is positive or negative:
DECLARE
num NUMBER(10) := -5;
BEGIN
IF num > 0 THEN
DBMS_OUTPUT.PUT_LINE(num || ' is positive.');
ELSEIF num < 0 THEN
DBMS_OUTPUT.PUT_LINE(num || ' is negative.');
ELSE
DBMS_OUTPUT.PUT_LINE(num || ' is zero.');
END IF;
END;
Output
The output of the above example would be:
-5 is negative.
Explanation
In the above example, we declare a variable num
and initialize it to the value -5
. We then use the IF statement to check if the number is positive or negative or zero. Since num
is negative, the second statement inside the IF block is executed, which prints out num
along with the string 'is negative' to the console.
Use
The IF statement is useful in situations where you need to execute a block of code conditionally based on certain criteria. For example, you may want to execute one block of code if a certain condition is true, and another block of code if the condition is false.
Important Points
- The IF statement is a control statement in PL/SQL that allows you to execute a block of code conditionally.
- It can be used with multiple
ELSEIF
blocks to check additional conditions. - The condition must be enclosed in parentheses.
- You can nest IF statements within one another to create more complex conditions.
Summary
In summary, the IF statement in PL/SQL is a useful control statement that allows you to execute a block of code conditionally based on a certain condition. It can be used with multiple ELSEIF
blocks to check additional conditions. The condition must be enclosed in parentheses and you can nest IF statements for more complex conditions.