Oracle plsql Notes

67
Database:- It’s a collection of organized data where the data will be stored in the form of rows and columns. Where each row is a called a record and each column is a field. In the database the data is stored in the objects, which are called the database objects. So first the objects should be created and in order to create an object the data is to be defined and that data should be defined in the form of columns and those are called fields. After defining the fields the rows or records can be inserted dynamically. Oracle:- Oracle is a package, which is developed by Sir E F Codd in 1969 and implemented by Oracle Corporation in 1971. But this has got the recognition of ANSI and ISO in 1979 and used as the most popular database application by the programmers. This is a ORDBMS (Object Relational DataBase Management System) where DBMS is a software by using which the data can be 1.Defined 2.Inserted 3.Stored 4.Accesed 5.Deleted etc. Oracle provides two additional features, which are 1.Relational:-This feature allows the user to establish a relationship between more than one database objects .The relation can be any of the following types. 1.One to One. 2.One to Many. 3.Many to One. 2.Object:- By using the objects a set of related data can be bundled and their features can be available to any database objects later on. This object concept supports three main features. Those are:- 1.Inheritance (Attaining property of one object to another) 2.Encapsulation:-(Wrapping up of different types of data into a single bundle.) 3.Polymorphisim (Using a data for more than one purpose) Normalization:- In an application development cycle arrangement of data takes an important role. This arrangement should be done by keeping all

description

it may usefull someone else like me

Transcript of Oracle plsql Notes

Page 1: Oracle  plsql Notes

Database:- It’s a collection of organized data where the data will be stored in the form of rows and columns. Where each row is a called a record and each column is a field. In the database the data is stored in the objects, which are called the database objects. So first the objects should be created and in order to create an object the data is to be defined and that data should be defined in the form of columns and those are called fields. After defining the fields the rows or records can be inserted dynamically.Oracle:-Oracle is a package, which is developed by Sir E F Codd in 1969 and implemented by Oracle Corporation in 1971. But this has got the recognition of ANSI and ISO in 1979 and used as the most popular database application by the programmers. This is a ORDBMS (Object Relational DataBase Management System) where DBMS is a software by using which the data can be1.Defined2.Inserted3.Stored4.Accesed5.Deleted etc.

Oracle provides two additional features, which are

1.Relational:-This feature allows the user to establish a relationship between more than one database objects .The relation can be any of the following types.1.One to One.2.One to Many.3.Many to One.

2.Object:- By using the objects a set of related data can be bundled and their features can be available to any database objects later on. This object concept supports three main features. Those are:-

1.Inheritance (Attaining property of one object to another)2.Encapsulation:-(Wrapping up of different types of data into a single bundle.)3.Polymorphisim (Using a data for more than one purpose)

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:-

Page 2: Oracle  plsql Notes

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.Table2.View3.Sequence4.Index5.Cluster6.SynonymBut 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 are1.scott , 2.system, 3.Demo ,4.sys ,5.po8 6.dbsnmpTo 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

1.Data definition lang:-Used to define the and remove the definition of data.There are 4 commands in this language having different purposes.1.create 2.drop 3.Alter 4.Truncate

2.Data manipulation lang:-Used to make any manipulation or changes over the existing data having 3 commands in it1.insert 2.update 3.Delete

3.Data/Transaction control language:-The commands in this language can further devided into two more parts.1.Non data base comands:-Not related to the database directly and those are1.select 2.commit 3.Rollback 4.savepoint2.Database commands:-Related directly to the database and those are1.grant 2.revokeIn addition to all these one more SQL command is there which does not undergo any of the commands.That is “rename”.

Page 3: Oracle  plsql Notes

While creating a table at first we have to define the fields each according to their datatypes.There are different types of data we use in our day to day life and oracle also provide some datatypes to deal with those data.A.Character data:-1.char(w):-This is a fixed length character data type where any character data upto 255 characters can be stored. The default width for a character data is 1.2.varchar2(w) :-This is a variable length character data type which can accept maximum 2000 characters into it.Ch varchar23.long:-This is also variable length character data type which can accept maximum 2gb data into it. This is generally used for storing large data like resumes, receipts etc. But only one long field is allowed per a table. B.Numeric data:-1.number(w):-This data type accept any numeric data upto 39 digits.If any decimal data is to be stored in a field of number data type that can be stored in the form of number(n,m). Where n is the total width for the field ,m for the decimal number and n-m for the whole part.2.smallint:-To store only whole numbers.3.float:-To store the floating point i.e. very large or very small values.C.Date data:-1.date:-Used to store any data data between 1st jan 4712 bc to 31st dec 4712 ad in the format ‘dd-mon-yy’ .D.Pictures and graphical data:-1.Raw:-Used to store the pricture data upto 256 character length.2.Long raw:-Used to store picture and graphical data of large size and stores upto 2gb .Only one long raw is allowed per a table.

E. Large objects:-1.BLOB:-Binary large object2.CLOB:-Character large object3.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. create table stud_01(rollno number(3),name varchar2(10),

Page 4: Oracle  plsql Notes

doj date,marks1 number(3),marks2 number(3),marks4 number(3));

Whenever oracle is installed it creates 4 tables by default. Those are1.emp 2.dept 3.salgrade 4.bonusNote:-1.A table name can be any name without a space and it should be

unique the current user. It does not allow any special symbols in it except the underscore ( _ ).

2.Every SQL commands should end with a semicolon.B.Alter:-Used to change the structure of a table created. It can be done in three ways.1.Adding new fields:-syntax:-alter table <<tab name>> add (f1 dtype(w),f2

dtype(w),.......);ex:-alter table stud add (tot number(3),avr number(5,2));2.Changing the width of existing fields:-Width of an existing field can be increased and also can be decreased if the table is empty.syntax:-alter table <<tab name>> modify (f1 dtype(new width),f2 dtype(new width));ex:-alter table stud modify(tot number(4),avr number(6,2));3.To drop a column:-syntax:-alter table <<tab name>> drop(col name);

C.Drop:-Used to remove the existence of a table in the database.syntax:-drop table <<tab name>>;ex:-drop table stud;

D.Truncate:-Used to delete all the records from a table permanently.syntax:-Truncate table <<tab name>>;ex:-truncate table stud;

B.Data manipulation commands:-

1.Insert:-Used to insert the records to an existing database table. This can be done in 4 different ways:-1.To insert all the values and for a single record:-syntax:-insert into <<tab name>> values(f1val,f2val,....,fn val);ex:-insert into stud values(101,’aaa’,45,66,78);2.To insert for a few columns but for one record:-syntax:-insert into <<tab name>> (f1,f2,f3,...) values(f1 val,f2 val,f3 val,...);ex:-a. insert into stud(rno,name,sub1,sub2,sub3)

Values(102,’aaa’,56,78,98);b. insert into

stud(name,sub1,sub2,sub3,rno)values(‘cccc’,89,55,65,103);3.For all the fields and more than one recs:-syntax:-insert into <<tab name>> values(&f1,&f2,&f3,....);ex:-insert into stud1 values(&rno,’&name’,&sub1,&sub2,&sub3);4.For few fields and more than one recs:-

Page 5: Oracle  plsql Notes

syntax:-insert into <<tab name>> (f1,f2,f3,...) values(&f1,&f2,&f3,...);ex:-insert into stud (rno,name) values(&rno,’&name’); To insert data from another table:-Data to a table can be inserted from another existing table if the structure of both are same.syntax:-insert into <<tab name>> select */field names from <<existing tab name>>;ex:-a.insert into stud(rno,name,sub1,sub2,sub3) select * from stud1;b.insert into stud(rno,name) select rno,name from stud1;

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=1052. 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;

