Monday, October 5, 2015

plsql - IF-THEN, IF-THEN-ELSE,IF-THEN-ELSIF STATEMENT

IF - THEN

it is the simplest form of IF control statement, frequently used in decision making and changing the control flow of the program execution.

The IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition is FALSE or NULL, then the IF statement does nothing.

Syntax:
Syntax for IF-THEN statement is:

IF condition true THEN
{do this};

END IF;

sample code


declare
i number :=&i;
j number := &j;
k number :=&k;
begin

if i <=15 then
dbms_output.put_line ('value of i is ' ||i);
end if;
if j >= 20 and j <= 50 then
dbms_output.put_line ('value of i is ' ||j);
end if;
if k >= 50 and j <= 70 then
dbms_output.put_line ('value of i is ' ||j);
end if;
end;



IF-THEN-ELSE



A sequence of IF-THEN statements can be followed by an optional sequence of ELSE statements, which execute when the condition is FALSE.


Syntax for the IF-THEN-ELSE statement is:

IF condition THEN
   COND1;
ELSE
   COND2;
END IF;
Where, COND1 and COND2 are different sequence of statements. In the IF-THEN-ELSE statements, when the test condition is TRUE, the statement COND1 is executed and COND2 is skipped; when the test condition is FALSE, then COND1 is bypassed and statement COND2 is executed. For example:

IF color = red THEN
  dbms_output.put_line('You have chosen a red car')
ELSE
  dbms_output.put_line('Please choose a color for your car');
END IF;


Sample code

declare
i number :=&i;
j number := &j;
k number :=&k;
begin

if i <=15 then
dbms_output.put_line ('input value of i is with in limit of less than 15 :' ||i);
else
dbms_output.put_line ('input value of i is NOT with in limit of less than 15 :' ||i);
end if;
if j >= 20 and j <= 50 then
dbms_output.put_line ('input value of j is with in limit of (20 and 50) : ' ||j);
else
dbms_output.put_line ('input value of j is NOT with in limit of (20 and 50) :' ||j);
end if;
if k >= 50 and k <= 70 then
dbms_output.put_line ('input value of k is with in limit of (50 and 70) : ' ||k);
else
dbms_output.put_line ('input value of k is NOT with in limit of (50 and 70) : ' ||k);
end if;
end;



IF-THEN-ELSIF


The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-THEN statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets you add additional conditions.

When using IF-THEN-ELSIF statements there are few points to keep in mind.

sample code 

declare
i number :=&i;

begin

if i <=20 then
dbms_output.put_line ('value of i is less than 21');
elsif i between 21 and  50 then
dbms_output.put_line ('value of i is bt 20 - 50');
elsif i between 51 and  70 then
dbms_output.put_line ('value of i is bt 50 - 70');
else
dbms_output.put_line ('value of i is greater than 71');
end if;
end;

No comments :

Post a Comment