PL / SQL Cursor Aim: Queries
PL / SQL Cursor Aim: Queries
Aim:
To solve the following programs using cursor.
Queries:
SQL> create table emp (ename varchar2(15), empno varchar(25),sal
number(20));
Output
Table created.
SQL> select *from emp;
Output
ENAME EMPNO SAL
-------------------- ---------- ----------
kavitha 17 20000
deepa 8 15000
kala 15 15000
subha 9 15000
shobana 27 10000
Use a cursor to select the five highest paid employees from the following emp table:
SQL>set serveroutput on
SQL>DECLARE
2 CURSOR c1 IS SELECT * FROM emp ORDERBY sal DESC;
3 e_rec emp%rowtype;
4 BEGIN
5 FOR e_rec IN c1
6 LOOP
7 DBMS_OUTPUT.PUT_LINE('Number'|| ‘ ‘||e_rec.empno);
8 DBMS_OUTPUT.PUT_LINE('Name'|| ‘ ‘||e_rec.ename);
9 DBMS_OUTPUT.PUT_LINE('Salary'|| ‘ ‘||e_rec.sal);
10 EXIT WHEN c1%ROWCOUNT>=5;
11 END LOOP;
12 END;
13 /
Number: 17
Name: kavitha
Salary: 20000
Number: 8
Name: deepa
Salary: 15000
Number: 15
Name: kala
Salary: 15000
Number: 9
Name: subha
Salary: 15000
Number: 27
PREETHA.R
10MA05
1
Name: shobana
Salary: 10000
Create a table Item ( itemid, itemname, ordid, actualprice)
Declare a user defined exception called ‘zero-price’ on the item table when the following
situation occurs: Select the value of actualprice into a local variable for a particular
orderid and if the price of the item is zero, then raise this exception.
SQL>select * from item;
OUTPUT
IID INAME ORDID PRICE
---------------------------------------------------------------------
1 soap 11 50
2 choco 23 0
3 shampoo 12 90
4 ice cream 2 30
5 bag 34 250
SQL>commit;
Commit complete.
P42. Write PL/SQL script that traps an invalid data type value given and displays a
custom error message.
SQL> DECLARE
2 it item%ROWTYPE;
3 e1 EXCEPTION;
4 pr it.acprice%TYPE;
5 BEGIN
6 SELECT acprice INTO pr FROM item_ars where itemid='&itmid';
7 IF pr = 0 THEN
8 RAISE e1;
9 END IF;
10 EXCEPTION
11 WHEN no_data_found THEN
12 RAISE_APPLICATION_ERROR (-20001,'no data');
13 WHEN e1 THEN
14 RAISE_APPLICATION_ERROR (-20002,'the price is zero... we are sorry...:(');
15 END;
16 /
Enter value for itmid: 333
old 6: SELECT acprice INTO pr FROM item_ars where itemid='&itmid';
new 6: SELECT acprice INTO pr FROM item_ars where itemid='333';
DECLARE
*
ERROR at line 1:
ORA-20002: the price is zero... we are sorry...:(
ORA-06512: at line 14
PROGRAM BASED ON DATABASE INTERACTION
PREETHA.R
10MA05
2
1..Write PL/SQL SCRIPT to determine the salary of employee in the EMP table. If salary
>7500 give an increment of 15% , otherwise display the message NO INCREMENT . Get
the empno from the user.
SQL>DECLARE
2 Eno number(12);
3 Salry emp.sal%type
4 Begin
5 eno1:=&eno1;
6 select sal into salry from employee where eno=eno1;
7 if (salry>7500) then
8 salry:=salry+salry*0.15
9 DBMS_OUTPUT.PUT_LINE(salry);
10 Else
11 DBMS_OUTPUT.PUT_LINE(‘No increment’);
12 End if;
13 End
14 /
OUTPUT:
SQL> DECLARE