Page 6: Oracle  plsql Notes

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 are1.and 2.orTruth table:-and:-cond1 cond2 res

T T TT F FF T FF F F

OR:-T T TT F TF T TF F F

FOR RES AND DIV:-

UPDATE STUD SET RES=’PASS’ WHERE SUB1>=35 AND SUB2>=35 AND SUB3>=35;UPDATE STUD SET RES=’FAIL’ WHERE SUB1<35 OR SUB2<35 OR SUB3<35;UPDATE STUD SET DIV=’FIRST’ WHERE RES=’PASS’ AND AVR>=60;UPDATE STUD SET DIV=’SECOND’ WHERE RES=’PASS’ AND AVR>=50 AND AVR<60;UPDATE STUD SET DIV=’THIRD’ WHERE RES=’PASS’ AND AVR>=35 AND AVR<50;

UPDATE STUD SET DIV=’NILL’ WHERE RES=’FAIL’;Q.

Page 7: Oracle  plsql Notes

CREATE A TABLE FOR EMPLOYEES WITH THE COLUMNS ENO,ENAME,BASIC, HRA,DA,TA,PF,NSAL THE CALCULATE HRA OF 12%,DA OF 28%,TA OF 600 AND PF OF 10% THEN CALCULATE THE NET SALARY.symbols and operators:-

symbols:-1. * :-stands for all.2. & :-Address operator used to refer the location of the variable or

the field.3.%:-Used for resembling the field values with a character.

operators:-1.unary(the operators deal with a single field)2.binary operator.3.comparisonal operators.Unary:-+,-(signs)2.binary opeartors:-the operators which deal with more than one

fields or variables.e.g.+(add),-(sub),*(mul),/(div)3.used for comparing the field values with any others.e.g. = (equal)> (greater than)< (Less than)>= (Greater than or equals)<=(Less than or equals) != (or) <> :-Not equals

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;

c).LIKE:-Retrieves the data by using the meta characters(start letter, end letter etc.).ex:-SELECT * FROM EMP WHERE JOB LIKE ‘A%’;2. SELECT * FROM EMP WHERE ENAME LIKE ‘%J__ES’;

3.SELECT * FROM EMP WHERE ENAME LIKE ‘%S’;

Page 8: Oracle  plsql Notes

NOT LIKE(Opp. to like)

select * from emp where ename not like ‘A%’;

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 ascex:- 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;

Retrieving the data based on an expression:-select * from table name where cname=&cname;----selects the records from a table for which the rno entered satisfies.ex:-select * from emp where empno=&empno;

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 constraintsb. Referential constraints

A. Integrity constraints:-

1.null:-allows to insert null values for a column which is a default property of a column. syntax:-column name dtype(w) null

ex:-create table con1(no number(3) NULL,name varchar2(10));

2.not null:-Does not allow to insert null values to a column. syntax:-column name dtype(w) not null Ex:- create table con1(no number(3) not null,name varchar2(10));

Page 9: Oracle  plsql Notes

3.primary key:-works as a not null constraint and also does not allow repeated values for a field .From the field to which primary key is associated, reference can be taken to other columns of the same or different table.Notes:-1.Only one primary key can be associated with a particular table.syntax:-column name dtype(w) constraints constr_name primary keyex:-rno number(3) constraints rno_c primary key.ex:- create table con1(no number(3) constraints pk1 primary key ,name varchar2(10));

4.unique:-This constraint designates a column as unique by means of which

1. null values can be inserted2. does not allow repeated values3. reference can be taken to other tables from the column to

which it is associated.4. More than once can be used in a single table.

syntax:-column name dtype(w) constraint constr_name unique 5. More than one unique keys are allowed in a table.

5.check:-By using this constraint a column value can be restricted to certain range by giving a condition.syntax:-column name dtype(w) constraints constr_name check(condition);create table tab1 (no number(5) constraints con_ck check(no between 100 and 1000),name varchar2(10) constraints con_ck1 check(name=upper(name) and name like ‘P%’));In the above table no value can be entered into no column which are less than 100 and greater than 1000 and also no lower case character can be entered for name and the name should start with the alphabet ‘P’. Create a table for transaction in the bank with the fields

accountno,ac holder’s name,bal,tr type,closing bal to calculate the closing bal as per the tr type.

6.references:-Used to refer a column of one table into another table or to another column in the same table.syntax:-<<col name>> dtype references <<table name>> (con name),ex:-eno number(3) references emp(empno),notes:-1.For the referred column of the parent table there should be a

primary key or a unique key.2.The values available with the parent column only can be inserted to the column which is the reference.3.The width of the reference column should be equal to the width of the parent column.

Page 10: Oracle  plsql Notes

create table stud(rno number(3) constraints stud_pk1 primary key ,name varchar2(10),doj date));create table stud1 (rno number(3) references stud(rno),sub1 number(3),sub2 number(3),sub3 number(3));create table stud2(rollno number(3) references stud(rno),res varchar2(4),div varchar2(6));7.foreign key:-Establishes a parent and children relationship between the tables by assigning a constraint name for that.syntax:-Constraints <<c name>> foreign key(ref col name) references <t name>(parent col name);Ex:-create table stud3(rollno number(3) constraints stud3_pk primary key,s1 number(3),s2 number(3),s3 number(3),constraints stud3_fk1 foreign key(rollno) references stud(rno) on delete cascade);

create table depT1(deptno number(2) constraints de_pk primary key,dname varchar2(10) constraints de_uq unique,loc varchar2(10));

create table emp1(empno number(4) constraints empk1 primary key,ename varchar2(10) constraints emck1 check(ename=upper(ename)),job varchar2(10), mgr number(4) constraints emfk1 foreign key(mgr) references emp1(empno),hiredate date default sysdate,sal number(7,2) constraints emck2 check(sal between 800 and 5000),comm number(4) null,deptno number(2),constraints emfk2 foreign key(deptno) references dept1(deptno));

create table employ(eno number(4),ename varchar2(10) constraint em_ck1 check(ename=upper(ename)),job varchar2(10),mgr number(4), constraints em_fk1 foreign key(mgr) references employ(eno),hiredate date default sysdate,sal number(7,2) constraints em_ck2 check(sal between 2000 and 10000),comm number(7,2) null,dno number(2), constraints em_fk2 foreign key(dno) references depart(dno),constraints em_pk1 primary key(eno));

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);

Page 11: Oracle  plsql Notes

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.equijoin2.outer join3.selfjoin4.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,deptwhere 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;

Alias for table:-If the name of a table is required as a subscription to identify

a column then with out writing the full name a single letter can be used for that which is called the alias.ex:-select e.ename,e.sal,e.empno,e.job,e.deptno,d.dname, d.loc from emp e,dept d where e.deptno=d.deptno;

Joining two tables by using set operators:-Tables can be joined by using the set operators if they have the same structure. The set operators are1.union

Page 12: Oracle  plsql Notes

2.union all3.intersection4.minusA={1,2,3,4,5,6}B={4,5,6,7,8}a u b={1,2,3,4,5,6,7,8}a ua b={1,2,3,4,5,6,4,5,6,7,8}a n b={4,5,6}a-b={1,2,3}b-a={7,8}

union:-Retrieves the unique records from the two tables by combining those two.ex:- select * from empunionselect * from employ1;

