Oracle PLSQL Notes
Oracle PLSQL Notes
Normalization:-
In an application development cycle arrangement of data takes an
important role. This arrangement should be done by keeping all the
data and their activities in mind. This process is called normalization.
This normalization can be done by using the constraints which are
used to restrict the data to a particular extent and also by
establishing the relationship between two different data. There are
two types of constraints: -
1.Integrity constraints (To establish the data integrity in an object)
2.Referencial constraint (To establish relationship between the data
of more than one objects).
Maintenance of data in oracle database:-
Data can be maintained in the database by using some objects, which
are called database objects. There are 6 different objects in the
database: -
1.Table
2.View
3.Sequence
4.Index
5.Cluster
6.Synonym
But among all these the table is the main object and the rest of all
need the help of the table to function themselves.
Oracle is a software based on client-server technology where
database the server and though it can accessed by any number of
users each called the clients. So in order to login oracle we must
have to be connected with the database through any of the users.
There are 6 users, which will be created by default while installing
oracle. Those are
1.scott , 2.system, 3.Demo ,4.sys ,5.po8 6.dbsnmp
To store the data in the database first we have to create any of the
database objects.
There are 4 major components in oracle application which are
1.Sql 2.Pl/SQL 3.SQL*PLUS 4.Dev-2000
1.SQL: -
This is a non-procedural structure oriented language because it
follows some particular syntax. This is developed by E F Codd and
earlier known as SEQUEL.There 3 types of languages in SQL,which
are
E. Large objects:-
1.BLOB:-Binary large object
2.CLOB:-Character large object
3.NCLOB:-National character large object
Creating a table:-
A table can be created by using “create table” command as the
following syntax:-
syntax:-
create table <<tablename>>(field1 datatype(w),field2
datatype(w),...............,fieldn datatype(w) );
Ex:-
A. create table your_table(name varchar2(15),last_name
varchar2(12),
do_birth date,age number(3),address1 varchar2(20),address2
varchar2(20));
2.Update:-
Used to update a field or column with any value or based on the data
of another field from the same or different table.
syntax:-
update <<table name>> set <<field name>> = <<value/expr
>>,<<field2>>= <<value/expr,..........., where condition;
The where condition sholud be given while updating a particular row
otherwise that is not necessary.
Ex:-update student set sname=’eeee’ where rollno=105
2. update student set
tot=sub1+sub2+sub3,avr=sub1+sub2+sub3/3;
By using logical operators:-
The logical operators ‘and’ and ‘or’ can be used with the condition to
combine more than one conditions.
ex:-
3.Delete:-Used to delete a record or more than one records
temporarily from the table.
syntax:-delete from <<table name>> where <<condition>>;
ex:-
1.delete from student where rollno=104;
2. delete from student;
Data control language commands:-
A.select :-
used for retriving the datas from a database object e.g. tables.
syntax:-
1.select * from <<table name>>;
----selects all the datas from a table.
2.select field1,field2,field3,..... from <tablename>>;
----selects the datas from a table only with the mentioned fields.
ex:-
1.select * from emp;
2.select rno,sname,tot,avr from stud;
B.commit:-
used to save the changes permanently to an object.
syntax:-
commit;
C.rollback:-
used to get the changes cancel out since the last commit . It acts just
like undo.
syntax:-rollback;
D.savepoint:-
allows to create a private area by the user which is saved
temporarily by means of which the user can rollback the changes up
to that particular point.
syntax:-savepoint <<savepoint name>>
ex:-savepoint s1;
while rolback:-
rolback to <<savepoint name>>
ex:-rollback to s1;
Logical operators:-
While giving the conditions by using where clause if more than one
condition are required for a query then logical operators can be used.
Those are
1.and 2.or
Truth table:-
and:-
cond1 cond2 res
T T T
T F F
F T F
F F F
OR:-
T T T
T F T
F T T
F F F
Relational operators:-
a).IN:-Retrieves the data where the condition matches.
ex:-
1.SELECT * FROM EMP WHERE JOB IN ‘MANAGER’;
2.SELECT * FROM EMP WHERE DEPTNO IN (20,30);
NOT IN:-retrieves the row for which the condition does not match.
ex:- SELECT * FROM EMP WHERE JOB NOT IN (‘CLERK’,’MANAGER’);
b).BETWEEN:-Retrieves the data which lies in the range given by the
between operator.
ex:
1.SELECT * FROM EMP WHERE SAL BETWEEN 3000 AND 4000;
select * from emp where sal between 2000 and 3000;
not between(opp. of between).
ex:- SELECT * FROM EMP WHERE SAL NOT BETWEEN 3000 AND
5000;
ORDER BY CLAUSE:-
This is used to retrieve the data from a table in ascending or
descending order.
syntax:-Select * from <<table name>> order by <<fieldname>>
asc/desc;
ex:-select * from emp order by sal asc
ex:- select * from emp order by ename desc;
Where asc is used for ascending order and desc for descending order
. But the default order is ascending.
Distinct:-Used to retrieve only the distinct(not repeated) rows from a
table.
ex:-select distinct * from list;
CONSTRAINTS:-
Constraints are the clauses by using which the following features can
be added to a field of a table:-
1.preventing the insertion of duplicate rows into a column.
2.restricting the values with in a range.
3.Taking reference from one table to another table.
4.Not leaving a field as blank.
Basically Constraints are of two different types:-
a. Integrity constraints
b. Referential constraints
A. Integrity constraints:-
Droping a constraint:-
syntax:-Alter table <<table name>> drop constraint <<con name>>
cascade;
ex:- alter table employ drop constraint em_ck2 cascade;
ex2:-Alter table stud drop primary key;
Adding a constraint:-
syntax:-alter table <<tablename>> add constraint <<con name>>
con type(col name);
ex1:-Alter table stud add constraint st_pk1 primary key(rno);
ex2:- alter table employ add constraints em_ck2 check(sal between
800 and 5000);
Joining conditions:-
The procedure for combining more than one tables based upon a
common data which shares the primary and foreign key relationship
is called joining statements.
These are of 4 types:-
1.equijoin
2.outer join
3.selfjoin
4.Joining by using set operators.
Equijoin:-
Joining more than one table by basing upon a common field
having primary and foreign key relationship and by using a (=)
symbol is called equijoin.
ex:-
1.select empno,ename,job,sal,dname,loc from emp,dept where
emp.deptno=dept.deptno; (Only for selecting)
2. create table empjoin as select
empno,ename,job,sal,emp.deptno,dname,loc from emp,dept
where emp.deptno=dept.deptno; (To store the joined data in a table
called empjoin)
Outerjoin:-
In equijoin though we are selecting the data from dept table
but all the data are not being retrieved .So to avoid this we have to
use outer join. This is possible by using a (+) symbol with the
deficiency column in the joining condition.
ex:- select empno,ename,job,sal,emp.deptno, dept.deptno,
dname,loc from emp,dept where emp.deptno(+) =dept.deptno;
Selfjoin:-
If in a single table any column is referred from another column
then those two can be joined by using a joining condition which is
called the selfjoin.
ex:- select
m.empno,m.ename,m.job,m.mgr,e.empno,e.ename,e.job,e.mgr from
emp e,emp m where e.empno=m.mgr;
union all:-retrieves all the records from both the tables irrespective
of the repetition.
ex:-Select * from emp
union all
select * from employ1;
intersect:-
retrieves only the rows which are common to both the tables.
ex:-select * from emp
intersect
select * from employ1;
minus:-Retrieves only the rows from the first table except the rows
which are common to both.
ex:-
select * from emp
minus
select * from employ1;
sql queries:-
The statement which is associated with a select command is called a
query. Queries are of three types. Those are
1.simple query
2.Nested query
3.Single row sub query.
Simple query:-The statement used for selecting the rows from a table
with a single select statement only is called simple query.
ex:-
Select * from emp;
select * from dept; etc.
Nested query:-
If in a single query more than one select statements exist one inside
another then that is called a nested query. The maximum number of
select commands can be taken in a nested query is 255.
EX:- select * from emp where deptno=(select deptno from emp
where job=’PRESIDENT’)
ex-2:-select * from emp where sal>=(select avg(sal) from emp);
Select the details of the employees who are getting sal more than the
avg sal of the employees from the department where president is
working ?
ex:-select * from emp where sal>=(select avg(sal) from emp where
deptno=(select deptno from emp where job=’PRESIDENT’));
Select * from emp where sal>(select avg(sal) from emp where
deptno=(select deptno from emp where ename='SMITH'));
having clause:-
This can be used with a group by clause to compare the value of a
group function with any other values.
ex:-select job,max(sal) from emp group by job having
max(sal)>=5000;
select job,sum(sal) from emp group by job having sum(sal)>6000
Views:-
views are the logical windows to a table where data from one or
more than one tables can be stored and retrieved. Views are of two
types-
1.simple view
2.complex view
Sequences:-
Sequence is also a database object which generates the serial
numbers with a step or the same numbers. After creating a sequence
it can be attached to one or more than one tables for generate the
numbers as per the increment given.
syntax to create:-
create sequence <<sequence name>>
increment by <<number>>
start with <<number>>
minvalue <number>>
maxvalue <<number>>
cycle/nocycle
cache <<no>> /nocache;
ex:-
create sequence s5
increment by 2
start with 1
maxvalue 20;
sequence parameters:-
To generate the numbers for a field the sequence should be attached
to a table’s column by using the following parameters.
1.nextval:-It generates the next value of the sequence as per the
increment given.
2.currval:-It generates the current value of the sequence irrespective
of the increment.
attaching a seq to a column:-
The seq. generates the numbers in the insert statements .while
inserting it does not ask for the value of that column and it takes the
value automatically from the seq.
syntax:-
insert into <<table name>>
values(<<seq.name>>.parameter,&field2,&field3,.....);
ex:-
1.insert into stud values(s1.nextval,’&name’,&sub1,&sub2,&sub3);
2.insert into st1 values(s3.currval,’&name’,&sub1,&sub2,&sub3);
altering a asequence:-
Alter sequence <<seq name>> maxvalue <<number>>;
dropping a sequence:-
Drop sequence <<seq name>>;
Indexes:-
Index can be created on a column or on more than one columns
which is used to give the faster access to the user while retrieving
the rows with a query using a certain condition based on that
particular column where index is created. Index are of three types
1.simple index
2.multicolumn index
3.unique index
Sql functions:-
Functions are the instructions which are allready created and
initiates a particular action when
called.These are of 4 types
1.Character functions
2.Numeric functions
3.Date functions
4.Conversion functions
Character functions:-
1.lower:-Used to convert a string into lower case.
syntax:-lower(‘string’)
ex:-select lower(‘MICRO COMPUTERS’) from dual;
output:-micro computers
ex:-select ename,lower(ename) from emp;
note:-dual is oracles own table from where the datas not present in
any table can be retrived.
2.upper:-used to convert a string into upper case letters.
syntax:-upper(‘string’)
ex:-
a)select upper(‘micro computers’) from dual;
output:-MICRO COMPUTERS
b)select ename,lower(ename),upper(lower(ename)) from emp;
3.initcap:-used to conver a string into it’s first character as upper
case letter.
syntax:-initcap(‘string’/fieldname)
ex:-
select initcap(‘micro computer associates’) from dual;
output:-Micro Computer Associates
select ename,initcap(ename) from emp;
4.length:-used to find out the number of characters in a string.
syntax:-length(‘string’/fieldname)
ex:-select length(‘computer’) from dual;
output:-8
select ename,length(ename) from emp;
5.instr:-Used to find out the position of a particular character in a
string.
syntax:-instr(‘string’/field name,’char’);
ex:-select instr(‘computer’,’t’) fromdual;
output:-6
select ename,instr(ename,’s’) from emp;
6.substr:-displays only the number of characters given starting from
a particular position.
syntax:-substr(‘string’,start no(POS),no of char);
ex:-select substr(‘computer’,3,4)from dual;
output:-mput
7.translate:-Used to replace a character in the string with any other
char.
syntax:-translate(‘string’,’char1’,’char2’);
ex:-select translate(‘computer’,’m’,’r’) from dual;
output:-corputer
select ename,translate(ename,'ABC','XYZ') FROM EMP;
8.replace:-Used to replace a data with another.
syntax:-replace (fieldname,’old’,’new’)
ex:-select job,replace(job,’CLERK’,’JR. ASST.’) FROM EMP;
9.lpad:-Used to remove fill the leading blanks in a data from left.
syntax:-lpad(fieldname,nos.,’char’)
ex:-select job,lpad(job,10,’*’) from emp;
10.rpad:-used to fill the leading blanks in a char data from right.
syntax:-rpad(fieldname,nos.,’char’)
ex:- select job,rpad(job,12,’*’) from emp;
Ascii(american standard code for information interchange.
a->97,b->98,....,z->122
A->65,......,Z->90
0-48 ,9->57
11.ascii:-Used to display the ascii code of a char.
syntax:-ascii(‘char’);
ex:-select ascii(‘a’) from dual;
output:-97
12.chr:-displays the char for an ascii number.
syntax:-chr(num)
ex:-select chr(65) from dual;
output:-A
13.concat:-Used to add one string into another string’s end.
syntax:-concat(‘string1’,’string2’);
ex:-select concat(‘michel’,’jackson’) from dual;
select ename,job,concat(ename,job) from emp;
14.Soundex():-Used to select the data from a table for a particular
field for which it sounds as the data given.
Syntax:-where soundex(field)=soundex(data);
Ex 1:-select * from emp where soundex(job)=soundex(‘CLERC’);
Ex 2:-select * from emp where soundex(ename)=soundex(‘myler’);
15:-Ltrim:-To remove the space from a string from the left side.
Syntax:-ltrim(‘ string’);
SELECT 'The employee '||ename||ltrim(‘ is getting Rs.
‘)||sal||’ per month’ from emp;
Numeric functions:-
The functions dealing with numbers is called numeric
functions.Those are
1.mod:-used to find the reminder of a division.
syntax:-mod(num,divisor)
ex:-select mod(45,7) from dual;
day monday
d 1-7
dd date of the month
dy Day of the weak in 3 chars.(e.g sun,mon,…)
ddth date with the abbr. 2nd,5th,3rd
mon 3 letter format(jan,feb)
month full month
mm 1-12
hh time in 12 hours
hh24 time in 24 hours
mi minutes
ss seconds
am am/pm
a.m. am/pm with (.)
SQL*PLUS:-
This is the main software of oracle which checks and
keeps track on all the activities of oracle applications. It has some
commands which are:-
1.cl scr:-To clear the screen.
2.save:-To save a command in a file with the extension .sql
syntax:-
a)save filename
b)save filename replace:-To replace the content of a command file
with another command.
c)save file append :-To add another command to an already existing
command file.
3.@ /start:-To execute a command file.
Syntax:-@filename
4.edit:-Used to open a file in the notepad buffer.
Syntax:- edit filename
5.describe:-Used to describe the database structure of a table.
Syntax:-Desc tablename
6.quit/exit:-To close oracle sql*plus.
7.prompt:-To display any text on the screen.
Syntax:-prompt string
8.accept:-Used to accept a value for a variable .
syntax:-Accept varname prompt “Any text :” hide
ex:-
accept rollno number prompt “Enter the rollno :”
accept pawd char prompt “Enter password :” hide
9.define:-Used to display the value stored in a variable.
Syntax:-define variablename
Begin
execution part
<<input statements
arithmatical statements
output statements>>
exception handler section
end;
declaration sec:-In this section all the variables which is to be used
in a prog. should be declared as their types. And these variables are
called bind variables.
synt:-
var datatype(w);
ex:-rno number(3);
name varchar2(10); etc.
input statements:-
The statement required to enter the data to the variables is called in
put statement.
syntax:-
var:=&var name;
ex:-rno:=&rollno;
name:=’&name’; etc.
Arithmetical statements:-
Statements used for calculation
var:=var (o) var;
ex:-
sum:=no1+no2;
tot:=sub1+sub2+sub3;
set serveroutput on
declare
no1 number(3):=100;
• initialization of variables no2 number(3,1):=5.6; begin
dbms_output.put_line(‘First number=’||no1);
dbms_output.put_line(‘Second number=’||no2);
end;
• WAP to enter any two numbers and find out their sum, difference,
product, quotient and reminder.
set serveroutput on
declare
no1 number(5);
no2 number(5);
s number(5);
d number(5);
p number(8);
q number(7,2);
rem number(3);
begin
no1:=&number1;
no2:=&number2;
s:=no1+no2;
d:=no1-no2;
p:=no1*no2;
q:=no1/no2;
rem:=mod(no1,no2);
dbms_output.put_line(‘Sum=’||s);
dbms_output.put_line(‘Difference=’||d);
dbms_output.put_line(‘Product=’||p);
dbms_output.put_line(‘Quotient=’||q);
dbms_output.put_line(‘Reminder=’||rem);
end;
/
• WAP to find out the total and average of 3 sub marks for any
student.
set serveroutput on
declare
rno number(3);
sname varchar2(10);
sub1 number(2);
sub2 number(2);
sub3 number(2);
tot number(3);
avr number(5,2);
begin
rno:=&rollno;
sname:=’&stud_name’;
sub1:=&sub1;
sub2:=&sub2;
sub3:=&sub3;
tot:=sub1+sub2+sub3;
avr:=tot/3;
dbms_output.put_line(‘ ‘);
dbms_output.put_line(‘Roll no=’||rno);
dbms_output.put_line(‘Stud name=’||sname);
dbms_output.put_line(‘Sub1 marks=’||sub1);
dbms_output.put_line(‘Sub2 marks=’||sub2);
dbms_output.put_line(‘Sub3 marks=’||sub3);
dbms_output.put_line(‘Total marks=’||tot);
dbms_output.put_line(‘Average marks=’||avr);
end;
/
• WAP to accept the principal amount, rate and time period then
find the simple interest and also find the amount to be paid by the
bearer.
• wap to find out the area and circumference of a circle.
set serveroutput on
declare
pi number(5,3):=3.141;
rad number(5,2);
area number(7,2);
circum number(7,2);
begin
rad:=&radius;
area:=pi*rad*rad;
circum:=2*pi*rad;
dbms_output.put_line(‘Radius=’||rad||’Cms.’);
dbms_output.put_line(‘Area=’||area||’Sq. Cms.’);
dbms_output.put_line(‘Circumference=’||circum||’Cms.’);
end;
/
• WAP to enter any roll number and print the corresponding name
from emp table.
set serveroutput on
declare
x varchar2(10);
en varchar2(10);
s number(7,2);
begin
x:=’&job’;
select ename,sal,job into en,S,x from emp where job=x;
dbms_output.put_line(‘Job=’||x||’ ‘||’emp name=’||en||’
salary=’||s);
end;
/
IF ELSE STATEMENTS:-
Unlike other softwares in pl/sql also it’s possible to take decission by
using the keywords “if” and “else”.The keyword if is allways
associated with a condition and if the condition satisfies then the
statements following it executes.
syntax:-
if condition then
statements for true;
else
statements for false;
end if;
• WAp to enter any number and find out whether it’s positive or
negative or zero.
set serveroutput on
declare
num number(5);
begin
num:=&number;
if num>0 then
dbms_output.put_line(num||’ is positive’);
elsif num<0 then
dbms_output.put_line(num||’ is negative’);
else
dbms_output.put_line(num||’ is equal to zero’);
end if;
end;
• WAP to accept the monthly salary of any employee and the find
the bonus of 12% on annual salary if experience is more than 3
years and otherwise the bonus is Rs.1000.After all calculate the
total salary received by the employ on that month along with
the bonus amount.
Declare
Msal number(7,2):=&msal;
Annsal number(9,2);
Bonus number(7,2);
doj date:=’&date_of_join’;
Exp number(3);
Totsal number(9,2);
Begin
Exp:=months_between(sysdate,doj)/12;
Annsal:=msal*12;
If exp>3 then
Bonus:=annsal*12/100;
Else
Bonus:=1000;
End if;
Totsal:=msal+bonus;
Dbms_output.put_line(‘Annual salary=Rs.’||annsal);
Dbms_output.put_line(‘Experience=’||exp||’ years’);
Dbms_output.put_line(‘Bonus amount=Rs.’||bonus);
Dbms_output.put_line(‘Total salary drawn=Rs.’||totsal);
End;
/
Nested if-else:-
If one condition is written inside another condition then that is called
nested if-else.This is required when we need to combine more than
one conditions.
Syntax:-
if cond1 then
if cond 2 then
Statements
Else
statements
end if;
else
if cond3 then
statements
else
stements
end if;
end if;
• WAP to accept any number and check whether that is a multiple of
only 3 or only 5 or both 3 and 5 or none of them.
Declare
No number(4):=&no;
Begin
If mod(no,3)=0 then
If mod(no,5)=0 then
dbms_output.put_line(no||‘ is mutiple of both 3 and 5’);
else
dbms_output.put_line(no||‘ is mutiple of only 3’);
end if;
else
if mod(no,5)=0 then
dbms_output.put_line(no||‘ is mutiple of only 5’);
else
dbms_output.put_line(no||‘ is mutiple of none of 3 and 5’);
end if;
end if;
end;
/
declare
r number(3);
s1 number(2);
s2 number(2);
s3 number(2);
t number(3);
a number(5,2);
re varchar2(6);
d varchar2(8);
begin
r:=&rno;
select sub1,sub2,sub3 into s1,s2,s3 from stud where sno=r;
t:=s1+s2+s3;
a:=t/3;
if s1>=35 and s2>=35 and s3>=35 then
re:=’pass’;
else
re:=’fail’;
end if;
if re=’pass’ and a>=60 then
d:=’first’;
elsif re=’pass’ and a>=50 and a<60 then
d:=’second’;
elsif re=’pass’ and a>=35 and a<50 then
d:=’third’;
else
d:=’nill’;
end if;
update stud set tot=t,avr=a,res=re,div=d where sno=r;
end;
• wap to input any number and check wheather it’s even or odd.
set serveroutput on
declare
num number(4);
begin
num:=&number;
if mod(num,2)=0 then
dbms_output.put_line(num||’ is even’);
else
dbms_output.put_line(num||’ is odd’);
end if;
end;
declare
ch varchar2(1);
begin
ch:=’&char’;
if ch=’a’ or ch=’e’ or ch=’i’ or ch=’o’ or ch=’u’ OR ch=’A’ or ch=’E’ or
ch=’I’ or ch=’O’ or ch=’U’ then
dbms_output.put_line(ch ||’ is a vowel’);
else
dbms_output.put_line(ch|| ‘ is a consonant’);
end if;
end;
/
declare
cn number(3);
qty number(4);
pr number(7,2);
t number(8,2);
d number(6,2);
net number(8,2);
begin
cn:=&cust_number;
select cno,price,qtytaken into cn,pr,qty from cust where cno=cn;
t:=pr*qty;
if t>10000 then
d:=2.5*t/100;
else
d:=1.5*t/100;
end if;
net:=t-d;
update cust set tot=t,dis=d,billamt=net where cno=cn;
end;
/
Loops:-
Loops are used to repeate the execution of a statement for more than
once in a programme.
Those are generally of 4 types:-
1.simple loop
2.while loop
3.for loop
4.cursor for loop
Simple loop:-This loop starts the repetition according to initial value
given to the loop variable and continues till the exit statement
encounters it.
syntax:-
initialisation of loop variable x:=1; x:=10;
loop
statements;
increment/decrement; x:=x+1; x:=x-1;
(if <<condition x<=10/x>=1>> then
exit;)
end if;
((or))
exit when condition(x>10);
end loop;
declare
x number:=1;
d number:=3.5;
begin
loop
dbms_output.put_line (x);
x:=x+d;
if d=3.5 then
d:=4.5;
elsif d=4.5 then
d:=3.5;
end if;
exit when x>40;
end loop;
end;
/
--WAP to findout the reverse of a number and sum of the digits of a
number.
declare
n number(4);
r number(4);
s number(4):=0;
t number(4);
begin
n:=&number;
t:=n;
loop
r:=mod(n,10);
s:=s+r;
n:=floor(n/10);
exit when n=0;
end loop;
dbms_output.put_line(‘Sum of the digits of ‘||t||’ = ‘||s);
s:=0;
n:=t;
loop
r:=mod(t,10);
s:=s*10+r;
t:=floor(t/10);
exit when t=0;
end loop;
dbms_output.put_line(‘reverse of ‘||n||’ = ‘||s);
end;
/
For loop:-
syntax:-
for <<var>> in startno..endno
loop
statements;
end loop;
--WAP to print the numbers from 1 to 10 and print the numbers with
their type(i.e even or odd)
declare
n number(2);
t varchar2(5);
begin
dbms_output.put_line(‘Number’||’Type’);
for n in 1..10
loop
if mod(n,2)=0 then
t:=’even’;
else
t:=’odd’;
end if;
dbms_output.put_line(n||’ ‘||t);
end loop;
end;
/
--WAP to find out the sum of the squares upto any number starting
from 1.
sum=1*1+2*2+3*3+4*4+.....+n*n
declare
n number(5);
s number(5):=0;
i number(3);
begin
n:=&number;
for i in 1..n
loop
s:=s+(i*i);
end loop;
dbms_output.put_line(‘The sum of the series=’||s);
end;
/
Armstrong numbers:-
Sum of the cubes of the digits of the number=num
153=1*1*1+5*5*5+3*3*3=>1+125+27
set serveroutput on
declare
n number(5);
s number(6):=0;
r number(2);
n1 number(4);
begin
n:=&number;
n1:=n;
loop
exit when n1<1;
r:=mod(n1,10);
s:=s+power(r,3);
n1:=floor(n1/10);
end loop;
if s=n then
dbms_output.put_line(n||’is armstrong’);
else
dbms_output.put_line(n||’is not armstrong’);
end if;
end;
Cursors:-
It’s an area where data can be selected and accessed either by
oracle or the user. There two types of cursors:-
1.implicit cursor:-The cursor which is created by the oracle buffer
automatically where any dml statements encounters to a table.
2.Explicit cursor:-this is the users private area Where data can be
collected from a table and can be accessed.
A cursor supports 3 attributes to work with it. Those are:-
1.sql%found:-Returns a true value if the cursor retrieves any rows
from the table.
2.sql%notfound:-Returns a true value if the cursor does not find any
value in the query.
3.sql%rowcount:-Counts the number of rows retrieved by the query.
--wap to delete the data for employees after entering the job.
declare
no number(3);
begin
delete from employ where job=’&job’;
if sql%notfound then
dbms_output.put_line(‘There is no employee doing this job’);
elsif sql%found then
dbms_output.put_line(‘Some data has been retrieved by the cursor’);
end if;
no:=sql%rowcount;
dbms_output.put_line(‘No of records deleted=’||no);
end;
/
set serveroutput on
declare
x number(4);
begin
update emp set sal=sal+1000 where deptno=&deptno;
x:=sql%rowcount;
dbms_output.put_line(x||’ no. of row updated’);
end;
/
set serveroutput on
declare
x number(4);
begin
delete from emp where job=’&job’;
x:=sql%rowcount;
dbms_output.put_line(x||’ no. of row updated’);
end;
/
set serveroutput on
declare
x number(4);
begin
update emp set sal=sal+1000 where deptno=&dno;
if sql%found then
dbms_output.put_line(‘Some rows are retrived by the query’);
elsif sql%notfound then
dbms_output.put_line(‘query is not able to retrive any row’);
end if;
x:=sql%rowcount;
dbms_output.put_line(x||’ no. of row updated’);
end;
/
set serveroutput on
declare
x number(4);
m varchar2(30);
t char(6);
D NUMBER(3);
name varchar2(10) not null :=’ ‘;
begin
D:=&DNO;
name:=’&your_name’;
update employ set sal=sal+1000 where dno=D;
if sql%found then
dbms_output.put_line(‘Some rows are retrieved by the query’);
elsif sql%notfound then
dbms_output.put_line(‘query is not able to retrieve any row’);
end if;
x:=sql%rowcount;
dbms_output.put_line(x||’ no. of row updated’);
m:=concat(to_char(x),’ no of rows updated on ‘);
t:=to_char(sysdate,’hh24:mi’);
insert into cursor_ret values(m,to_date(sysdate),t,D,name);
end;
/
Explicit cursors:-This is the oracles private area which can be created
by the user. After the creation data from a database can be selected
into the cursor. There are 4 main parts in a cursor which are:-
(declaration of a cursor:-
cursor <<cur name>> is select <<field names>> from table name
<<cond>>;
ex:-cursor c1 is select empno,ename,sal from emp where deptno=10;
(opening a cursor:-
open <<cursor name>>;
ex:-open c1;
(fetching the data from the cursor to the bind variables:-
syntax:-fetch <<cursor name>> into <<variables>>;
ex:-fetch c1 into eno,name,salary;
(closing the cursor:-
close <<cur name>>;
ex:-close c1;
---WAP to insert the datas of the clerks from emp table to another
table .
clerk table:-
create table cl_table(empno number(4),ename varchar2(10),
sal number(8,2),job varchar2(10),deptno number(3));
declare
eno number(4);
name varchar2(10);
salary number(8,2);
dno number(3);
j varchar2(10);
cursor c1 is select empno,ename,sal,job,deptno from emp where
job=’principal’;
begin
open c1;
loop
fetch c1 into eno,name,salary,j,dno ;
exit when c1%notfound;
insert into cl_table values(eno,name,salary,j,dno);
end loop;
close c1;
end;
/
• WAP to calculate the total salary for each deptno of the emp table
and put those into another table.
declare
cursor c1 is select sub1,sub2,sub3,sno from stud;
t number(3);
a number(5,2);
i number(3);
begin
for i in c1
loop
t:=i.sub1+i.sub2+i.sub3;
a:=t/3;
update stud set tot=t,avr=a where sno=i.sno;
end loop;
end;
/
Exceptions:-
If in a pl/sql programme any error encounters then the exceptions
are used to control and handle those.
The exceptions are of different types those are:-
1.when_no_data_found
2.Too_many_rows
3.Dup_val_on_index etc.
• WAP to accept any employee no. and insert the existing data
into another table. Write the exceptions such that if any error
encounters then the empno and a message should be inserted
to another table called error_tab.
declare
e number(6);
n varchar2(10);
s number(8,2);
d number(2);
j varchar2(10);
begin
e:=&empno;
select ename,job,sal,deptno into n,j,s,d from emp1 where empno=e;
insert into empl values(e,n,j,s,d);
exception
when too_many_rows then
insert into error_tab values(e,’There are more than one rec with
same no.’);
when no_data_found then
insert into error_tab values(e,’There are no rec with this no.’);
when value_error then
insert into error_tab values(e,’Width of the field exceeds the limit’);
end;
/
Note:-Value_error occurs if the width of a field exceeds while
entering the value.
declare
e number(4);
n varchar2(10);
s number(8,2);
d number(2);
j varchar2(10);
begin
e:=&empno;
select ename,job,sal,deptno into n,j,s,d from emp1 where empno=e;
insert into temp1 values(e,n,j,s,d);
end;
/
create table err_tab(eno number(4),err_type varchar2(20));
dup_val_on_index:-This error occurs when a duplicate value is
entered into a column having unique index or primary key.
• Wap to enter the data to dept table by using exception such that it
should not display any error if duplicate deptno is inserted.
set serveroutput on
declare
dno number(2);
name varchar2(10);
l varchar2(10);
begin
dno:=&deptno;
name:=’&dname’;
l:=’&location’;
insert into dept values(dno,name,l);
exception
when dup_val_on_index then
insert into error_tab values(dno,’Record already exist’);
dbms_output.put_line(‘Record allready exist’);
end;
/
declare
no number(3):=&rollno;
sname varchar2(10):=’&name’;
s1 number(3):=&sub1;
s2 number(3):=&sub2;
s3 number(3):=&sub3;
xyz exception;
begin
if s1>=100 or s2>=100 or s3>=100 then
raise xyz;
else
insert into stud values(no,sname,s1,s2,s3);
end if;
exception
when xyz then
dbms_output.put_line(‘Sorry ,U can not enter marks more than
100’);
insert into error_tab values(no,’Sorry mark can not be greater than
100’);
end;
/
ex:-
drop table bank;
Attributes:-
By using the atributes the columns and rows can be declared by any
other columns or rows from an existing table.Attributes are of 2
types:-
1.column%type:-Declares a field as a column type from any oracle
table. This acts as the data type in the pl/sql blocks.
2.row%type:-designates the variable as a row type from any valid
oracle table.
• WAP to calculate hra,da,ta,pf,net for employees based on basic
sal.
WAP to select the datas of any employee from empl2 table and insert
it to another table called empl1.
drop table empl1;
create table empl1(eno number(4),ename varchar2(10), job
varchar2(10), sal number(8,2),dno number(2));
create table empl2 as select empno,ename,job,sal,deptno from emp;
declare
emp_rec empl2%rowtype;
x number(4);
begin
x:=&empno;
select * into emp_rec from empl2 where empno=x;
insert into empl1
values(emp_rec.empno,emp_rec.ename,emp_rec.job,emp_rec.sal,e
mp_rec.deptno);
end;
/
Procedures:-
Procedure is a pl/sql programme unit which will be stored
permanently if created once then they can be called by their names
several times when required.
syntax:-
create or replace procedure <<pro_name>>(argument lists) as/is
declaration of the variables.
begin
statements
end;
Functions:-
These are also the stored programme units which can be created and
called any where in any other programs . Generally the function
returns a value. Unlike procedures they can not be called individually
by using the execute command.
syntax:-
create or replace function name(arg1 dtype,arg2 dtype,...) return
dtype is/as
declaration of variables.
begin
statements
return var;
end;
declare
n number;
f number;
begin
n:=&numbe;
f:=funfact(n);
dbms_output.put_line(‘Factorial of ‘||n||’= ‘||f);
end;
/
• WAP to get the hiredate of an employee from the emp table and
print it.
declare
e number(4);
hire date;
begin
e:=&empno;
hire:=funhire(e);
dbms_output.put_line(‘The employee is hired on ‘||to_char(hire,’day
ddth month yyyy’) );
end;
/
PACKAGES:-
This is also a stored program unit which is a combination of more
than one procedures or functions.While calling the procedures and
function they should be written along with the package name.There
are two parts in a packege.
1.Package definition
2.Package body definition
1.Package definition:-
syntax:-
create or replace package <<package name>> as/is
procdure and function inclusion
end <<packagename>>;
/
2.Package body definition:-
create or replace package body <<pack body name>> as/is
procedure <<pro name1>> (arg1 dtype,arg2 dtype) is
procedure definition
.....................
..............
end <<pro_name1>>;
procedure <<pro name2>> (arg1 dtype,arg2 dtype) is
procedure definition
.....................
..............
end <<pro_name2>>;
create or replace package my_pack is procedure addpro(no1 in
number,no2 in number); procedure subpro(no1 in number,no2 in
number);
function profun(no1 in number,no2 in number) return number ;
function divfun(no1 in number,no2 in number) return number;
end my_pack;
/
exec my_pack.addpro(20,30)
exec my_pack.subpro(34,20) etc.
exec pack_me.adddata(102,’bbbb’)
exec pack_me.caldata(101,34,55,65)
exec pack_me.deldata(102)
Database triggers:-
Triggers are the stored program units which fires when a dml
statement encounters the table based on which it is created.The
triger always fires for each row in the table.Triggers are of two types
according to the time of firing.Those are
1.After insert or update or delete
2.Before insert or update or delete
Syntax:-
create or replace trigger <<trigg name>> after/before
insert or update or delete on <<table name>> for each row
declare
<<declaration section>>
begin
<<execution part>>
end;
drop table mess;
create table mess(mess varchar2(20),time varchar2(30));
Create a trigger to update the stock table when purchased and sold.
create or replace trigger sale_trig after insert on sales for each row
declare
q number(4);
begin
select qstock into q from stock where itemno=:new.itemno;
if q<:new.qsold then
raise_application_error(‘-20001’,’Insufficient stock’);
else
update stock set qstock=q-:new.qsold where itemno=:new.itemno;
end if;
end;
/