Control Flow in PL/SQL
Control Flow in PL/SQL
Examples
DECLARE
a NUMBER;
b NUMBER;
DECLARE
a NUMBER;
b NUMBER;
BEGIN
SELECT sum(sal), max(sal) INTO a,b FROM emp;
IF a < b THEN
dbms_output.put_line('Max is Higher');
ELSE
dbms_output.put_line('Sum is higher');
END IF;
END;
BEGIN
SELECT sum(sal), max(sal) INTO a,b FROM emp;
IF a < b THEN
dbms_output.put_line('Max is Higher');
ELSIF b < a THEN
dbms_output.put_line('Sum is higher');
ELSE
dbms_output.put_line('Both are equal');
END IF;
END;
PL/SQL Loops
n
LOOP
< loop_body
loop_body>
> /* A list of statements. */
END LOOP;
At least one of the statements in <loop_body
<loop_body>
>
should be an EXIT statement of the form
EXIT WHEN <condition>;
LOOP Example
n
DECLARE
i NUMBER := 1;
BEGIN
LOOP
INSERT INTO T1 VALUES(i,i
VALUES(i,i);
);
i := i+1;
EXIT WHEN i>100;
END LOOP;
END;
DECLARE
i NUMBER := 1;
BEGIN
LOOP
dbms_output.put_line('hi');
i := i+1;
EXIT WHEN i>100;
END LOOP;
END;
Here, <var
< var>
> can be any variable; it is local to the forfor- loop
and need not be declared. Also, <start> and <finish> are
constants.
Loop-forming statements
Example
DECLARE
i NUMBER := 1;
BEGIN
LOOP
dbms_output.put_line('hi');
i := i+1;
DECLARE
i NUMBER := 1;
BEGIN
WHILE i < 100 LOOP
dbms_output.put_line('hi');
i := i+1;
END LOOP;
END;
DECLARE
Here, <var
<var>
> can be any
variable; it is local to the
for--loop and need not be
for
declared. Also, <start>
and <finish> are
constants.
BEGIN
For i in 1..100 loop
dbms_output.put_line(i);
END LOOP;
END;
PL/SQL Cursors
Cursors
n
Example
A SIMPLE CURSOR
A SIMPLE CURSOR
Declare
cursor c1 is
select * from emp
emp;;
BEGIN
for emp_rec in c1 loop
dbms_output.put_line(emp_rec.ename);
dbms_output.put_line(emp_rec.ename
);
end loop;
END;
Declaration
salsum integer;
BEGIN
salsum := 0;
for emp_rec in c1 loop
salsum := salsum + emp_rec.sal
emp_rec.sal;;
end loop;
dbms_output.put_line('Salary sum: ' || salsum
salsum);
);
END;
Procedure created.