union all:-retrieves all the records from both the tables irrespective of the repetition.ex:-Select * from emp union allselect * from employ1;

intersect:-retrieves only the rows which are common to both the tables.ex:-select * from empintersect select * from employ1;

minus:-Retrieves only the rows from the first table except the rows which are common to both.ex:-select * from empminusselect * from employ1;

sql queries:-The statement which is associated with a select command is called a query. Queries are of three types. Those are1.simple query2.Nested query3.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.

Page 13: Oracle  plsql Notes

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'));

Single row subquery:-The queries which retrieves only a single row are called s.r.s.q. Generally these kind of query uses a function.ex:-select sum(sal) from emp;select avg(sal) from emp;

group by clause:-used to retrieve the records from a table group by a field.

ex:-select avg(sal),deptno from emp group by deptno;

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

Any/some and all operators:-Any/Some:-Retrieves the rows for which the condition satisfies as the subquery returns.ex:-select empno,ename,job,sal from emp where sal<=any/some(select sal from emp where job=’MANAGER’);Retrieves all the records from emp where the sal is less than or equal to any of the sal(min sal) from emp where deptno=10.ex:-all:-Retrieves the rows which satisfies for the maximum value of the subquery as per the condition.ex:-select * from emp where sal>=all(select sal from emp where job=”manager”);Retrieves all the rows from emp who gets sal more than the max sal of all the managers.

Views:-

Page 14: Oracle  plsql Notes

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 view2.complex view

1.simple view:-The view created from the datas of a single table is called a simple view. In a simple view if any changes made to either to the table or the view that affects both of those. From a single table more than one views and from a view also another view can be created.syntax:-Create or replace view <<view name>> as select field1,field2,..../ * from <<table name>>;ex:-1.create or replace view empview as select * from emp;2.create or replace view empview as select empno,ename,job,sal from emp;3.create or replace view empview(empname,empno, empdesig, empsal) as select ename,empno,job,sal from emp;4.create or replace view empview as select * from emp where deptno=10;

views with constraints:-If a view is created with a where condition, even then the rows

can be inserted to that view which violates the where clause. So to prevent this type of insertion the view can be created with the constraint which is with check option.syntax:-Create or replace view <<view name>> as select <<column names/ *>> from <<table name>> where <<condition>> with check option;ex:-create or replace view empv1 as select empno,ename, job,sal,deptno from emp where deptno=20 with check option;

Complex view/Join view:-The view which is based upon the data of more than one tables or views is called a complex view.syntax:-Create or replace view <<view name>> as select <<columns/ *>> from <<table1,table2,....>;ex:-create or replace view empv as select empno,ename ,job,sal,loc,dname from emp,dept where emp.deptno= dept.deptno;notes:-Into complex views data can not be inserted because it’s based upon more than one tables.

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>>

Page 15: Oracle  plsql Notes

increment by <<number>>start with <<number>>minvalue <number>>maxvalue <<number>>cycle/nocyclecache <<no>> /nocache;ex:- create sequence s5increment by 2start with 1maxvalue 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 types1.simple index2.multicolumn index3.unique index

1.Simple index:-Index based on a single field of a table.syntax:-create index <<index name>> on <<table name(column name)>>;ex:-create index idx01 on stud(sno);2.multicolumn Index:- based on more than one fields of a table. syntax:-create index <<index name>> on <<table name(field1,field2,…);

Page 16: Oracle  plsql Notes

Ex:- create index idx1 on emp(empno,mgr);3.unique index:-Unique index just behaves like an unique constraint for a column. It does not allow any repetition in the field values. If already any repeated value is existing for a column for that the unique index can not be created.syntax:-create unique index <<index name>> on <<table(columnname)>>;ex:-create unique index idx1 on stud(rno);Clusters:-This is a database object which stores some common data in a single space in the database based on a particular column which is called the cluster key. By using this unnecessary wastage of memory space can be avoided.S yntax:-Create cluster <<cluster name>> (clu_key datatype(width));ex:-create cluster personnel(deptno number(3));To use the cluster key in table we have to craete the table as follows:-1)create table emp(empno number(3) ,ename varchar2(10),job varchar2(10),deptno number(3))cluster personnel(deptno);2)create table dept(dname varchar2(10),deptno number(3))cluster personnel(deptno);note:-In order to insert rows into the cluster tables we have to create a cluster index likesyntax:-create index <<index name>> on cluster <<cluster name>>;ex:- create index cl_idx1 on cluster personnel;Now data can be inserted to the cluster tables e.g. to emp and dept.USERS:-select * from all_users;

This displays all the user lists existing.Select user from dual;

Displays the current user logged in.An user is nothing but a privileged member who can access to

the database. These are just like the accounts. Each users will have one ID and all the Ids are associated with a password to open the user account.A user can not be created in any other user except the system user unless until it has the DBA privilege .So in order to create a user at first we should go for the system user.Creating new users:-syntax:-Create user <<username>> identified by <<password>>;ex:-Create user maya identified by mehndi;

After creating the user they should have given functionality, which are called the privileges. The privileges can be granted or taken off from the user in a user which is having the DBA privilege only. Privileges are the rights, which are of two types.1.Database privileges.2.Object privileges.

Page 17: Oracle  plsql Notes

1.Database privileges :-The rights or privileges given to the user are called database privileges ,though they deal with the database. Those are1.connect2.Resource3.DBAThese privileges can be given by using the following data control language command:-1.Grant:-Used to grant any of the privileges to an user.syntax:-Grant <<privilege>> to <<username>>;ex:-Grant connect/resource/DBA to maya;1.connect:-Grants the power to be connected to the database for the user.2.Resource:-Grants the power to create any object in the newly created user.3.DBA:-Grants the data base administration privileges e.g the power to create user ,grant and revoke the privileges etc.All these are the commands that only can be given from the user which has the administration power e.g. system user.Notes:-Before creating the user or granting any privilege first we have to go for the system user.For that give the command:-connect system/managerAfter creating the user give the required privileges e.g. connect,

resource etclikegrant connect,resource to maya;Now the user maya will be able to create any database objects like tables, view etc in it.Revoke:-This command is used to take out or withdraw any privileges from the user.syntax:-Revoke <<privilege name>> from <<username>>;ex:-Revoke connect, resource from maya;

Object privileges:-The privileges which can be granted to an object is called an object privilege. Those are insert, update, select ,delete and all.syntax:-Grant insert/select/update/delete/all on <<object>> to <<user name>>;select * from user.object;SQL> show useruser is “MICRO”SQL> connectEnter user-name: scottEnter password: *****SQL> grant dba to scott;Grant succeeded.SQL> grant select on emp to micro;Grant succeeded.

Page 18: Oracle  plsql Notes

SQL> connect micro/mcaConnected.SQL> select * from scott.emp;Synonyms:-These are just a duplicate copy for the tables in the same or different users.If one table exist in scott user then a duplicate of that can be created in any other users by granting the object privillege to those.syntax:-create synonym <<synonym name>> for <<table name>>;ex:-Create synonym s_emp for scott.emp;

NOTES:-1).If any changes are made in the table that reflects in the synonym and vice versa.2).If any previllege is granted or revoked from the table then it affects to the synonym.3).In synonyms it’s not possible to take ony a few columns from the table.dropping synonym:drop synonym <<syn name>>;Creating public synonym:-

This is a synonym which can be created in the user where the host table is present and from that synonym data can be accessed in any user present in oracle.Syntax:-Create public synonym <<syn name>> for <<table name>>;

