Syntax to write a sql program
Declare
<declaration stmts>
Begin
<executable stmts>
[exception <exceptional stmts>]----- optional
End;
PS:
For syntax:
For <var> in <start_num> .. <endnum> loop
<statement(s);>
End loop;
PS:
Reverse For syntax:
For <var> in reverse <start_num> .. <endnum> loop
<statement(s);>
End loop;
Other forms of if syntax are:
If <condition> then
<action(s);>
End if;
If <condition> then
<action(s);>
Else
<action(s);>
End if;
If <condition> then
<action(s);>
Elseif <condition> then
<action(s);>
else
<action(s);>
End if;
PS:
Loop syntax:
loop
<statement(s);>
Exit when <condition>;
End loop;
1) Write a PL/SQL code, EX_INVNO.SQL, block for
inverting a number using all forms of loops.
ANSWER:-
declare
n number(20):=123;
s number(13):=0;
d number(3):=1;
r number(3):=10;
begin
dbms_output.put_line('the number is :' || n);
while n>0 loop
d:=mod(n,10);
s:=(s*r)+d;
n:=n/r;
end loop;
dbms_output.put_line('inverted values' || s);
end;
/
OUTPUT:-
the number is:123
inverted value is:321
2) Write a PL/SQL code, EX_SUMNO.SQL that prints
the sum of ‘n’ natural numbers.
ANSWER:-
prompt enter number:
accept number n
declare
isum number(2):=0;
i number;
n number:=&n;
begin
for i in 1..n loop
isum:=isum+i;
end loop;
dbms_output.put_line('sum is ' || isum);
end;
OUTPUT:-
enter the number:7
sum is 28
3) Write a PL/SQL code, EX_AREA.SQL, of block to
calculate the area of the circle for the values of
radius varying from 3 to 7. Store the radius and the
corresponding values of calculated area in the table
AREA_VALUES.
ANSWER:-
set serveroutput on
declare
area number(5);
rad number(3);
pi number(4):=3.14;
begin
for rad in 3..7 loop
area:=pi*rad*rad;
dbms_output.put_line('area is' || area);
insert into area_values values(area,rad);
end loop;
end;
/
OUTPUT:-
area is :27
area is :48
area is :75
area is :108
area is :147
SQL>select * from area_values;
area rad
____ ____
27 3
48 4
75 5
108 6
147 7