Set A: Sample Output Table
Set A: Sample Output Table
1. Use a simple FOR loop to insert ten rows into a database table.
The values of a loop index, counter variable, and either of two
character strings are inserted. Which string is inserted depends
on the value of the loop index.
PL/SQL Block
-- available online in file 'sample1'
DECLARE
x NUMBER := 100;
BEGIN
FOR i IN 1..10 LOOP
IF MOD(i,2) = 0 THEN
-- i is even
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;
Character
--------i is odd
i is even
i is odd
i is even
i is odd
i is even
i is odd
i is even
i is odd
i is even
2. Use a cursor to select the five highest paid employees from the emp table.
Input Table
SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;
ENAME
EMPNO
SAL
---------- --------- -------KING
7839
5000
SCOTT
7788
3000
FORD
7902
3000
JONES
7566
2975
BLAKE
7698
2850
CLARK
7782
2450
ALLEN
7499
1600
TURNER
7844
1500
MILLER
7934
1300
WARD
7521
1250
MARTIN
7654
1250
ADAMS
7876
1100
JAMES
7900
950
SMITH
7369
800
PL/SQL Block
-- available online in file 'sample2'
DECLARE
CURSOR c1 is
SELECT ename, empno, sal FROM emp
ORDER BY sal DESC;
-- start with highest paid employee
my_ename VARCHAR2(10);
my_empno NUMBER(4);
my_sal
NUMBER(7,2);
BEGIN
OPEN c1;
FOR i IN 1..5 LOOP
FETCH c1 INTO my_ename, my_empno, my_sal;
EXIT WHEN c1%NOTFOUND; /* in case the number requested */
/* is more than the total
*/
/* number of employees
*/
INSERT INTO temp VALUES (my_sal, my_empno, my_ename);
COMMIT;
END LOOP;
CLOSE c1;
END;
Output Table
SQL> SELECT * FROM temp ORDER BY col1 DESC;
NUM_COL1 NUM_COL2
-------- -------5000
7839
3000
7902
CHAR_COL
-------KING
FORD
3000
2975
2850
7788
7566
7698
SCOTT
JONES
BLAKE
3. Write a program to sum all the odd number till 100 using for loop.
declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
for n in 1.. endvalue
loop
if mod(n,2)=1
then
sum1:=sum1+n;
end if
end loop;
dbms_output.put_line('sum = ' || sum1);
end;
DECLARE
no NUMBER (3) := &no;
a NUMBER (4);
b NUMBER (2);
BEGIN
FOR i IN 2..no - 1
LOOP
a := no MOD i;
IF a = 0
THEN
GOTO out;
END IF;
END LOOP;
<>
IF a = 1
THEN
DBMS_OUTPUT.PUT_LINE (no || ' is a prime number');
ELSE
DBMS_OUTPUT.PUT_LINE (no || ' is not a prime number');
END IF;
END;