Sql functions:-Functions are the instructions which are allready created and initiates a particular action when called.These are of 4 types1.Character functions2.Numeric functions3.Date functions4.Conversion functionsCharacter functions:-1.lower:-Used to convert a string into lower case.syntax:-lower(‘string’)ex:-select lower(‘MICRO COMPUTERS’) from dual;output:-micro computersex:-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 COMPUTERSb)select ename,lower(ename),upper(lower(ename)) from emp;

Page 19: Oracle  plsql Notes

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 Associatesselect 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:-8select 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:-6select 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:-mput7.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:-corputerselect 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->122A->65,......,Z->900-48 ,9->5711.ascii:-Used to display the ascii code of a char.syntax:-ascii(‘char’);ex:-select ascii(‘a’) from dual;output:-9712.chr:-displays the char for an ascii number.syntax:-chr(num)ex:-select chr(65) from dual;output:-A

Page 20: Oracle  plsql Notes

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 are1.mod:-used to find the reminder of a division.syntax:-mod(num,divisor)ex:-select mod(45,7) from dual;

2.abs:-Returns the absolute value of a number.syntax:-Abs(num)ex:-select abs(-345) from dual;==>3453.power:-returns the power of a number raised to a number.syntax:-power(num,index)ex:-select power(3,4) from dual;==>814.sqrt:-Returns the sq. root of any number.syntax:-Sqrt(num)ex:-select sqrt(144) from dual;output:-125.round:-Returns the number after rounding off it upto certain

digits.syntax:-round(num, no of places to be rounded)ex:-select round(238.5678,2) from dual;==>238.576.trunc:-used to round off a number after cutting it to a certain

position.syntax:-trunc(num,no. of digits)ex:-select trunc(45.5678,2) from dual;==>45.567.sign:-used to display the sign of a number value that whether it’s

positive or negative.syntax:-sign(field/num)ex:-select sign(sal-4000) from emp;8.nvl:-Returns a value given for the null values while taking part in an operation.ex:-nvl(field,any value)

Page 21: Oracle  plsql Notes

syntax:-select sal,comm,sal+nvl(comm,0) from emp;9.uid:-Returns the user id number from the table.Ex:-select uid from dual;10.user:-Returns the current user name logged into the system.11. greatest():-Returns the greatest of a set of numbers.Syntax:-greatest(no1,no2,no3,….);Ex;-select greatest(24,56,43) from dual;12. Least() :-Returns the smallest of set of any numbers.Syntax:-least(no1,no2,no3,….);Ex:-select least(23,66,89,4) from dual;Ex:-select sub1,sub2,sub3,greatest(sub1,sub2,sub3) great,least(sub1,sub2,sub3) small from stud13.Floor:-Returns the integral part of a decimel number.syntax:-floor(no)ex:-select floor(23.56) from dual;output:-2314.ceil:-Returns the next whole of a decimal number.syntax:-ceil(no)ex:-select ceil(23.346) from dual;output:-24group numeric functions:-1.sum:-used to find out the sum of a field values.ex:-sum(field name)ex:-select sum(sal) from emp;2.avg:-returns the average of the field values.syntax:-avg(field name)ex:-select avg(sal) fromemp;3.max/min:-returns the min or max of the field values.syntax:-max/min(sal)ex:-select min(sal) from emp;select max(sal) from emp; etc.4.count():-Returns the number of data for each group.Syntax:-count(column name)Ex:-select count(empno) where job=manager;Ex 2:-select job,sum(sal),avg(sal),min(sal),max(sal),count(sal) from emp group by job;Date functions:-1.Sysdate:-Returns the current system date.ex:-select sysdate from dual;2.month_between:-Calculates the months between two dates.syntax:-months_between(date1,date2)ex:-select months_between(sysdate,hiredate) from emp;select months_between(‘15-jun-99’,’21-dec-99’) from dual;3.add_months:-Used to add any number of months in a date.syntax:-add_months(date,no of months)ex:-select sysdate,add_months(sysdate,10) from dual;4.next_day:-Returns the date for next appearance of the given day.syntax:-next_day(date,’day’)ex:-select sysdate,next_day(sysdate,5) from dual;select next_day(15-may-99’,’friday’) from dual;

Page 22: Oracle  plsql Notes

15th may is saturdayoutput:-21-may-995.last_day:-Returns the last day of the month.syntax:-last_day(date)ex:-select hiredate,last_day(hiredate) from emp;select last_day(sysdate) from dual;conversion function:-1.to_char: converts number or date to character format .syntax:-to_char(date/number,’format’)to_char(date,’date picture’)codesuse

day mondayd 1-7dd 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 monthmm 1-12

y last digit of the yearyy last two digitsyyy last three digyyyy full yearyear In character format like (two thousand two)

hh time in 12 hourshh24 time in 24 hoursmi minutesss secondsam am/pma.m. am/pm with (.)

ex:-select to_char(sysdate,’ddth month yyyy hh24:mi:ss’) from dual;select to_char(sysdate,’day ddth month yyyy’) from dual;select to_char(sysdate,’dd mm yy’)from dual;select to_char(sysdate,’mm - dd - yyyy’) from dual;Number formats:-Format Use99,999 Separates the thousands place with a comma.$9999 Displays the number with a leading dollar($) Symbol9999MI returns a (–) sign to the end if a negative number.RM Returns the number with roman format.ex:-select sal,to_char(sal,’$99,999’) from dual;

2.to_date:- converts the char value representing date into a date value according to the format specified. if the format is omitted form is dd-mon-yy.

Page 23: Oracle  plsql Notes

syntax:-to_date(‘char’,’fmt’) ex:-insert into emp(hiredate) values(to_date(‘11/11/2001’,’dd/mm/yyyy’));ex2:-insert into dd values(to_date(‘08-25-2002’,’mm-dd-yyyy’))3.Decode:-used to change the values for a certain field based upon another field of a table.syntax:-decode(field,’value of the field’,changed value with expr)ex:-select sal,job,decode(job,’MANAGER’,sal*1.5/100) from emp; >increases the sal by 1.5% for managers.

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 filenameb)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:[email protected]:-Used to open a file in the notepad buffer.Syntax:- edit filename5.describe:-Used to describe the database structure of a table.Syntax:-Desc tablename6.quit/exit:-To close oracle sql*plus.7.prompt:-To display any text on the screen.Syntax:-prompt string8.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 :” hide9.define:-Used to display the value stored in a variable.Syntax:-define variablename

10.column:-Used to get various effects with the columns of a table.Syntax:-column <<c name>> heading/format <<new heading /format>>Ex:-column empno heading enocolumn sal heading salary etc.column sal format ‘$9,999’column ename format a4column ename HEADING ‘EMPLOYEE|NAME’Concatenation operator:-

Page 24: Oracle  plsql Notes

Select ‘The employee ‘||ename ||’ is drawing Rs.’ ||sal||’ per month’ from emp;

11.Clear column:-To cancel the column commands.

12.Show:-Used to show various options likeuser,pagesize,linesize,underline. etcsyntax:-show <<options>>13.set:-used to set linesize,pagesize,numwidth etc.syntax:-set <<option>>set underline <<char>>set underline off/onset heading off/onset timing on/off :-Displays the time taken for the execution of a

command.Set time on/off :-Displays the current time as sql prompt.Set feedback off/on:-Does not display any feedback after the execution of the command.Set sqlprompt “text” :-To change the sql prompt to any text.14.Setting title for a table:-

Titles are of two types.

1.ttitle:-Stands for top title, a title which appears at the top of each page.2.btitle:-Stands for the bottom title, a title which appears at the bottom of each page.

