Hi friends,today i will tell you about Control Structure in Pl/Sql.So first question come into mind is "what is Control Structure".So below is the answer-
'Control structure' enable us to specify the order in which the various instruction in a program are to be executed by the computer.In other word,the control structure determine the 'flow of control'in a program.There are three type of control structure in Pl/Sql namely:-ØBRANCHING
ØSELECTION
ØLOOPING
We will see one by one.
BRANCHING Statements in PL/SQL
The selection structure tests a condition, then executes one sequence of statements instead of another, depending on whether the condition is true or false. A condition is any variable or expression that returns a Boolean value (
TRUE
or FALSE
).
ØThere are two types of
Branching Statements :
ØCONDITIONAL
ØSIMPLE IF Statement
ØIF THEN ELSE Statement
ØIF ELSE IF Ladder Statement
ØNESTED IF Statement
ØUNCONDITIONAL
ØUNCONDITIONAL
ØGOTO Statement
ØThe GOTO statement
transfers control to a labeled block or statement.
ØRestrictions on GOTO
Statement :
ØGOTO statement cannot transfer
control into an IF statement, CASE statement, LOOP statement, or sub-block
I will give example of conditional branching in the form of code.I skip syntax of conditional
branching.
Simple if statement:-
Q1.A program for odd and even number
declare
num number:=#
begin
if mod(num,2)=0 then
dbms_output.put_line(num|| 'is even');
else
dbms_output.put_line(num|| 'is odd');
end if;
end;
/
if else if ladder statement
Q2.Find number is single or double or triple digit
declare
num number(10):=#
begin
if (num>=1 and num<=9) then
dbms_output.put_line('single digit number');
else if (num>=10 and num<=99) then
dbms_output.put_line('double digit number');
else if(num>=100 and num<=999) then
dbms_output.put_line('three digit number');
else
dbms_output.put_line('more than three digit number');
end if;
end;
/
Nested if statement
declare
age number(2):=&age;
gender char(1):='&gender' //in single quote due to character datatype
begin
if(gender='m' or gender='M') then
if(age>=21) then
dbms_output.put_line('he is valid for marries');
else
dbms_output.put_line('he is not valid for marries');
end if;
else if(gender='f' or gender='F') then
if(age>=18) then
dbms_output.put_line('he is valid for marries');
else
dbms_output.put_line('he is not valid for marries');
end if;
end if;
end;
/
GOTO statement:-
declare
num number:=&number //for taking number from user
begin
if mod(num,2)=0 then
goto l_even;
else
goto l_odd;
end if;
<<l_even>> //way to write goto level
dbms_output.put_line(num|| 'is a even number');
return;
<<l_odd>>
dbms_output.put_line(num|| 'is a odd number');
return;
end;
/
for more:PL/SQL control structures
Note:All these program compile on Oracle 10g.Before start to compile run following command
'set serveroutput on'.
No comments:
Post a Comment