These titles can be given in 3 alignments those are

1.left 2.right 3.centersyntax:-ttitle/btitle left/right/center “title”Some sql defined columns also can be used like Sql.pno :-For current pageSql.lno :-for current lineSql.user :-for the user name who is logged in currently.Ex:-1.TTITLE “EMPLOYEE REPORT”2.TTITLE LEFT “EMPLOYEE REPORT” CENTER “MICRO COMPUTERS” RIGHT “PAGE:” SQL.PNO15.Report header and footer:-Report header is a message which appear at the top of the report and report footer which appears at the end of the report.Syntax:-Rephead/repfoot “any message”Ex:- rephead center “ANNUAL REPORT-2001”repfoot center “END OF THE ANNUAL REPORT”ex:-ttitle left ‘Sathyam Infoways’ center ‘Employee Reports’ right

‘Page :’ sql.pno-skip 1 center ‘For Year –2001’16.Skip :-Used to move the control to any no of lines or a page

forwards.

Page 25: Oracle  plsql Notes

Syntax:-Skip page or skip <<no of lines>>

16.break:-used to break a particular column.syntax: break on <<cname>>17.clear:-used to clear the formats or column attributes applied to

the fields or tables.syntax:-clear columns/break/compute etc.18.compute:-Used to calculate the sum,avg,min,max of the field values at each breaks.Syntax:-compute <<opt>> of <<field>> on <<break column>>ex:-break on deptno skip pagecompute sum avg min max of sal on deptnoselect * from emp order by deptno;19.input:-Used to accept more than one SQL*PLUS commands as a single one and can be saved as a command file.Syntax:-Input Command 1Command 2…………..…………save filenameinputrephead “Employee Info.”ttitle “Data for 2002”break on deptno skip 1compute sum of sal on deptnoselect * from emp order by deptno;

PL/SQL(procedural language ext. to SQL):-Though It’s a procedural language it supports programming features. Features of pl/sql are:-1.Though it’s an extension to SQL it supports almost all SQL commands.2.It supports the programming feature by using which more than one statements can be combined together to perform a particular task.3.It allows the user to take decisions by using the if else statements.4.Any statements can be repeated in the execution by using the loops.5.It ‘s most important feature is it allows the user to create stored program units like procedures, functions, packages, triggers etc. which can be called at any moment it required.

Every plsql prog. is called the combination of statements or more than one blocks. Which can be written as the following syntax:-

Page 26: Oracle  plsql Notes

declaration section

Beginexecution part<<input statementsarithmatical statementsoutput statements>>exception handler sectionend;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 calculationvar:=var (o) var;ex:-sum:=no1+no2;tot:=sub1+sub2+sub3;

Note:-While assigning values to variable the “ : “ should be used before the assignment operator(=) e.g (:=).output statements:-

The statement used for getting the output .dbms_output.put_line(‘Any string’); -->to print the stringdbms_output.put_line(var name); --> to print the value in a variableex:-dbms_output.put_line(‘welcome to pl/sql’);dbms_output.put_line(‘roll no=’ || rno); etc.Note:-“ ||(concatenation) “ is used for combining two strings or values.set serveroutput on:-Used to make the output console open.--(used for comments) prg1:- WAP to print any statement.

set serveroutput onbegin

dbms_output.put_line(‘============================’);

Page 27: Oracle  plsql Notes

dbms_output.put_line(‘Wel come to Pl/sql programming’);dbms_output.put_line(‘============================’);end; WAP to print any two numbers

set serveroutput ondeclareno1 number(3):=100;

initialization of variables no2 number(3,1):=5.6; begindbms_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 ondeclareno1 number(5);no2 number(5);s number(5);d number(5);p number(8);q number(7,2);rem number(3);beginno1:=&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 ondeclarerno number(3);sname varchar2(10);sub1 number(2);sub2 number(2);sub3 number(2);

Page 28: Oracle  plsql Notes

tot number(3);avr number(5,2);beginrno:=&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 ondeclarepi number(5,3):=3.141;rad number(5,2);area number(7,2);circum number(7,2);beginrad:=&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 ondeclarex varchar2(10);en varchar2(10);s number(7,2);beginx:=’&job’;

Page 29: Oracle  plsql Notes

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 thenstatements for true;elsestatements for false;end if;

for more than one choice:-if cond1 thenstatements ;elsif cond 2 thenstatements;..elsestatements for false;end if;

wap to find out the greatest of any two numberssoln:-set serveroutput ondeclareno1 number(5);no2 number(5);beginno1:=&number1;no2:=&number2;if no1>=no2 thendbms_output.put_line(no1||’ is greatest’);elsedbms_output.put_line(no2||’ is greatest’);end if;end;

WAp to enter any number and find out whether it’s positive or negative or zero.

Page 30: Oracle  plsql Notes

set serveroutput ondeclarenum number(5);beginnum:=&number;if num>0 thendbms_output.put_line(num||’ is positive’);elsif num<0 thendbms_output.put_line(num||’ is negative’);elsedbms_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.

DeclareMsal number(7,2):=&msal;Annsal number(9,2);Bonus number(7,2);doj date:=’&date_of_join’;Exp number(3);Totsal number(9,2);BeginExp:=months_between(sysdate,doj)/12;Annsal:=msal*12;If exp>3 thenBonus:=annsal*12/100;ElseBonus:=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 thenStatements

Page 31: Oracle  plsql Notes

Elsestatementsend if;

elseif cond3 thenstatementselsestementsend 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.

DeclareNo number(4):=&no;BeginIf mod(no,3)=0 then

If mod(no,5)=0 thendbms_output.put_line(no||‘ is mutiple of both 3 and 5’);else

dbms_output.put_line(no||‘ is mutiple of only 3’);

end if;

elseif mod(no,5)=0 then

dbms_output.put_line(no||‘ is mutiple of only 5’);elsedbms_output.put_line(no||‘ is mutiple of none of 3 and 5’);end if;

end if;end;/

declarer number(3);s1 number(2);s2 number(2);s3 number(2);t number(3);a number(5,2);re varchar2(6);d varchar2(8);beginr:=&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

Page 32: Oracle  plsql Notes

re:=’pass’;elsere:=’fail’;end if;if re=’pass’ and a>=60 thend:=’first’;elsif re=’pass’ and a>=50 and a<60 thend:=’second’;elsif re=’pass’ and a>=35 and a<50 thend:=’third’;elsed:=’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 ondeclarenum number(4);beginnum:=&number;if mod(num,2)=0 then

dbms_output.put_line(num||’ is even’);elsedbms_output.put_line(num||’ is odd’);end if;end;

WAP to find out the greatest of any three numbers.set serveroutput ondeclareno1 number(4);no2 number(4);no3 number(4);beginno1:=&number1;no2:=&number2;no3:=&number3;if no1>no2 and no1>no3 thendbms_output.put_line(no1||’ is the greatest’);elsif no2>no3 and no2>no1 thendbms_output.put_line(no2||’ is the greatest’);elsedbms_output.put_line(no3|| ‘ is the greatest’);end if;end;/

Page 33: Oracle  plsql Notes

WAP to enter any number and check wheather it’s a multiple of 3 or 7 or both 3 and 7 or not of 3 or 7.set serveroutput ondeclarenum number(5);beginnum:=&number;

if mod(num,3)=0 and mod(num,7)=0 thendbms_output.put_line(num||’ is multiple of both 3 and 7’);elsif mod(num,3)=0 thendbms_output.put_line(num||’ is multiple of only 3’);elsif mod(num,7)=0 thendbms_output.put_line(num||’ is multiple of only 7’);elsedbms_output.put_line(num||’ is neither multiple of 3 nor of 7’);end if;end;/

WAP to enter any alphabet and check it wheather it’s a consonant or a vowel.

declarech varchar2(1);beginch:=’&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’ thendbms_output.put_line(ch ||’ is a vowel’);elsedbms_output.put_line(ch|| ‘ is a consonant’);end if;end;/

create table cust(cno number(3),itemname varchar2(10),price number(7,2),qtytaken number(4),tot number(8,2),dis number(6,2),billamt number(8,2));insert into cust (cno,itemname,price,qtytaken) values(&cno,’&itemname’,&price,&qtytaken); wap to findout tot ,dis and billamount in the above prg. where

dis=2.5% if tot>10000 otherwise dis=1.5%.

declarecn number(3);qty number(4);pr number(7,2);t number(8,2);d number(6,2);net number(8,2);

Page 34: Oracle  plsql Notes

begincn:=&cust_number;select cno,price,qtytaken into cn,pr,qty from cust where cno=cn;t:=pr*qty;if t>10000 thend:=2.5*t/100;elsed:=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 loop2.while loop3.for loop4.cursor for loopSimple 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;loopstatements;increment/decrement; x:=x+1; x:=x-1;(if <<condition x<=10/x>=1>> thenexit;) end if;((or))exit when condition(x>10);end loop;

WAP to to print a string for 10 times.set serveroutput ondeclarex number(2):=1;beginloopdbms_output.put_line(‘Welcome to loops’);x:=x+1;exit when x>10;end loop;end;/

Page 35: Oracle  plsql Notes

WAP to print the number 1 to 10 set serveroutput on declarex number(2); --x number(2):=10;beginx:=1;loopdbms_output.put_line(x);

x:=x+1; --x:=x-1;if x>10 then --if x<1 thenexit;end if;end loop;end;/

WAP to print the table of any numberdeclarex number(2):=1;n number(4);t number(5);beginn:=&number;loopt:=n*x;dbms_output.put_line(n||’*’||x||’=’||t);x:=x+1;exit when x>10;end loop;end;

/ WAP to print the numbers from 1 to 30 with alternate difference

of 3 and 4.1 4 8 11 15 18 22 25 29declarex number:=1;d number:=3;beginloopdbms_output.put_line(x);x:=x+d;if d=3 thend:=4;elsif d=4 then d:=3;end if;exit when x>30;end loop;end;

/ WAP to print 40 to 1 with an alternate difference of 3.5 and 4.5 in

decreasing order.

Page 36: Oracle  plsql Notes

declare x number:=1;d number:=3.5;beginloopdbms_output.put_line (x);x:=x+d;if d=3.5 thend:=4.5;elsif d=4.5 then d:=3.5;

end if;exit when x>40;end loop;end;

--WAP to findout the factorial of any number.declaren number(3);x number(2):=1;f number(5):=1;beginn:=&number;loopf:=f*x;x:=x+1;exit when x>n;end loop;dbms_output.put_line(‘Factorial of ‘||n||’ is=’||f);end;/

/--WAP to findout the reverse of a number and sum of the digits of a number.declaren number(4);r number(4);s number(4):=0;t number(4);beginn:=&number;t:=n;loopr:=mod(n,10);s:=s+r;n:=floor(n/10); exit when n=0;

Page 37: Oracle  plsql Notes

end loop;dbms_output.put_line(‘Sum of the digits of ‘||t||’ = ‘||s);s:=0;n:=t;loopr:=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..endnoloopstatements;end loop;

--WAP to print the numbers from 1 to 10 and print the numbers with their type(i.e even or odd)declaren number(2);t varchar2(5);begindbms_output.put_line(‘Number’||’Type’);for n in 1..10loopif mod(n,2)=0 thent:=’even’;elset:=’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

declaren number(5);s number(5):=0;i number(3);beginn:=&number;for i in 1..n

Page 38: Oracle  plsql Notes

loops:=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=num153=1*1*1+5*5*5+3*3*3=>1+125+27

set serveroutput ondeclaren number(5);s number(6):=0;r number(2);n1 number(4);beginn:=&number;n1:=n;loopexit when n1<1;r:=mod(n1,10); s:=s+power(r,3);n1:=floor(n1/10);end loop;if s=n thendbms_output.put_line(n||’is armstrong’);elsedbms_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.

declareno number(3);

Page 39: Oracle  plsql Notes

begindelete from employ where job=’&job’;if sql%notfound thendbms_output.put_line(‘There is no employee doing this job’);elsif sql%found thendbms_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;/

--WAP to increase the sal of employees by 1000 rs. for deptno=10;

set serveroutput ondeclarex number(4);beginupdate emp set sal=sal+1000 where deptno=&deptno;x:=sql%rowcount;dbms_output.put_line(x||’ no. of row updated’);end;/

set serveroutput ondeclarex number(4);begindelete from emp where job=’&job’;x:=sql%rowcount;dbms_output.put_line(x||’ no. of row updated’);end;/

set serveroutput ondeclarex number(4);beginupdate emp set sal=sal+1000 where deptno=&dno;if sql%found thendbms_output.put_line(‘Some rows are retrived by the query’);elsif sql%notfound thendbms_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;/

Page 40: Oracle  plsql Notes

--WAP to increase the salary for the employees of a particular department and enter the no of records updated,date,time,dept no and name of the person who increased the salary into another table called cursor_ret.

create table cursor_ret(mess varchar2(30),update_date date,time varchar2(10),deptno number(3),name varchar2(10));

set serveroutput ondeclarex number(4);m varchar2(30);t char(6);D NUMBER(3);name varchar2(10) not null :=’ ‘;beginD:=&DNO;name:=’&your_name’;update employ set sal=sal+1000 where dno=D;if sql%found thendbms_output.put_line(‘Some rows are retrieved by the query’);elsif sql%notfound thendbms_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;

Page 41: Oracle  plsql Notes

---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));

declareeno 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’;beginopen c1;loopfetch 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.

create table temptot( chcol varchar2(40),totsal number(9,2));set serveroutput ondeclaretot1 number(6):=0;tot2 number(6):=0;tot3 number(6):=0;d number(4);s number(6);cursor c1 is select sal,deptno from emp;beginopen c1;loopfetch c1 into s,d;exit when c1% notfound;if d=10 thentot1:=tot1+s;elsif d=20 thentot2:=tot2+s;elsif d=30 thentot3:=tot3+s;end if;

Page 42: Oracle  plsql Notes

end loop;dbms_output.put_line(‘Dept 10 total salary :’||tot1);dbms_output.put_line(‘Dept 20 total salary :’||tot2);dbms_output.put_line(‘Dept 30 total salary :’||tot3);insert into temptot(chcol,totsal)values(‘Dept 10 total salary :’,tot1);insert into temptot(chcol,totsal)values(‘Dept 20 total salary :’,tot2);insert into temptot(chcol,totsal)values(‘Dept 30 total salary :’,tot3);close c1;end;/

cursor for loops:-This is a kind of loop which executes the number of times till the cursor retrieves the last record of the table.syntax:-declaration of the cursorbeginfor var in <<cur_name>>loopstatementsend loop;

WAp to calculate the electricity bill for apseb with the conditions:-

if charged unit<=100 rate=1.35,mrent 100charged unit >100 rate=2.95,mrent 150charged unit >400 rate=4.5,mrent 200create table apseb(cno number(3),cname varchar2(5), pmr number(4),cmr number(4),cu number(4),total number(7,2),mrent number(3),netbill number(8,2)); insert the records:-insert into apseb(cno,cname,pmr,cmr) values(101,’aaa’,2360,3278);insert into apseb(cno,cname,pmr,cmr) values(102,’bbb’,256,421);insert into apseb(cno,cname,pmr,cmr) values(103,’ccc’,3160,3228);insert into apseb(cno,cname,pmr,cmr) values(104,’ddd’,360,1278);insert into apseb(cno,cname,pmr,cmr) values(105,’eee’,2010,2278);declare cursor c is select cno,pmr,cmr from apseb;cunit number(4);tamt number(7,2);mr number(3);bill number(8,2);beginfor i in c loopcunit:=i.cmr-i.pmr;if cunit<=100 thentamt:=1.35*cunit;mr:=100;elsif cunit>100 and cunit<=400 thentamt:=1.35*100+(cunit-100)*2.95;

Page 43: Oracle  plsql Notes

mr:=150;elsif cunit>400 thentamt:=100*1.35+300*2.95+(cunit-400)*4.5;mr:=200;end if;bill:=tamt+mr;update apseb set cu=cunit,total=tamt,mrent=mr,netbill=bill where

cno=i.cno;end loop;end;/

WAP to calculate tot and average of students for three subjects by using cursor for loop.

declarecursor c1 is select sub1,sub2,sub3,sno from stud;t number(3);a number(5,2);i number(3);beginfor i in c1loopt:=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_found2.Too_many_rows3.Dup_val_on_index etc.

1.too_many_rows:-This exception occurs if the select statement retrieves more than one rows when the user need only one.syntax:-exceptionwhen too_many_rows thenaction;

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.

Page 44: Oracle  plsql Notes

sql>create table error_tab(eno number(6),err_type varchar2(50));sql>create table empl as select empno,ename,job,sal,deptno from emp ;sql>truncate table empl;

declaree number(6);n varchar2(10);s number(8,2);d number(2);j varchar2(10);begine:=&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);exceptionwhen too_many_rows theninsert into error_tab values(e,’There are more than one rec with

same no.’);when no_data_found theninsert into error_tab values(e,’There are no rec with this no.’);when value_error theninsert 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.

declaree number(4);n varchar2(10);s number(8,2);d number(2);j varchar2(10);begine:=&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 ondeclaredno number(2);

Page 45: Oracle  plsql Notes

name varchar2(10);l varchar2(10);begindno:=&deptno;name:=’&dname’;l:=’&location’;insert into dept values(dno,name,l);exceptionwhen dup_val_on_index then

insert into error_tab values(dno,’Record already exist’);dbms_output.put_line(‘Record allready exist’);end;/

User defined exceptions:-These can be defined by the user in the declaration section and can be used in the plsql block.syntax:-declareexcep_name exception;begin..if cond thenraise <<exception name>>;end if;when <<exception name >> thenaction;.end;/

declareno number(3):=&rollno;sname varchar2(10):=’&name’;s1 number(3):=&sub1;s2 number(3):=&sub2;s3 number(3):=&sub3;xyz exception;beginif s1>=100 or s2>=100 or s3>=100 thenraise xyz;elseinsert into stud values(no,sname,s1,s2,s3);end if;exceptionwhen xyz thendbms_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’);

Page 46: Oracle  plsql Notes

end;/

ex:-drop table bank;

create table bank(acno number(3),ahname varchar2(10),pbal number(7,2),dep number(7,2),wit number(7,2),cbal number(7,2));declareano number(3);name varchar2(10);b number(7,2);d number(7,2);w number(7,2);my_exp exception;beginano:=&accno;name:=’&ahname’;b:=&bal;d:=&dep_amt;w :=&wit_amt;insert into bank values(ano,name,b,d,w,0);if (b+d)<w thenraise my_exp;elseupdate bank set cbal=(b+d)-w where acno=ano;end if;exceptionwhen my_exp theninsert into err_tab values(ano,’insufficient balance’);end;/

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.

Page 47: Oracle  plsql Notes

drop table empl;create table empl(eno number(3),ename varchar2(10),sal number(7,2),hra number(5,2),da number(6,2),ta number(6,2),pf number(5,2),net number(8,2));insert into empl (eno,ename,sal) values (101,’aaa’,5000); insert into empl (eno,ename,sal) values (102,’bbb’,3500); insert into empl (eno,ename,sal) values (103,’ccc’,6500); insert into empl (eno,ename,sal) values (104,’ddd’,8000);declare cursor c1 is select eno,sal from empl;no empl.eno%type;s empl.sal%type;h empl.hra%type;d empl.da%type;t empl.ta%type;p empl.pf%type;n empl.net%type;beginopen c1;loopif c1%isopen thenfetch c1 into no,s;exit when c1%notfound;h:=s*13/100;d:=s*25/100;t:=800;p:=s*10/100;n:=(s+d+t+h)-p;end if;update empl set hra=h,da=d,ta=t,pf=p,net=n where eno=no;end loop;close c1;end;/syntax for rowtype:-rec_name(any var) table%rowtype;

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;

declareemp_rec empl2%rowtype;x number(4);beginx:=&empno;select * into emp_rec from empl2 where empno=x;

Page 48: Oracle  plsql Notes

insert into empl1 values(emp_rec.empno,emp_rec.ename,emp_rec.job,emp_rec.sal,emp_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/isdeclaration of the variables.beginstatementsend;

Executing a procedure individually:-exec <<procedure name>>(arg1,arg2,...);Create a procedure for adding any two numbers:-create or replace procedure pro_add(no1 in number,no2 in number) ass number;begins:=no1+no2;dbms_output.put_line(‘Sum of the two numbers=’||s);end;/

Calling a procedure by using the programmes:-set serveroutput ondeclarex number;y number;beginx:=&num1;y:=&num2;pro_add(x,y);end;/

create or replace procedure input_rec(no number,name varchar2) asbegininsert into empl (eno,ename) values(no,name);end;/

exec input_rec(101,’aaa’);exec input_rec(102,’bbb’);

Page 49: Oracle  plsql Notes

exec input_rec(103,’ccc’);exec input_rec(104,’ddd’);exec input_rec(105,’eee’);

create or replace procedure update_emp(no number,s number) ish empl.hra%type;d empl.da%type;t empl.ta%type;p empl.pf%type;n empl.net%type;beginif s>=10000 thenh:=12*s/100;d:=25*s/100;t:=1000;p:=10*s/100;elsif s>=5000 and s<10000 thenh:=14*s/100;d:=23*s/100;t:=8*s/100;p:=10*s/100;elseh:=15*s/100;d:=21*s/100;t:=800;p:=10*s/100;end if;n:=(s+h+d+t)-p;update empl set sal=s,hra=h,da=d,ta=t,net=n,pf=p where eno=no;end;/

create or replace procedure delete_emp(no number) asbegindelete from empl where eno=no;end;/

create or replace procedure addemp ascursor c1 is select * from empl2 order by empno;e number;na varchar2(10);j varchar2(10);s number;d number;beginopen c1;loopfetch c1 into e,na,j,s,d ;

Page 50: Oracle  plsql Notes

exit when c1%rowcount>5;insert into empl1 values(e,na,j,s,d);end loop;close c1;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/asdeclaration of variables.beginstatementsreturn var;end;

create a function for adding any three numbers.create or replace function funadd(no1 in number,no2 in number,no3 in number) return number iss number;begins:=no1+no2+no3;return s;end;/

prog to call addfun:-set serveroutput ondeclarea number(3):=&no1;b number(3):=&no2;c number(3):=&no3;x number(5);beginx:=funadd(a,b,c);

dbms_output.put_line(‘Sum of three numbers= ‘||x);end;/

declares number;begins:=funadd(100,200,300);dbms_output.put_line(‘Sum of three numbers= ‘||s);end;

Page 51: Oracle  plsql Notes

/

crteate a function to find factorial of a number.

create or replace function funfact(no in number) return number isx number:=1;f number:=1;beginwhile x<=noloopf:=f*x;x:=x+1;end loop;return f;end;/

declaren number;f number;beginn:=&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.

create or replace function funhire(eno in number) return date ishdate date;beginselect hiredate into Hdate from emp where empno=eno;return hdate;end;/

declaree number(4);hire date;begine:=&empno;hire:=funhire(e);dbms_output.put_line(‘The employee is hired on ‘||to_char(hire,’day ddth month yyyy’) );end;/PACKAGES:-

Page 52: Oracle  plsql Notes

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 definition2.Package body definition

1.Package definition:-syntax:-create or replace package <<package name>> as/isprocdure and function inclusionend <<packagename>>;/2.Package body definition:-create or replace package body <<pack body name>> as/isprocedure <<pro name1>> (arg1 dtype,arg2 dtype) isprocedure definition...................................end <<pro_name1>>;procedure <<pro name2>> (arg1 dtype,arg2 dtype) isprocedure 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;/

Package body creation

create or replace package body my_pack isprocedure addpro(no1 in number,no2 in number) iss number;begins:=no1+no2;dbms_output.put_line(‘Sum of the two numbers=’||s);end addpro;procedure subpro(no1 in number,no2 in number) isd number;begind:=no1-no2;dbms_output.put_line(‘Difference of the two numbers=’||d);end subpro;function profun (no1 in number,no2 in number) return number isp number;

Page 53: Oracle  plsql Notes

beginp:=no1*no2;return p;end profun;function divfun (no1 in number,no2 in number) return number isq number;beginq:=no1/no2;return q;end divfun;end my_pack;

/

To find product and quotientdeclaren1 number(4):=&no1;n2 number(4):=&no2;p number(5);q number(5,2);beginp:=my_pack.profun(n1,n2);q:=my_pack.divfun(n1,n2);

dbms_output.put_line(‘Product of the two numbers=’||p);dbms_output.put_line(‘Quotient of the two numbers=’||q);end;/

exec my_pack.addpro(20,30)exec my_pack.subpro(34,20) etc.

Create a package with three procedures 1.For adding the student data to a table 2.For calculating the total, average, result and division 3.for deleting a record from the student table. after that write a program to call all of those.

Create or replace package pack_me isProcedure adddata (no number,sname varchar2) ;Procedure caldata(no number,s1 number,s2 number,s3 number);Procedure deldata(no number) ;End pack_me;/

create or replace package body pack_me isprocedure adddata(no number,sname varchar2) isbegininsert into stud (rno,name)values(no,sname);end adddata;procedure caldata (no number,s1 number,s2 number,s3 number) ist stud.tot%type;

Page 54: Oracle  plsql Notes

a stud.avr%type;re stud.res%type;di stud.div%type;begint:=s1+s2+s3;a:=t/3;if s1>=35 and s2>=35 and s3>=35 thenre:=’pass’;elsere:=’fail’;end if;if re=’pass’ and a>=60 thendi:=’first’;elsif re=’pass’ and a>=50 then di:=’second’;elsif re=’pass’ and a>=35 thendi:=’third’;elsedi:=’Nill’;end if;update stud set sub1=s1,sub2=s2,sub3=s3,tot=t,avr=a,res=re,div=di where rno=no;end caldata;procedure deldata(no number) isbegindelete from stud where rno=no;end deldata;end pack_me;/

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 are1.After insert or update or delete2.Before insert or update or deleteSyntax:-create or replace trigger <<trigg name>> after/beforeinsert or update or delete on <<table name>> for each rowdeclare<<declaration section>>begin<<execution part>>end;

Page 55: Oracle  plsql Notes

drop table mess;create table mess(mess varchar2(20),time varchar2(30));

create or replace trigger mytri before insert or update or delete on stud for each rowdeclarem varchar2(20);time varchar2(30);beginif (inserting) thenm:=’you are inserting’;end if;if (updating) then m:=’u are updating’;end if;if (deleting) then m:=’u are deleting’;end if;time:=to_char(sysdate,’ddth month yyyy hh:mi am’);insert into mess values(m,time);end;/

Create a trigger to update the stock table when purchased and sold.

drop table stock;

create table stock(itemno number(3) constraints st_pk primary key,iname varchar2(10),qstock number(4));

drop table purchase;

create table purchase(itemno number(3) references stock(itemno),iname varchar2(10),qpur number(4));

drop table sales;create table sales(itemno number(3) references stock(itemno),iname varchar2(10),qsold number(4));insert into stock values(101,’tv’,100);insert into stock values(102,’cooler’,100);insert into stock values(103,’fridge’,100);insert into stock values(104,’suitcase’,100);

create or replace trigger pur_tri after insert on purchase for each rowdeclareq number(4);beginselect qstock into q from stock where itemno=:new.itemno;

Page 56: Oracle  plsql Notes

update stock set qstock=q+:new.qpur where itemno=:new.itemno;end;/

create or replace trigger sale_trig after insert on sales for each row declareq number(4);beginselect qstock into q from stock where itemno=:new.itemno;if q<:new.qsold thenraise_application_error(‘-20001’,’Insufficient stock’);elseupdate stock set qstock=q-:new.qsold where itemno=:new.itemno;end if;end;/

create a table for bank and write a trigger for transaction. create table bank_main(acno number(3) constraints b_pk primary

key, ahname varchar2(10),bal number(10,2)); create table bank_trans(acno number(3) references

bank_main(acno), payeename varchar2(10),trtype varchar2(10), tramount number(10,2)); insert into bank_main values(101,’rajesh’,20000); insert into bank_main values(102,’Suresh’,10000); insert into bank_main values(103,’Satish’,5000); insert into bank_main values(104,’Priya’,7500); insert into bank_main values(105,’Simran’,4500); create or replace trigger trans_tri after insert on bank_trans for

each row declare b number(10,2); begin select bal into b from bank_main where acno=:new.acno; if :new.trtype=’withdraw’ and b<:new.tramount then raise_application_error(-20002,’Insufficient balance,overdraft’); elsif :new.trtype=’withdraw’ then update bank_main set bal=b-:new.tramount where

acno=:new.acno; elsif :new.trtype=’deposit’ then update bank_main set bal=b+:new.tramount where

acno=:new.acno; end if; end;

Page 57: Oracle  plsql Notes

/ create or replace trigger date_tri before insert or update or delete

on bank_trans for each row begin if to_char(sysdate,’d’)=1 then raise_application_error(-20003,’Today is Sunday’); elsif to_char(sysdate,’hh24’) not between 9 and 13 then raise_application_error(-20004,’This is not working hour’); elsif to_char(sysdate,’dd’)=23 and to_char(sysdate,’mon’)=’feb’

thenraise_application_error(-20005,’Today this is Holiday for Bakrid’);end if;end;/--Create a trigger to calculate the total and average marks for 3 subjects after inserting the marks to the student table.