You are on page 1of 261

Department of Computer Science and Engineering /Dr.N.G.

P IT

Dr. N.G.P. INSTITUTE OF TECHNOLOGY

Coimbatore-641048

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

DATABASE MANAGEMENT SYSTEMS LABORATORY (R2013)

Prepared by Approved by
Mr.A.Dinesh Kumar,AP/CSE HoD/CSE
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

OBJECTIVE:
Learn to create and use a database
Be familiarized with a query language
Have hands on experience on DDL Commands
Have a good understanding of DML Commands and DCL commands
Familiarize advanced SQL queries.
Be Exposed to different applications

LIST OF EXPERIMENTS
1. Creation of a database and writing SQL queries to retrieve information from the
database.
2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records
based on conditions.
3. Creation of Views, Synonyms, Sequence, Indexes, Save point.
4. Creating an Employee database to set various constraints.
5. Creating relationship between the databases.
6. Study of PL/SQL block.
7. Write a PL/SQL block to satisfy some conditions by accepting input from the user.
8. Write a PL/SQL block that handles all types of exceptions.
9. Creation of Procedures.
10. Creation of database triggers and functions.
11. Mini project (Application Development using Oracle/ Mysql )

LAB EQUIPMENTS
Hardware and Software required for a batch of 20 students:
Hardware:
20 Personal Computers
Software:
Front end : VB/VC ++/JAVA
Back end: Oracle 11g, my SQL, DB2
Platform: Windows 2000 Professional/XP
Oracle server could be loaded and can be connected from individual PCs.
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT
EXNO 1 &2
CS6312 Database Management Systems lab
DDL, DML, DCL AND TCL COMMANDS OF SQL

AIM :
To execute the SQL queries for Data Definition Language (DDL),Data
Manipulation Language (DML) ,Data control Language(DCL) and Transaction Control
languages(TCL) using oracle.

DDL(Data Definition Language)
DDL statements are used to define the database structure or schema.
DDL commands are
 Create
 Alter
 Add
 Modify
 View
 Truncate

CREATE:
Description : To create a object in the database.

Syntax : create table table_name (columnname1 datatype, columnname
datatype, columnname3 datatype, ....);

Example : SQL> create table ss11(name char(10),rollno number(5),dept
varchar2(7),college varchar2(10));

Output : Table created.

VIEW:
Description : To view the description of table.

Syntax : Desc <table_name>;

Example : SQL> desc ss11;

Output :

Name Null? Type
-------------------------------- --------- ----------------------------
NAME CHAR(10)
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

ROLLNO NUMBER(5)
DEPT VARCHAR2(7)
COLLEGE VARCHAR2(10)

ALTER:
Description : This command is used to add,modify column in a table.
Syntax : alter table <table_name> add(columnname1 datatype,
columnname datatype, columnname3 datatype, ....);

: alter table <table_name> modify(columnname1 datatype,
columnname datatype, columnname3 datatype, ....);

Example : SQL> alter table ss11 add(rank number(2));

Output : Table altered.

Example : SQL> alter table ss11 modify(dept char(15));

Output : Table altered.
SQL> desc ss11;
Name Null? Type
--------------------- ---------------------------
---------------------------- NAME CHAR(10)
ROLLNO NUMBER(5)
DEPT CHAR(15)
COLLEGE VARCHAR2(10)
RANK NUMBER(2)

TRUNCATE:

Description : Truncate command is used to delete all the rows from the table and
free the space containing the table.
Syntax : truncate table <table_name>;
Example : SQL> truncate table ss11;
Output : Table truncated.

DROP:
Description : The SQL DROP command is used to remove an object from the
database. If you drop a table, all the rows in the table is deleted and the table
structure is removed from the database.
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

Syntax : drop table <table_name>;
Example : SQL> drop table ss11;
Output : Table dropped.
SCREEN SHOT

DML(Data Manipulation Language)

DML statements deals with querying, updating, deleting and inseting records in
tables, views or schema.
DML commands are
 Insert
 Update
 Select
 Where clause
 Delete
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

INSERT:
Description : This statement used to insert a row of data into table.

Syntax : insert into <table_name> values(data1,data2,data3,......);

Example : SQL> insert into ss17 values(&rollno,'&name',&mark1,&mark2);

Output :
Enter value for rollno: 08
Enter value for name: bharathi
Enter value for mark1: 89
Enter value for mark2: 92
old 1: insert into ss17 values(&rollno,'&name',&mark1,&mark2)
new 1: insert into ss17 values(08,'bharathi',89,92)

1 row created.

SQL> /
Enter value for rollno: 01
Enter value for name: abi
Enter value for mark1: 66
Enter value for mark2: 45
old 1: insert into ss17 values(&rollno,'&name',&mark1,&mark2)
new 1: insert into ss17 values(01,'abi',66,45)

1 row created.

SQL> select * from ss17;

ROLLNO NAME MARK1 MARK2
---------- ----------- ---------- ----------
8 bharathi 89 92
1 abi 66 45

OR
Description : The second form specifies both the column names and the values
to be inserted.

Syntax : insert into <table_name>(column1,column2...)
values(value1,value2,....);
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

Example : SQL> insert into ss17(rollno,name,mark1,mark2)
values(11,'kiruthika',95,98);

Output : 1 row created.

SELECT:
Description : This command is used to select rows from a table.

Syntax : select *from <table_name>;

Example : SQL> select * from ss17;

Output :
ROLLNO NAME MARK1 MARK2

---------- ----------- ---------- ----------

8 bharathi 89 92

1 abi 66 45

11 kiruthika 95 98
SCREEN SHOT
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

WHERE CLAUSE:
Description : The WHERE Clause is used to retrieve specific information from
a table excluding other irrelevant data.

The condition you provide in the WHERE clause filters the rows retrieved from
the table and gives you only those rows which you expected to see.
WHERE clause can be used along with SELECT, DELETE, UPDATE
statements.

Syntax : SELECT column_list FROM <table-name> WHERE
condition;

Example 1 : SQL> select name,mark1 from ss17 where rollno = 17;

Output :
NAME MARK1
----------- ----------
naveena 88

Example 2 To select particular record based on condition
Example 2 : SQL> select * from ss17 where name = 'naveena';
Output :

ROLLNO NAME MARK1 MARK2
---------- ----------- ---------- ----------
17 naveena 88 74

SCREEN SHOT
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

UPDATE:
Description : Updates existing data within a table.

Syntax : update table_name SET column_name1 = value1,
column_name2 = value2, ... [WHERE condition] ;

Example : update ss17 set total=mark1+mark2;

Output : 5 rows updated.

SQL> select * from ss17;

ROLLNO NAME MARK1 MARK2 TOTAL

---------- ----------- ---------- ---------- ----------

8 bharathi 89 92 181

1 abi 66 45 111

11 kiruthika 95 98 193

17 naveena 88 74 162

3 teena 23 36 59

DELETE:
Description : This command is used to delete the row from database.

Syntax : delete from <table_name> where(search conditions);

Example : SQL> delete from ss17 where name='bharathi';

Output : 1 row deleted.

SQL> select * from ss17;

ROLLNO NAME MARK1 MARK2 TOTAL

---------- ----------- ---------- ---------- ----------

1 abi 66 45 111

11 kiruthika 95 98 193
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

17 naveena 88 74 162

3 teena 23 36 59

TCL (Transaction Control)
These statements are used to manage the changes made by DML statements.
It allows statments to be grouped together into logical structures.
TCL commands are
 Commit
 Rollback

COMMIT:
Description : Used to save data that made by developer.

Syntax : commit;
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

Example : SQL> commit;

Output : Commit complete.

ROLLBACK:
Description : Used to save data that made by developer.

Syntax : commit;

Example : SQL> rollback;

Output : Rollback complete.

Oracle Built in Functions
There are two types of functions in Oracle.

Single Row Functions:
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT

CS6312 Database Management Systems lab

Single row or Scalar functions return a value for every row that is
processed in a query.

Group Functions:

Group functions are built-in SQL functions that operate on groups of rows
and return one value for the entire group.

AGGREGATE FUNCTION

1. AVG:
Description : The AVG() function returns the average value of a numeric
column.
Syntax : SELECT AVG(column_name) FROM <table_name>;

Example : SQL> select avg(mark1) from ss17;

OUTPUT :
AVG(MARK1)
------------------
68
2. SUM :
Description : The SUM() function returns the total sum of a numeric column.
Syntax : SELECT SUM(column_name) FROM <table_name>;
Example : SQL> select sum(mark1) from ss17;

OUTPUT :
SUM(MARK1)
--------------------
272

3. MAX :
Description : The MAX() function returns the largest value of the selected
column.

Syntax : SELECT MAX(column_name) FROM <table_name>;

Example : SQL> select max(mark1) from ss17;
Department of Computer Science and Engineering /Dr.N.G.P IT
CS6312 Database Management Systems lab

OUTPUT :
MAX(MARK1)
--------------------
95
4. MIN :
Description : The MIN() function returns the smallest value of the selected
column.

Syntax : SELECT MIN(column_name) FROM <table_name>;

Example : SQL> select min(mark1) from ss17;

OUTPUT :
MIN(MARK1)
--------------------
23
5. COUNT :
Description : The COUNT() function returns the numbers of rows .
Syntax : SELECT COUNT(column_name) FROM <table_name>;
Example : SQL> select count(name) from ss17;

OUTPUT :
COUNT(NAME)
----------------------
4
6. STDDEV :
Description : The STDDEV() function returns standard deviation of X .

Syntax : SELECT STDDEV(column_name) FROM <table_name>;

Example : SQL> select stddev(mark1) from ss17;

OUTPUT :
STDDEV(MARK1)
-------------------------
32.444825
CS6312 Database Management Systems lab

7. VARIANCE :
Description : The VARIANCE() function returns variance of X.

Syntax : SELECT VARIANCE(column_name) FROM <table_name>;

Example : SQL> select VARIANCE(mark1) from ss17;

OUTPUT :
VARIANCE(MARK1)
------------------------------
1052.66667

DCL (Data Control Language)

It is used to create roles, permissions and referential integrity.
Used to control access to database by securing it.
DCL commands are
 Grant
 Revoke
CS6312 Database Management Systems lab

GRANT:
Description : This command is used for gives access privileges to users for
database.

Syntax : grant dba to username;

Example : SQL> grant all on details to data;

Output : Grant succeeded.

REVOKE:
Description : This command is used for withdraw access privileges to users for
database.

Syntax : revoke permission on <table_name> from<user_name>;
Example : SQL> revoke delete on details from data;

Output : Revoke succeeded.
CS6312 Database Management Systems lab
CS6312 Database Management Systems lab

Viva-Voce:
1. What is SQL?
2. What is database?
3. What is DBMS?
4. What is a Database system?
5. Advantages of DBMS?
6. Disadvantage in File Processing System?
7. What are the categories of SQL command?
8. What is DML?
9. What are DML command?
10. Give the general form of SQL Queries?
11. Define tuple variable?
12.Write the syntax to retrieve specific columns from a table:
13. Define DCL?
14. List the DCL commands used in data bases
15. What type of privileges can be granted?
16. Write the syntax for grant command
17. What are TCL commands?
RESULT:
Thus the DDL,DML, TCL,DCL commands of sql was executed
successfully and output is verified.
EXNO 3 CS6312 Database Management Systems lab
DATABASE OBJECTS

AIM :
To create a database objects and perform synonyms, sequence, views ,index and
save point objects.

SYNONYMS
A synonym is an alias or alternate name for a table, view, sequence or schema
objects.

public creates a public synonym.

Schema is the schema to contain the sequence.

synonym is the name of the synonym to be created.

for identifies the object for which the synonym is created.

The object can be of these types: table, view, sequence, stored procedure,
function, or package, and synonym.

SQL> select * from details;
ROLLNO NAME ADDRESS GRADE
------------- ---------- --------------- ------------
1 a dpm c

5 raksha ooty b

8 dinu erode o

11 raji cbe d

CREATE A SYNONYM:
Description : Used to save data that made by developer.

Syntax : create synonym<synonym_name> for <table_name>;

Example : SQL> create synonym data11 for details;

Output : Synonym created.
CS6312 Database Management Systems
lab

SQL> select * from data11;
ROLLNO NAME ADDRESS GRADE
------------- --------- --------------- ----------
1 a dpm c

5 raksha ooty b

8 dinu erode o

11 raji cbe d

SQL> update details set name='abi' where

grade='c';

1 row updated.

SQL> select * from data11;
ROLLNO NAME ADDRESS GRADE
------------- ---------- ---------------- -------------
1 abi dpm c

5 raksha ooty b

8 dinu erode o

11 raji cbe d
CS6312 Database Management Systems
lab

SEQUENCE

In Oracle, can create an autonumber field by using sequences.
A sequence is an object in Oracle that is used to generate a number sequence.
Used to generate primary key value or unique key value automatically.
CREATE SEQUENCE

Description : To create a sequence in Oracle to handle an autonumber field.

Syntax : create sequence <sequence_name> [increment by n][start with
x][maxvalue n] [minvalue n][cycle/nocycle][cache n / nocache);
Example : create sequence myseq increment by 1 start with 1 maxvalue 1000
minvalue 1 nocycle cache 6;

Output : Sequence created.
CS6312 Database Management Systems lab

 START WITH : defines the first number of the sequence. Default is one.

 INCREMENT : define how many to add to get the nextvalues. Default is one.

 MINVALUE : defines the lowest value of the sequence when the sequence
is created to count down (increment by a minus number).

 MAXVALUE : defines the largest value of the sequence.

 CYCLE/NOCYCLE : tells the sequence to start over once it reaches the
maxvalue or minvalue. The default is NOCYCLE.

 CACHE/NOCACHE : tells thae database how many numbers to cache in
memory.

NEXTVAL:

Description : Insert one row into table Nextval stands for nextvalue.

Syntax : select sequence_name.nextval from table_name;

Example : SQL> select myseq.nextval from emp17;

Output : NEXTVAL
-------------
1
2
3
4
5
6

6 rows selected.

CURRVAL:

Description : CURRVAL is used instead of NEXTVAL to use the same
sequence number more than onces. currval stands for current value

Syntax : select <sequence_name>.currval from table_name;

Example : SQL> select myseq.currval from emp17;
CS6312 Database Management Systems lab

Output : CURRVAL
--------------
6
6
6
6
6
6
6 rows selected.
ALTER:

Description : The ALTER SEQUENCE command to alter a sequence.

Syntax : select sequence_name.nextval from table_name;

Example : SQL> alter sequence myseq increment by 10;

Output : Sequence altered.

AFTER ALTERING:

Output : SQL> select myseq.nextval from emp17;
NEXTVAL
----------------
16
26
36
46
56
66
6 rows selected.

SQL> alter sequence myseq increment by 1;

Sequence altered.

SQL> select myseq.nextval from emp17;

NEXTVAL
---------------
67
CS6312 Database Management Systems lab

68
69
70
71
72
6 rows selected.

Drop Sequence:
Description : Used to save data that made by developer.

Syntax : drop sequence <sequence_name>;

Example : SQL> drop sequence myseq;

Output : Sequence dropped.
CS6312 Database Management Systems lab
CS6312 Database Management Systems lab
CS6312 Database Management Systems lab

VIEWS

It takes the output of query and treats it as table.
Oracle stores only the definition of a view, not the rows retrieved by the query.

CREATE A VIEW :
Description : A view is, in essence, a virtual table. It does not physically exist.
Rather, it is created by a query joining one or more tables.
Syntax : create view <view_name>as select col1,col2,... from <basetable>;

Example : create view myview as select empno,ename from emp17;

Output : View created.

Create a virtual table based on the result set of the select statement.
Now query the view as follws:

SQL> select * from myview;
EMPNO ENAME
------------ ----------
121 swathi
44 uma
88 veena
14 kiruthi

UPDATING A VIEW :
Description : Update command for view is same as for tables.

Syntax : update <view_name> set value where condition;

Example : SQL> update myview set empno='111' where ename='swathi';

Output : 1 row updated.

After update
SQL> select * from myview;

EMPNO ENAME
---------- ----------
111 swathi
CS6312 Database Management Systems lab

44 uma
88 veena
14 kiruthi

DELETE A VIEW :
Description : Delete the row from database.

Syntax : delete from <view_name> where condition;

Example : SQL> delete from myview where ename='swathi';

Output : 1 row deleted.

After delete
SQL> select * from myview;

EMPNO ENAME
---------- ----------
44 uma
88 veena
14 kiruthi

DROPPING A VIEW :
Description : Drop command for destroy the table from database.

Syntax : drop view <view_name>;

Example : SQL> drop view myview;

Output : View dropped.
CS6312 Database Management Systems lab
CS6312 Database Management Systems lab

INDEX

Indexes are used to speed up SQL statement execution on a table.
Oracle indexes provide a faster access path to data in tables.
The index points directly to the location of the rows containing the value and
reduces disk I/O.

Creating a Indexes
Description : Drop command for destroy the table from database.

Syntax : drop view <view_name>;

Example : SQL> create index ind on d11(name);

Output : Index created.

Example : SQL> create unique index ind2 on d11(rollno);

Output : Index created.

Example : SQL> drop index ind;

Output : Index dropped.

Example : SQL> drop index ind2;

Output : Index dropped.
CS6312 Database Management Systems lab

SAVEPOINT
Description : command is used to undo the Records in a particular transaction.

Syntax : savepoint <savepoint_name>;

Example : SQL> savepoint veena1;

Output : Savepoint created.
CS6312 Database Management Systems lab

RESULT:
Thus the database objects (synonyms, sequences, views, index objects )
and (savepoint) tcl commands was executed successfully and output is verified.
EX NO 4 EMPLOYEE DATABASECS6312
USING Database Management Systems lab
CONSTRAINTS

Q. Creating an Employee database to set various constraints.

AIM :

To Create an Employee database to set various constraints.

INTEGRITY CONSTRAINT

An integrity constraint is a mechanism used by oracle to prevent invalid data
entry into the table.
It has enforcing the rules for the columns in a table.
The types of the integrity constraints are:
a) Domain Integrity b) Entity Integrity c) Referential Integrity

a) Domain Integrity

Verify wheather the data entered is n proper form and also they set a range for the
input data.

Not null

Check

NOT NULL CONSTRAINTS

Description :

While creating tables, by default the rows can have null value .
The enforcement of not null constraint in a table ensure that the table contains
values.

SYNTAX
Create table<table_name>(col1 data type CONSTRAINT<constraint name>
constraint def,col2 datatype);

Example : create table empn(eid number not null,ename varchar2(12) not null,dept
char(5),city varchar2(25));

OUTPUT : Table created.
CS6312 Database Management Systems lab

SQL> select * from empn;
NAME NULL? TYPE
------------ --------------- --------------
EID NOTNULL NUMBER

NAME NOTNULL VARCHAR2(12)
DEPT CHAR(25)

CITY VARCHAR2(25)

Check Constraint:

Check constraint can be defined to allow only a particular range of values .
when the manipulation violates this constraint, the record will be rejected.
Check condition cannot contain sub queries.
 IN
 NOT IN
 BETWEEN
 LIKE
1)IN :
SYNTAX : Check (col name IN (set of permitted values));

Example : Create table empin(eid number not null,ename varchar2(12) not null,dept
char(5),gender varchar(2) check(gender in(‘M’,’F’)));

OUTPUT : Table created.

2)NOT IN :
SYNTAX : Check (col name NOT IN (set of values not permitted));

Example : Create table empino(eid number not null,ename varchar2(12) not null,dept
char(5),gender varchar(2) check(gender not in(‘M’,’F’)));

OUTPUT : Table created.

3)BETWEEN :
SYNTAX : Check (col name BETWEEN value1 AND value2);
CS6312 Database Management Systems lab

Example : Create table empb(eid number not null,ename varchar2(12),gender
varchar(2) check(age between ‘1’ and ‘100’);

OUTPUT : Table created.

4)LIKE :

SYNTAX : Check (col name LIKE ‘S%’);

Example : Create table empb(eid number not null,ename varchar2(12),gender
varchar(2) check(age between ‘1’ and ‘100’);

OUTPUT : Table created.

ENTITY INTEGRITY

Maintains uniqueness in a record.
An entity represents a table and each row of a table represents an instance of that
entity.
To identify each row in a table uniquely we need to use this constraint.
There are 2 entity constraints:

 Unique key constraint
 Primary Key Constraint
UNIQUE KEY CONSTRAINT

Description : To prevent duplication of values with in the row of a column.

Example : create table empll(id number(5) unique);

OUTPUT : Table created.

SQL > desc empll;
NAME NULL? TYPE
----------- ------------ ------------
ID NOTNULL NUMBER

PRIMARY KEY CONSTRAINT
Description : It is one or more columns in a table which identifies each row in the table
uniquely.
Example : create table empss(eregno number primary key, name varchar2(12));
CS6312 Database Management Systems lab

OUTPUT : Table created.

FOREIGN KEY CONSTRAINT
Description : A column or combination of column included in the definition of
referential integrity, which would refer to a referenced key.

Example : create table empss1(eregno number,address varchar2(12) foreign
key(eregno) references empss);

OUTPUT : Table created.

REFERENCED KEY
Description : It is a unique or primary key upon which is defined on a column
belonging to the parent table.

Example : select distinct name from empss where 33<=(select eregno from
where name=’c’);

OUTPUT :
NAME
---------

Charu

Dharan

sharan

VIVA QUESTIONS
1. What is integrity constraint?
2. List the types of constraint.
3. Primary Key Constraint
4. Referential Integrity

RESULT :
Thus the various set of constraints are executed successfully and output is
verified.
EX No 5 CS6312
CREATING RELATIONSHIP Database Management
BETWEEN Systems lab
THE DATABASE

AIM :
To create a database and perform joins.

Relating Data through Join Concept

The purpose of a join concept is to combine data spread across tables.
A join is actually performed by the „where‟ clause which combines specified
rows of tables.
Syntax:
select columns from <table1>, <table2> where logical expression;
Types of Joins
 Simple Join
 Self Join
 Outer Join
 Inner Join

1. Simple Join
a) Equi-join:
Description :
o A join, which is based on equalities, is called equi-join.
o It combines rows that have the same values for the specified columns.

Example :SQL>select * from empz,deptz where empz.deptno=deptz.deptno;

Output :
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME CLGNAME
----------- ------------- -------- ------------- ------ -------------- ------------ ---------------
5 raja asp 1 20000 1 CSE ksr
8 ganga asp 2 17000 2 ece kite
30 veena ap 3 15000 3 IT KITE
12 kiruthika ap 3 15000 3 IT KITE
CS6312 Database Management Systems lab

b) Non Equi-join:

Description :
A join which is based on the relational operations other than = is called a
non equi-join.

Example :SQL>select* from empz,deptz where empz.deptno!=deptz.deptno;

Output :
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME CLGNAME
---------- ------------ --------- -------------- ---------- ----------- --------------- ---------------
12 kiruthika ap 3 15000 1 CSE ksr

8 ganga asp 2 17000 1 CSE ksr

30 veena ap 3 15000 2 ece kite

EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME CLGNAME
---------- ------------ --------- -------------- ---------- ----------- --------------- ---------------
12 kiruthika ap 3 15000 2 ece kite

5 raja asp 1 20000 2 ece kite

30 veena ap 3 15000 4 auto bit

EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME CLGNAME
---------- ------------ --------- -------------- ---------- ----------- --------------- ---------------
12 kiruthika ap 3 15000 4 auto bit

8 ganga asp 2 17000 4 auto bit

5 raja asp 1 20000 4 auto bit
CS6312 Database Management Systems lab

SCREEN SHORTS:
CS6312 Database Management Systems lab

2. Self join:
Description :
o Joining of a table to itself is known as self-join.
o It joins one row in a table to another.
o It can compare each row of the table to itself and also with other
rows of the same table.

Example : SQL> select empz.ename,empz.job,deptz.dname from empz,deptz
where empz.deptno=deptz.deptno;

Output :
ENAME JOB DNAME
------------- ----------- -------------
raja asp CSE

ganga asp ece

veena ap IT

kiruthika ap IT

3.Outer Join:
Description :
o It extends the result of a simple join.
o An outer join returns all the rows returned by simple join as well as
those rows from one table that do not match any row from the table.
o The symbol (+) represents outer join.

Example : SQL> select empz.ename,deptz.deptno from empz,deptz where
empz.deptno=deptz.deptno(+);

Output :
ENAME DEPTNO
---------- ----------
raja 1

ganga 2

veena 3

kiruthika 3
CS6312 Database Management Systems lab

VIVA QUESTIONS:

1. What is a self join?

2. What is a join and explain different types of joins.

3. What is outer join? Explain Left outer join, Right outer join and Full outer join.

4. What is the difference between WHERE clause and HAVING clause?

5. How does a left join work?

6. What is the difference between JOIN and UNION?

7. What does a right outer join include?

RESULT:
Thus the joins are executed successfully and output is verified.
EX No 6 CS6312
STUDY OF PL/SQL Database Management Systems lab
BLOCK

INTRODUCTION
The PL/SQL programming language was developed by Oracle Corporation in the
late 1980s as procedural extension language for SQL and the Oracle relational database.
Following are notable facts about PL/SQL:

PL/SQL is a completely portable, high-performance transaction-processing
language.

PL/SQL provides a built-in interpreted and OS independent programming
environment.

PL/SQL can also directly be called from the command-line SQL*Plus interface.

Direct call can also be made from external programming language calls to
database.

PL/SQL ARCHITECTURE

The PL/SQL compilation and run-time system is a technology, not an independent
product. Think of this technology as an engine that compiles and executes PL/SQL
blocks and subprograms. The engine can be installed in an Oracle server or in an
application development tool such as Oracle Forms or Oracle Reports.

So, PL/SQL can reside in two environments:

The Oracle database server
Oracle tools

These two environments are independent. PL/SQL is bundled with the Oracle server
but might be unavailable in some tools. In either environment, the PL/SQL engine
accepts as input any valid PL/SQL block or subprogram.

The PL/SQL engine processing an anonymous block. The engine executes
procedural statements but sends SQL statements to the SQL Statement Executor in the
Oracle server.
CS6312 Database Management Systems lab

Figure 1-4 PL/SQL Engine

In Oracle Tools

When it contains the PL/SQL engine, an application development tool can
process PL/SQL blocks and subprograms. The tool passes the blocks to its local
PL/SQL engine. The engine executes all procedural statements at the application site
and sends only SQL statements to Oracle. Thus, most of the work is done at the
application site, not at the server site.

Furthermore, if the block contains no SQL statements, the engine executes the
entire block at the application site. This is useful if your application can benefit from
conditional and iterative control.

Frequently, Oracle Forms applications use SQL statements merely to test the
value of field entries or to do simple computations. By using PL/SQL instead, you can
avoid calls to the Oracle server. Moreover, you can use PL/SQL functions to manipulate
field entries.

Advantages of PL/SQL

PL/SQL is a completely portable, high-performance transaction processing
language that offers the following advantages:

Support for SQL
Support for object-oriented programming
Better performance
Higher productivity
CS6312 Database Management Systems lab

Full portability
Tight integration with Oracle
Tight security

PL/SQL - Basic Syntax
PL/SQL is a block-structured language, meaning that PL/SQL programs are
divided and written in logical blocks of code.

Each block consists of three sub-parts:

Declarations

This section starts with the keyword DECLARE. It is an optional section and
defines all variables, cursors, subprograms, and other elements to be used in the
program.

Executable Commands

This section is enclosed between the keywords BEGIN and END and it is a
mandatory section. It consists of the executable PL/SQL statements of the program.

Exception Handling
This section starts with the keyword EXCEPTION. This section is again
optional and contains exception(s) that handle errors in the program.

Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested
within other PL/SQL blocks using BEGIN and END.

The basic structure of a PL/SQL block:

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
CS6312 Database Management Systems lab

The 'Hello World' Example:
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code from SQL
command line, you may need to type / at the beginning of the first blank line after the
last line of the code.
When the above code is executed at SQL prompt, it produces following result:

Hello World

PL/SQL procedure successfully completed.

PL/SQL PROGRAM UNIT
A PL/SQL program unit is one of the following: PL/SQL Anonymous
Block, Procedure, Function, Package Specification, Package Body, Trigger. Program
units are the PL/SQL source code that is compiled, developed and ultimately executed
on the database.

PL/SQL Anonymous Block
The basic unit of a PL/SQL source program is the block, which groups related
declarations and statements. A PL/SQL block is defined by the keywords DECLARE,
BEGIN, EXCEPTION, and END. These keywords divide the block into a declarative
part, an executable part, and an exception-handling part. The declaration section is
optional and may be used to define and initialize constants and variables. If a variable is
not initialized then it defaults to NULL value. The optional exception-handling part is
used to handle run time errors. Only the executable part is required. A block can have a
label.

For example:

<<label>> -- this is optional
DECLARE -- value default
-- this section is optional
number1 NUMBER(2);
CS6312 Database Management Systems lab

text1
--text2 varchar4(12)
DATE
this section := 'Hello
:= SYSDATE;
is mandatory, mustworld';
-- current
contain dateone
at least andexecutable
time statement
BEGIN
SELECTThe street_number
symbol := functions as an assignment operator to store a value in a variable.
INTO number1
FROMBlocks
address can be nested: Because a block is an executable statement, it can appear
inWHERE
another block
name wherever an executable statement is allowed. A block to an interactive
= 'INU';
EXCEPTION
tool (such as SQL*Plus) or embed it in an Oracle Precompiler or OCI program. The
-- this section is optional
interactive tool or program runs the block one time. The block is not stored in the
WHEN OTHERS THEN
database, and for that reason, it is called an anonymous block (even if it has a label).
DBMS_OUTPUT.PUT_LINE('Error Code is ' || TO_CHAR(SQLCODE ) );
PL/SQL - PROCEDURES Message is ' || SQLERRM );
DBMS_OUTPUT.PUT_LINE('Error
END; A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the
'Modular design'. A subprogram can be invoked by another subprogram or program
which is called the calling program.
A subprogram can be created:

At schema level

Inside a package

Inside a PL/SQL block

A schema level subprogram is a standalone subprogram. It is created with the
CREATE PROCEDURE or CREATE FUNCTION statement. It is stored in the
database and can be deleted with the DROP PROCEDURE or DROP FUNCTION
statement.
A subprogram created inside a package is a packaged subprogram. It is stored
in the database and can be deleted only when the package is deleted with the DROP
PACKAGE statement.
CS6312 Database Management Systems lab

PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of
parameters. PL/SQL provides two kinds of subprograms:

Functions: these subprograms return a single value, mainly used to compute and
return a value.
Procedures: these subprograms do not return a value directly, mainly used to
perform an action.
Parts of a PL/SQL Subprogram
Each PL/SQL subprogram has a name, and may have a parameter list. Like
anonymous PL/SQL blocks and, the named blocks a subprograms will also have
following three parts:

Declarative Part
It is an optional part. However, the declarative part for a subprogram does
not start with the DECLARE keyword. It contains declarations of types, cursors,
constants, variables, exceptions, and nested subprograms. These items are local to
the subprogram and cease to exist when the subprogram completes execution.

Executable Part
This is a mandatory part and contains statements that perform the
designated action.

Exception-handling
This is again an optional part. It contains the code that handles run-time
errors.

Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE
statement.

CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;

Where,
procedure-name specifies the name of the procedure.
CS6312 Database Management Systems lab

[OR REPLACE] option allows modifying an existing procedure.

The optional parameter list contains name, mode and types of the parameters. IN
represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
procedure-body contains the executable part.

PL/SQL - Functions
A PL/SQL function is same as a procedure except that it returns a value.

Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as
follows:

CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

Where,

function-name specifies the name of the function.
[OR REPLACE] option allows modifying an existing function.

The optional parameter list contains name, mode and types of the parameters. IN
represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.

RETURN clause specifies that data type you are going to return from the
function.
o function-body contains the executable part.
o function-body must contain a RETURN statement.
CS6312 Database Management Systems lab

PL/SQL - Cursors
Oracle creates a memory area, known as context area, for processing an SQL
statement, which contains all information needed for processing the statement, for
example, number of rows processed, etc.

A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL statement.
The set of rows the cursor holds is referred to as the active set.
There are two types of cursors:

 Implicit cursors

 Explicit cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement
is executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an
implicit cursor is associated with this statement. For INSERT operations, the cursor
holds the data that needs to be inserted. For UPDATE and DELETE operations, the
cursor identifies the rows that would be affected.

In PL/SQL, the most recent implicit cursor as the SQL cursor, which always has
the attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
SQL cursor has additional attributes, %BULK_ROWCOUNT and
%BULK_EXCEPTIONS, designed for use with the FORALL statement.

Explicit Cursors

Explicit cursors are programmer defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is :

CURSOR cursor_name IS select_statement;
CS6312 Database Management Systems lab

Working with an explicit cursor involves four steps:

Declaring the cursor for initializing in the memory

Opening the cursor for allocating memory

Fetching the cursor for retrieving data

Closing the cursor to release allocated memory

Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated SELECT
statement.

For example:

CURSOR c_customers IS SELECT id, name, address FROM customers;
Opening the Cursor
Opening the cursor allocates memory for the cursor and makes it ready for fetching the
rows returned by the SQL statement into it.

OPEN c_customers;
Fetching the Cursor
Fetching the cursor involves accessing one row at a time.

FETCH c_customers INTO c_id, c_name, c_addr;
Closing the Cursor
Closing the cursor means releasing the allocated memory.

CLOSE c_customers;
Example:
Following is a complete example to illustrate the concepts of explicit cursors:

DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CS6312 Database Management Systems lab

CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
EXIT WHEN c_customers%notfound;
END LOOP;
CLOSE c_customers;
END;
/

When the above code is executed at SQL prompt, it produces the following result:

1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed.

PL/SQL - Triggers
Triggers are stored programs, which are automatically executed or fired when
some events occur. Triggers are, in fact, written to be executed in response to any of the
following events:

A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event
is associated.
CS6312 Database Management Systems lab

Creating Triggers
The syntax for creating a trigger is:

CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Where,

CREATE [OR REPLACE] TRIGGER trigger_name : Creates or replaces an
existing trigger with the trigger_name.

{BEFORE | AFTER | INSTEAD OF}: This specifies when the trigger would be
executed. The INSTEAD OF clause is used for creating trigger on a view.

{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
[OF col_name]: This specifies the column name that would be updated.

[ON table_name]: This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old
values for various DML statements, like INSERT, UPDATE, and DELETE.

[FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.

WHEN (condition): This provides a condition for rows for which the trigger
would fire. This clause is valid only for row level triggers.
CS6312 Database Management Systems lab

Example:
To start with, we will be using the CUSTOMERS table:

S
e
l
e
c
t
|2
*0||
0|
31f0|
2r.2
|
|o05
|0
m
+
|R
The following program creates a row level trigger for the customers table that -ac| |
-A
would fire for INSERT or UPDATE or DELETE operations performed on the m u-h1
CUSTOMERS table. This trigger will display the salary difference between the old es-m 5D
st0e
values and new values: +
ehl
o-d0
CREATE OR REPLACE TRIGGER display_salary_changes |m h
BEFORE DELETE OR INSERT OR UPDATE ON customers -a.
e-b0i
FOR EACH ROW r-a0|
WHEN (NEW.ID > 0) s-d2
DECLARE ;-
sal_diff number; -||2
BEGIN -+ 23
sal_diff := :NEW.salary - :OLD.salary; --0
K
--0
dbms_output.put_line('Old salary: ' || :OLD.salary); h+
dbms_output.put_line('New salary: ' || :NEW.salary); -i-0|
dbms_output.put_line('Salary difference: ' || sal_diff); + .
-l0
END; -aK
/ -n0o
-|t
When the above code is executed at SQL prompt, it produces the following result: -|a
+
--6
Trigger created. -5|
-3-
--0
-|02
-.5
-k-0
-+ 0
a-
-u|
-
--h8M
-i5u
-k0m
-+ 0
|-.b
-a
+
--0i
--40|
-
-||2
-47
--5
C
--0
h-0|
-a-
--i.B
-t0h
0
-ao
-lp
--|a
i-
-|l
-
|--
+
+
-5
2-
2-|
-
|-H
-a
M
-r
P
-d
-i
-k
-|
-
-
-6
-
-|
+
|
K
o
I
m
aD
l
|

N
A
M
E
|

A
CS6312 Database Management Systems lab G
E

Here following two points are important and should be noted carefully: |

OLD and NEW references are not available for table level triggers, rather you A
can use them for record level triggers. D
D
If you want to query the table in the same trigger, then you should use the
R
AFTER keyword, because triggers can query the table or change it again only E
after the initial changes are applied and the table is back in a consistent state. S
Above trigger has been written in such a way that it will fire before any DELETE S
or INSERT or UPDATE operation on the table, but you can write your trigger on
a single or multiple operations, for example BEFORE DELETE, which will fire |
whenever a record will be deleted using DELETE operation on the table.
S
PL/SQL - Packages A
L
PL/SQL packages are schema objects that groups logically related PL/SQL types, A
variables and subprograms. R
Y
A package will have two mandatory parts:

Package specification |
+
Package body or definition -
-
Package Specification -
+
The specification is the interface to the package. It just DECLARES the types, -
variables, constants, exceptions, cursors, and subprograms that can be referenced from -
outside the package. In other words, it contains all information about the content of the -
package, but excludes the code for the subprograms. -
-
All objects placed in the specification are called public objects. Any subprogram
-
not in the package specification but coded in the package body is called
-
a private object.
-
The following code snippet shows a package specification having a single -
procedure. You can have many global variables defined and multiple procedures or -
functions inside a package. +
-
CREATE PACKAGE cust_sal AS -
PROCEDURE find_sal(c_id customers.id%type); -
END cust_sal; -
/ -
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
CS6312 Database Management Systems lab

When the above code is executed at SQL prompt, it produces the following result:

Package created.
Package Body
The package body has the codes for various methods declared in the package
specification and other private declarations, which are hidden from code outside the
package.

The CREATE PACKAGE BODY Statement is used for creating the package body. The
following code snippet shows the package body declaration for the cust_sal package
created above.

CREATE OR REPLACE PACKAGE BODY cust_sal AS
PROCEDURE find_sal(c_id customers.id%TYPE) IS
c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/

When the above code is executed at SQL prompt, it produces the following result:
Package body created.
Using the Package Elements
The package elements (variables, procedures or functions) are accessed with the
following syntax:
package_name.element_name;
Consider, we already have created above package in our database schema, the following
program uses the find_sal method of the cust_sal package:
DECLARE
code customers.id%type := &cc_id;
BEGIN
cust_sal.find_sal(code);
END;
/
CS6312 Database Management Systems lab

When the above code is executed at SQL prompt, it prompt to enter customer ID, and
when you enter an ID, it displays the corresponding salary as follows:

Enter value for cc_id: 1
Salary: 3000

PL/SQL procedure successfully completed.

VIVA QUESTIONS
1. What is PL/SQL?
2. What is the basic structure of PL/SQL?
3. What are the components of a PL/SQL Block?
4. What are the datatypes a available in PL/SQL?
5. What is the difference between a procedure and a function?
6. Describe the use of %ROWTYPE and %TYPE in PL/SQL?

RESULT:
Thus the case study is studied.
EX NO 7 PL/SQLCS6312
BLOCK Database Management Systems lab

Q. Write a PL/SQL block to satisfy some conditions by accepting input from the user.

AIM:
To write a PL/SQL to implement the given program.

Conditional Control- Branching in PL/SQL:
Sequence of statements can be executed on satisfying certain condition. If
statements are being used and different forms of if are:

1. Simple IF 2. If then else 3. Else if 4. Nested if

1. SIMPLE IF:

Syntax:
IF condition THEN
statement1;
statement2;
END IF;

Example:
SQL> set serveroutput on;

SQL> DECLARE

2 a number(2) := 10;

3 BEGIN

4 a:= 10;

5 -- check the boolean condition using if statement

6 IF( a < 20 ) THEN

7 -- if condition is true then print the following

8 dbms_output.put_line('a is less than 20 ' );

9 END IF;
CS6312 Database Management Systems lab

10 dbms_output.put_line('value of a is : ' ||

a); 11 END;

12 /

OUTPUT:

a is less than 20
value of a is : 10

PL/SQL procedure successfully completed.

IF-THEN-ELSE statement is:
A sequence of IF-THEN statements can be followed by an optional sequence
of ELSE statements, which execute when the condition is FALSE.

Syntax
IF condition THEN
statement1;
ELSE
statement2;
CS6312 Database Management Systems lab

END IF;

Example:
SQL> set serveroutput on;
SQL> DECLARE

2 a number(3) := 100;

3 BEGIN

4 -- check the boolean condition using if statement

5 IF( a < 20 ) THEN

6 -- if condition is true then print the following

7 dbms_output.put_line('a is less than 20 ' );

8 ELSE

9 dbms_output.put_line('a is not less than 20 ' );

10 END IF;

11 dbms_output.put_line('value of a is : ' ||
a); 12 END;

13 /

OUTPUT:

a is not less than 20
value of a is : 100

PL/SQL procedure successfully completed.
CS6312 Database Management Systems lab

IF-THEN-ELSIF Statement

Description: It allows you to choose between several alternatives.

Syntax:
IF condition1 THEN
statement1;
ELSIF condition2 THEN
statement2;
ELSIF condition3 THEN
statement3;
ELSE
statement;
END IF;

Example :
SQL> set serveroutput on;

SQL> DECLARE

2 a number(3) := 100;

3 BEGIN
CS6312 Database Management Systems lab

4 IF ( a = 10 ) THEN

5 dbms_output.put_line('Value of a is 10' );

6 ELSIF ( a = 20 ) THEN

7 dbms_output.put_line('Value of a is 20' );

8 ELSIF ( a = 30 ) THEN

9 dbms_output.put_line('Value of a is 30' );

10 ELSE

11 dbms_output.put_line('None of the values is matching');

12 END IF;

13 dbms_output.put_line('Exact value of a is: '|| a );

14 END;

15 /

OUTPUT:
None of the values is matching
Exact value of a is: 100

PL/SQL procedure successfully completed.
CS6312 Database Management Systems lab

NESTED IF:

Syntax :
IF condition THEN
statement1;
ELSE IF condition THEN
statement2;
ELSE
statement3;
END IF;
END IF;
ELSE
statement3;
END IF;

Example :

SQL> set serveroutput on;

SQL> DECLARE

2 a number(3) := 100;
CS6312 Database Management Systems lab

3 b number(3) := 200;

4 BEGIN

5 -- check the boolean condition

6 IF( a = 100 ) THEN

7 -- if condition is true then check the following

8 IF( b = 200 ) THEN

9 -- if condition is true then print the following

10 dbms_output.put_line('Value of a is 100 and b is 200' );

11 END IF;

12 END IF;

13 dbms_output.put_line('Exact value of a is : ' || a );

14 dbms_output.put_line('Exact value of b is : ' || b );
15 END;

16 /

OUTPUT:
Value of a is 100 and b is 200

Exact value of a is : 100

Exact value of b is : 200

PL/SQL procedure successfully completed.
CS6312 Database Management Systems lab

Example 2 for Nested if :

GREATEST AMONG THREE NUMBER
AIM
To write a PL/SQL program to find a greatest number among the three numbers.
ALGORITHM:
Step 1: Set the server output on.

Step 2: Declare all the variables.

Step 3: Get the a, b and c value from the user.

Step 4: Check a is greater than b and c, if it is display a is greater

Step 5: If the condition is false check b is greater than c then ‘b’ is greater.

Step 6: If the condition is false display c is greater.
CS6312 Database Management Systems lab

Step 7: PL/SQL procedure is completed and display greatest number among the

three number.

PROGRAM:
SQL> set serveroutput on;
SQL> declare

2 a number;

3 b number;

4 c number;

5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;

9 dbms_output.put_line('The Greatest number among the Three number is:');
10 dbms_output.put_line('********************************');

11 dbms_output.put_line('the given number a: '||a);

12 dbms_output.put_line('the given number b: '||b);

13 dbms_output.put_line('the given number c: '||c);

14 dbms_output.put_line('********************************');

15 if a>b and a>c then

16 dbms_output.put_line(a|| 'is
greater'); 17 else if b >c then

18 dbms_output.put_line(b|| 'is greater');
19 else
CS6312 Database Management Systems lab

20 dbms_output.put_line(c|| 'is greater');

21 end if;

22 end if;

23 end;

24 /

OUTPUT:
Enter value for a: 23
old 6: a:=&a;

new 6: a:=23; Enter

value for b: 45 old

7: b:=&b;

new 7: b:=45;
Enter value for c: 12
old 8: c:=&c;

new 8: c:=12;

The Greatest number among the Three number is:

********************************

the given number a: 23

the given number b: 45
the given number c: 12

********************************
45 is greater

PL/SQL procedure successfully completed.
CS6312 Database Management Systems lab

VIVA QUESTIONS:
1. Define block.
2. What are the two types of sub programs in PL/SQL?
3. List the Advantages of Sub programs.
4. What is Procedure?
5. Explain about REPLACE and AUTHID.
6. Define Function.
7. Give the syntax for Function.
8. What are the Parameters in Procedure?
9. Discuss abput control structures.

RESULT:
Thus, the PL/SQL programs have been executed successfully.
EXNO 8 CS6312 Database
EXCEPTION HANDLING Management Systems lab
IN PL/SQL

AIM :
To write a PL/SQL block to raise and handle different types of exceptions.

1. Checking whether any of the item with its unit is less than the pre-order level
using Pre-Defined Exception:

ALGORITHM :
Step 1 : Check in the item table whether any of the item’s unit is lesser than its
pre-order level.
Step 2 : If no data is found, then the NO_DATA_FOUND exception is raised
automatically.
Step 3 : Else if multiple rows are returned, then TOO_MANY_ROWS exception
is raised.
Step 4 : Else the name of the item is displayed.
Step 5 : End the PL/SQL block.

PROGRAM :
SQL>set serveroutput on;
SQL>declare
2 name varchar2(10);
3 begin
4 select iname into name from item where unit<pol;
5 dbms_output.put_line(‘the name of the item is ’|| name);
6 exception
7 when NO_DATA_FOUND then
8 dbms_output.put_line('None of the row matches the given condition');
9 when TOO_MANY_ROWS then
10 dbms_output.put_line(‘multiple rows matches the given condition');
11 end;
12 /

OUTPUT :
None of the row matches the given condition

PL/SQL procedure successfully completed.
CS6312 Database Management Systems lab
CS6312 Database Management Systems lab

2. Checking whether the item with its unit is less than the pre-order level using
User-Defined Exception:

ALGORITHM :
Step 1 : Declare the user-defined exception.
Step 2 : Read the id of the item.
Step 3 : Scan the item table for the matching id.
Step 4 : If found, then check whether it’s unit s less than the pre-order level.
Step 5 : If yes, then raise the exception by using the statement RAISE
EXCEPTION_NAME.
Step 6 : Else display the item name.
Step 7 : End the PL/SQL block.

PROGRAM :
SQL> set serverout on;
SQL> declare
2 iunit number;
3 ipol number;
4 DATA_NOT_AVAILABLE exception;
5 begin
6 select unit,pol into iunit,ipol from item where
id=1; 7 if ipol<iunit then
8 raise DATA_NOT_AVAILABLE;
9 end if;
10 exception
11 when DATA_NOT_AVAILABLE then
12 dbms_output.put_line('No records were retreived');
13 end;
14 /

OUTPUT :
No records were retrieved

PL/SQL procedure successfully completed.
CS6312 Database Management Systems lab

3. Inserting an amount in to a table called feespaid using user-defined
exception:

ALGORITHM :
Step 1 : Declare an user-defined exception called SUCCESS_INSERT.
Step 2 : Write an SQL insert statement to insert the amount into the feespaid
table.
Step 3 : Check whether any of the row was updated.
Step 4 : If found, the raise the exception SUCCESS_INSERT.
Step 5 : Else the insertion error occurs.
Step 6 :End the PL/SQL block.

PROGRAM :
SQL>set serveroutput on;
SQL> declare
2 amount number(5);
3 sid number(5);
4 SUCCESS_INSERT exception;
5 begin
6 insert into feespaid
values(&id,&amt); 7 if SQL%FOUND
then
8 raise SUCCESS_INSERT;
CS6312 Database Management Systems lab

9 end if;
10 exception
11 when SUCCESS_INSERT then
12 dbms_output.put_line('Insertion done...');
13 end;
14 /
OUTPUT:
SQL> /

Enter value for id: 1

Enter value for amt: 45000

old 6: insert into feespaid values(&id,&amt);
new 6: insert into feespaid values(1,45000);
insertion done...

PL/SQL procedure successfully completed.
CS6312 Database Management Systems lab

VIVA QUESTIONS:
1. What is an Exception? What are types of Exception?

2. What is Raise_application_error?

3. Where the Pre_defined_exceptions are stored?

RESULT:
Thus, the exception handling in PL/SQL blocks have been executed successfully.
CS6312 Database Management Systems lab

ADDITIONAL PROGRAMS
a) THE FIBONACCI SERIES GENERATION
AIM
To write a PL/SQL program to generate Fibonacci series for ‘n’ numbers.

ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables assign the values for the some of the variables

Step 3: Add the two variables (a, b) and values are stored in the temporary

variables(c).

Step 4: Display the temporary variables(c) and swap the ‘a’ and ‘b’ values and

increment i value

Step 5: Repeat step 3 to step 4 until i reach 10.

Step 6:PL.SQL procedure is completed and display Fibonacci series
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 a number:=-1;
3 b number:=1;
4 c number;
5 i number:=1;
6 begin
7 dbms_output.put_line('The Fibonacci series is:');
8 for i in 1..5
9 loop
10 c:=a+b;
11 a:=b;
12 b:=c;
13 dbms_output.put_line(c);
14 end loop;
15 end;
16 /

OUTPUT:
The Fibonacci series is:
0
1
1
2
3
PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands for generating Fibonacci series up to ‘n’ number was
executed and verified successfully.
CS6312 Database Management Systems lab

b) SUM OF DIGITS OF A GIVEN NUMBER
AIM
To write a PL/SQL program to sum of the digits of a given number
ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables assign the values for s as 0(zero).

Step 3: Get the n value from the user.

Step 4: check n is greater than 0, if it is calculate mod n and assign to the n2.

Step 5: Add n2 value with s and truncate floating value when n is divided into 10

and assign this value to n

Step 6: Repeat step 4 to step 5 until n equal to or less than zero.

Step 7: PL/SQL procedure is completed and display sum of digits of given number.
CS6312 Database Management Systems lab

PROGRAM:

SQL> declare
2 n number;
3 n1 number;
4 s number:=0;
5 n2 number;
6 begin
7 n:=&n;
8 n1:=n;
9 while n>0
10 loop
11 n2:=mod(n,10);
12 s:=s+n2;
13 n:=trunc(n/10);
14 end loop;
15 dbms_output.put_line('The sum of the given number is:'||s);
16 end;
17 /

OUTPUT:
Enter value for n: 23
old 7: n:=&n;
new 7: n:=23;
The sum of the given number is:5

PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands for sum of digits of a given number was executed and verified
successfully.
CS6312 Database Management Systems lab

c) PALINDROME
AIM
To write a PL/SQL program to check whether a given string is palindrome or not.

ALGORITHM:

Step 1: Set the server output on.

Step 2: Get the input string (name1) from the user

Step 3: Calculate the length of the input string

Step 4: Check L is greater than 0, if it is cut one character from last and store in the

string name2.

Step 5: Decrement L value by 1 and repeat step 4 to 5 until L equal to or less than

zero.

Step 6: Check name1 is equal to name2 if it is then print the given string is

palindrome otherwise is not a palindrome.

Step 7: PL/SQL procedure is completed and display the result.
CS6312 Database Management Systems lab

PROGRAM

SQL> declare
2 name1 varchar(20);
3 name2 varchar(20);
4 l number;
5 begin
6 name1:='&name1';
7 l:=length(name1);
8 while l>0
9 loop
10 name2:=name2||substr(name1,l,1);
11 dbms_output.put_line(name2);
12 l:=l-1;
13 end loop;
14 dbms_output.put_line('Reverse of string');
15 dbms_output.put_line('******************************************');
16 if name1=name2
17 then
18 dbms_output.put_line(name1||' is palindrome');
19 else
20 dbms_output.put_line(name1||' is not palindrome');
21 end if;
22 end;
23 /
CS6312 Database Management Systems lab

OUTPUT:

Enter value for name1: ko
old 6: name1:='&name1';
new 6: name1:='ko';
o
ok
Reverse of string
******************************************
ko is not palindrome

PL/SQL procedure successfully completed.

SQL> /
Enter value for name1: hah
old 6: name1:='&name1';
new 6: name1:='hah';
h
ha
hah
Reverse of string
******************************************
hah is palindrome

PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands to check a given string is palindrome or not was executed
and verified successfully.
CS6312 Database Management Systems lab

d) SWAP THE TWO VALUES WITH OUT USING THIRD VARIABLES
AIM
To write a PL/SQL program to swap the two values with out using temporary variables.

ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables.

Step 3: Get the two values(a,b) from the user

Step 4: do the following calculation

a=a+b
b=a-b
a=a–b

Step 5: PL/SQL procedure is completed and display a and b value after swapping
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 a number;
3 b number;
4 begin
5 a:=&a;
6 b:=&b;
7 dbms_output.put_line('Swap the two values without using Third variables');
8 dbms_output.put_line('*************************************************');
9 dbms_output.put_line('The value of a:'||a);
10 dbms_output.put_line('The value of b:'||b);
11 a:=a+b;
12 b:=a-b;
13 a:=a-b;
14 dbms_output.put_line('The value of a after swapping: '||a);
15 dbms_output.put_line('The value of b after swapping: '||b);
16 end;
17 /
CS6312 Database Management Systems lab

OUTPUT:
Enter value for a: 9
old 5: a:=&a;
new 5: a:=9;
Enter value for b: 2
old 6: b:=&b;
new 6: b:=2;
Swap the two values without using Third variables
**************************************************************
The value of a:9
The value of b:2
The value of a after swapping: 2
The value of b after swapping: 9

PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands to swap the two numbers without using third variables was
executed and verified successfully.
CS6312 Database Management Systems lab

e) SWAP THE TWO VALUES USING THIRD VARIABLES
AIM
To write a PL/SQL program to swap the two values with out using temporary variables

ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables.

Step 3: Get the two values(a,b) from the user

Step 4: swap the two numbers with a help of temporary variable ‘c’

c=a
a=b
b=c

Step 5: PL.SQL procedure is completed and display a and b value after swapping
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 dbms_output.put_line('Swap the two values using third variables');
9 dbms_output.put_line('***********************************************');
10 dbms_output.put_line('The value of a:'||a);
11 dbms_output.put_line('The value of b:'||
b); 12 c:=a;
13 a:=b;
14 b:=c;
15 dbms_output.put_line('The value of a after swapping: '||a);
16 dbms_output.put_line('The value of b after swapping: '||b);
17 end;
18 /
CS6312 Database Management Systems lab

OUTPUT:
Enter value for a: 3
old 6: a:=&a;
new 6: a:=3;
Enter value for b: 6
old 7: b:=&b;
new 7: b:=6;
Swap the two values using third variables
**************************************************************
The value of a:3
The value of b:6
The value of a after swapping: 6
The value of b after swapping: 3

PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands to swap the two numbers using third variables was executed
and verified successfully.
CS6312 Database Management Systems lab

f) FACTORIAL
AIM
To write a PL/SQL program to find a factorial value for a given number.

ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables assign the values for i and fact as 1.

Step 3: Get the n value from the user.

Step 4: Check n is greater than i, if it is calculate fact by using the formula

fact=fact*i. and increment i value by 1.

Step 5: Repeat step 4 until n equal to or less than zero.

Step 6: PL/SQL procedure is completed and display factorial value for a given number.
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 fact number:=1;
3 n number;
4 i number:=1;
5 r number;
6 begin
7 dbms_output.put_line('This is the Factorial program:');
8 r:=&n;
9 while i<=r
10 loop
11 fact:=fact *
i; 12 i:=i+1;
13 end loop;
14 dbms_output.put_line('The factorial value is:');
15 dbms_output.put_line(fact);
16 end;
17 /

OUTPUT:
Enter value for n: 5
old 8: r:=&n;
new 8: r:=5;
This is the Factorial program:
The factorial value is:
120

PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands to find the factorial value for a given number was executed
and verified successfully.
CS6312 Database Management Systems lab

g) GREATEST AMONG TWO NUMBERS
AIM
To write a PL/SQL program to find a greatest number among the two numbers.

ALGORITHM:
Step 1: Set the server output on.

Step 2: Declare all the variables.

Step 3: Get the a and b value from the user.

Step 4: Check a is greater than b, if it is display a is greater

Step 5: If the condition is false then ‘b’ is greater.

Step 6: PL/SQL procedure is completed and display greatest number among the

two number.
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 a number;
3 b number;
4 begin
5 a:=&a;
6 b:=&b;
7 dbms_output.put_line('Greatest Among Two numbers:');
8 dbms_output.put_line('**************************************');
9 dbms_output.put_line('the given number a: '||a);
10 dbms_output.put_line('the given number b: '||b);
11 if a > b
12 then
13 dbms_output.put_line(a|| ' is greater');
14 else
15 dbms_output.put_line(b|| ' is greater');
16 end if;
17 end;
18 /
CS6312 Database Management Systems lab

OUTPUT:
Enter value for a: 34
old 5: a:=&a;
new 5: a:=34;
Enter value for b: 23
old 6: b:=&b;
new 6: b:=23;
Greatest Among Two numbers:
**************************************
the given number a: 34
the given number b: 23
34 is greater

PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands to display greatest number among the two numbers was
executed and verified successfully.
CS6312 Database Management Systems lab

h) GREATEST AMONG THREE NUMBER
AIM
To write a PL/SQL program to find a greatest number among the three numbers.
ALGORITHM:
Step 1: Set the server output on.

Step 2: Declare all the variables.

Step 3: Get the a, b and c value from the user.

Step 4: Check a is greater than b and c, if it is display a is greater

Step 5: If the condition is false check b is greater than c then ‘b’ is greater.

Step 6: If the condition is false display c is greater.

Step 7: PL/SQL procedure is completed and display greatest number among the

three number
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
9 dbms_output.put_line('The Greatest number among the Three number is:');
10 dbms_output.put_line('********************************');
11 dbms_output.put_line('the given number a: '||a);
12 dbms_output.put_line('the given number b: '||b);
13 dbms_output.put_line('the given number c: '||c);
14 dbms_output.put_line('********************************');
15 if a>b and a>c then
16 dbms_output.put_line(a|| 'is greater');
17 else if b >c then
18 dbms_output.put_line(b|| 'is greater');
19 else
20 dbms_output.put_line(c|| 'is greater');
21 end if;
22 end if;
23 end;
24 /
CS6312 Database Management Systems lab

OUTPUT:

Enter value for a: 23
old 6: a:=&a;
new 6: a:=23;
Enter value for b: 45
old 7: b:=&b;
new 7: b:=45;
Enter value for c: 12
old 8: c:=&c;
new 8: c:=12;
The Greatest number among the Three number is:
********************************
the given number a: 23
the given number b: 45
the given number c: 12
********************************
45is greater

PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands to display greatest number among the three numbers was
executed and verified successfully.
CS6312 Database Management Systems lab

i) FINDING EVEN or ODD NUMBER
AIM
To write a PL/SQL program to find a given number is odd or even.

ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables.

Step 3: Get the input(b) from the user.

Step 4: Calculate mod(b,2) and assign result to the variable a.

Step 5: If remainder is equal to zero then it is an odd number otherwise it is an even number.

Step 6: PL/SQL procedure is completed and display the given number is odd or even.
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 a number;
3 b number;
4 begin
5 dbms_output.put_line('Find a number is ODD or
EVEN'); 6 b:=&b;
7 a:=mod(b,2);
8 if a =0 then
9 dbms_output.put_line('even number');
10 else
11 dbms_output.put_line('odd number');
12 end if;
13 end;
14 /
OUTPUT:
Enter value for c: 6
old 7: b:=&b;
new 7: b:=6;
Find a number is ODD or EVEN
even number
PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands to find a given number is odd or even was executed and
verified successfully.
CS6312 Database Management Systems lab

j) BASIC ARITHMETIC OPERATION
AIM
To write a PL/SQL program to perform a mathematical operation like addition, subtraction,
multiplication and division of a given numbers.

ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables.

Step 3: Get the input(a,b) from the user.

Step 4: Perform addition with two numbers (a,b) and store result in the variable e.

Step 5: Perform subtraction with two numbers(a,b) and store result in the variable e

Step 6: Perform multiplication with two numbers (a,b) and store result in the variable e.

Step 7: Perform division with two numbers (a,b) and store result in the variable e.

Step 8: PL/SQL procedure is completed and display the addition, subtraction,

multiplication and division result or a given numbers.
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 a number;
3 b number;
4 c number;
5 d number;
6 e number;
7 begin
8 dbms_output.put_line('The Arithmetic operation:');
9 a:=&c;
10 b:=&d;
11 dbms_output.put_line('The Addition result:');
12 e:=a+b;
13 dbms_output.put_line(e);
14 dbms_output.put_line('The Subtraction result is:');
15 e:=a-b;
16 dbms_output.put_line(e);
17 dbms_output.put_line('The Multiplication result is:');
18 e:=a*b;
19 dbms_output.put_line(e);
20 dbms_output.put_line('The Division result is:');
21 e:=a/b;
22 dbms_output.put_line(e);
23 end;
24 /
CS6312 Database Management Systems lab

OUTPUT:
Enter value for c: 6
old 9: a:=&c;
new 9: a:=6;
Enter value for d: 2
old 10: b:=&d;
new 10: b:=2;
The Arithmetic operation:
The Addition result:
8
The Subtraction result is:
4
The Multiplication result is:
12
The Division result is:
3

PL/SQL procedure successfully completed.

RESULT:

Thus the PL/SQL commands to perform arithmetic operation like addition, subtraction,
multiplication and division was executed and verified successfully.
CS6312 Database Management Systems lab

k) AMSTRONG NUMBER PROGRAM
AIM
To write a PL/SQL program to find a given number is amstrong number.

ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables and assign s is equal to 0(zero).

Step 3: Get the input(a) from the user.

Step 4: Assign that value into n and check n is greater than 0(zero),if it is do

following three steps:

1. n1:=mod(n,10);
2. s:=s+power(n1,3);
3. n:=floor(n/10);
Step 5: Repeat step 4 until n becomes 0(zero) or less than 0.

Step 6: If ‘s’ is equal to ‘b’ then its an amstrong number else it is not an amstrong number.

Step 7: PL/SQL procedure is completed and display the result.
CS6312 Database Management Systems lab

PROGRAM:

SQL> declare
2 a number;
3 b number;
4 n number;
5 n1 number;
6 s number:=0;
7 begin
8 dbms_output.put_line('The Amstrong number program');
9 dbms_output.put_line('******************************************');
10 b:=&a;
11 n:=b;
12 while n>0
13 loop
14 n1:=mod(n,10);
15 s:=s+power(n1,3);
16 n:=floor(n/10);
17 end loop;
18 if b != s
19 then
20 dbms_output.put_line('Not Amstrong number');
21 else
22 dbms_output.put_line('Amstrong number');
23 end if;
24 end;
25 /
CS6312 Database Management Systems lab

OUTPUT:

Enter value for a: 3
old 10: b:=&a;
new 10: b:=3;
The Amstrong number program
************************************************************
Not Amstrong number

PL/SQL procedure successfully completed.

SQL> /
Enter value for a: 153
old 10: b:=&a;
new 10: b:=153;
The Amstrong number program
************************************************************
Amstrong number

PL/SQL procedure successfully completed.

RESULT:

Thus the PL/SQL commands to check a given number is amstrong number or not was
executed and verified successfully.
CS6312 Database Management Systems lab

l) DISPLAYING GRADE OF THE STUDENT
AIM
To write a PL/SQL program to display the grade of the student result.

ALGORITHM:
Step 1: Set the server output on.

Step 2: Declare all the variables.

Step 3: Get the 6 subject marks from the user.

Step 4: Calculate total marks and percentage of marks.

Step 5: Check all subject mark is greater than 35 if it is not the display student result as fail.

Step 6: If all marks are greater than 35 then check percentage is less than 60 then display

‘Third Grade’.

Step 7: If the percentage is greater than 60 and less than 75 then display ‘Second Grade’.

Step 8: If all conditions are false then display ‘First Grade’.

Step 9: PL/SQL procedure is completed and display grade.
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 tam number;
3 eng number;
4 maths number;
5 cs number;
6 chem number;
7 physi number;
8 tot number;
9 avge number;
10 begin
11 tam:=&tam;
12 eng:=&eng;
13 cs:=&cs;
14 maths:=&maths;
15 physi:=&physi;
16 chem:=&chem;
17 tot:=tam+eng+cs+maths+ physi +chem;
18 avge:=trunc(tot/6);
19 dbms_output.put_line('Student Result');
20 dbms_output.put_line('*********************************************');
21 dbms_output.put_line('English:'||eng);
22 dbms_output.put_line('Tamil:'||tam);
23 dbms_output.put_line('Maths:'||maths);
24 dbms_output.put_line('Computer Science'||cs);
25 dbms_output.put_line('Physics:'||physi);
26 dbms_output.put_line('Chemistry:'||chem);
27 dbms_output.put_line('*********************************************');
28 dbms_output.put_line('The Percentage:'||avge);
29 if (tam<35 or eng<35 or maths<35 or chem<35 or physi<35 or cs<35) then
30 dbms_output.put_line('Fail');
31 else if (avge<=60) then
CS6312 Database Management Systems lab

32 dbms_output.put_line(' Third Grade');
33 else if (avge>= 61 and avge <=75) then
34 dbms_output.put_line('Second Grade');
35 else
36 dbms_output.put_line('First Grade');
37 end if;
38 end if;
39 end if;
40 end;
41 /

OUTPUT:

Enter value for tam: 89
old 11: tam:=&tam;
new 11: tam:=89;
Enter value for eng: 67
old 12: eng:=&eng;
new 12: eng:=67;
Enter value for cs: 90
old 13: cs:=&cs;
new 13: cs:=90;
Enter value for maths: 45
old 14: maths:=&maths;
new 14: maths:=45;
Enter value for physi: 67
old 15: physi:=&physi;
new 15: physi:=67;
Enter value for chem: 89
old 16: chem:=&chem;
new 16: chem:=89;
CS6312 Database Management Systems lab

Student Result
*********************************************
English:67
Tamil:89
Maths:45
Computer Science90
Physics:67
Chemistry:89
*********************************************
The Percentage:74
Second Grade

PL/SQL procedure successfully completed.

RESULT:

Thus the PL/SQL commands to display the grade of student result was executed and
verified successfully.
CS6312 Database Management Systems lab

m) DISPLAY THE NUMBER IN REVERSE ORDER
AIM
To write a PL/SQL program to display a given number in reverse order.
ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables and assign b is equal to 0(zero).

Step 3: Get the input(a) from the user.

Step 4: Check a is greater than 0(zero),if it is do following three steps:

1. c:=mod(a,10);
2. b:=(b*10)+c;
3. a:=trunc(a/10);
Step 5: Repeat step 4 until a becomes 0(zero) or less than 0.

Step 6: PL/SQL procedure is completed and display the result.
CS6312 Database Management Systems lab

PROGRAM:

SQL> declare
2 a number;
3 b number:=0;
4 c number;
5 begin
6 dbms_output.put_line('Reverse of the given number');
7 dbms_output.put_line('********************************************');
8 a:=&a;
9 while a>0
10 loop
11 c:=mod(a,10);
12 b:=(b*10)+c;
13 a:=trunc(a/10);
14 end loop;
15 dbms_output.put_line('The reverse number:'||b);
16 end;
17 /

OUTPUT:
Enter value for a: 78
old 8: a:=&a;
new 8: a:=78;
Reverse of the given number
********************************************
The reverse number:87

PL/SQL procedure successfully completed.

RESULT:

Thus the PL/SQL commands to display the given number in reverse order was executed
and verified successfully.
CS6312 Database Management Systems lab

n) DISPLAY THE NUMBER IN REVERSE ORDER USING STRING FUNCTION

AIM
To write a PL/SQL program to reverse the given number using string function.
ALGORITHM:

Step 1: Set the server output on.

Step 2: Get the input string as number(name1) from the user

Step 3: Calculate the length of the input string

Step 4: Check L is greater than 0, if it is cut one character from last and store in the string

name2.

Step 5: Decrement L value by 1 and repeat step 4 to 5 until L equal to or less than zero.

Step 6: PL/SQL procedure is completed and display the result.
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 name1 varchar(20);
3 name2 varchar(20);
4 l number;
5 begin
6 name1:='&name1';
7 l:=length(name1);
8 while l>0
9 loop
10 name2:=name2||substr(name1,l,1);
11 l:=l-1;
12 end loop;
13 dbms_output.put_line('Reverse the number using string
function'); 14 dbms_output.put_line('The given nunber is: '||name1);
15 dbms_output.put_line('The reverse of a given number is: '||name2);
16 end;
17 /

OUTPUT:
Enter value for name1: 234
old 6: name1:='&name1';
new 6: name1:='234';
Reverse the number using string function
The given nunber is: 234
The reverse of a given number is: 432
PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL commands to display the given number in reverse order using string
function was executed and verified successfully
CS6312 Database Management Systems lab

o) PRIME NUMBER OR NOT
AIM
To write a PL/SQL program to find a given number is prime or not

ALGORITHM:

Step 1: Set the server output on.

Step 2: Declare all the variables and assign c is equal to 0(zero).

Step 3: Get the input(a) from the user.

Step 4: Inside the for loop calculate mod(a,i) and check the result is equal to

0(zero) then increment count value c by 1(e).this will continue until I is equal to a.

Step 5: If c is equal to 2 then the given number is prime number otherwise the

given number is not prime number.

Step 6: PL/SQL procedure is completed and display the given number is prime or not.
CS6312 Database Management Systems lab

PROGRAM:
SQL> declare
2 a number;
3 c number:=0;
4 i number;
5 begin
6 a:=&a;
7 for i in 1..a
8 loop
9 if mod(a,i)=0
then 10 c:=c+1;
11 end if;
12 end loop;
13 if c=2 then
14 dbms_output.put_line(a||' is prime number');
15 else
16 dbms_output.put_line(a||' is not prime number');
17 end if;
18 end;
19 /

OUTPUT:
Enter value for a: 23
old 6: a:=&a;
new 6: a:=23;
23 is prime number

PL/SQL procedure successfully completed

RESULT:
Thus the PL/SQL commands to find a given number is prime or not was executed and verified
successfully.
EX No 9 CREATIONS OF CS6312 Database Management Systems lab
PROCEDURE

AIM:
To implement a procedure program.

ALGORITHM:
Step 1: Create a table ticket with fields ticket_number, starting place, destination
place, and ticket_fare.

Step 2: create a procedure called change with an argument tno.

Step 3 : If the ticket-fare of ticket-number placed is greater than 100, then the total-
fare is multiplied by 1-2 and returned else if is multiplied by 1-6 and is returned.

SYNTAX :
CREATE [ORREPLACE] PROCEDURE PROCEDURENAME
[PARAMETER[IN/OUT/IN/IN OUT] DATATYPE
[:=/DEFAULT EXPRESSION]
[(PARAMETER)]
IS/AS
DECLARATION
BEGIN
PL/SQL CODES
[EXCEPTION]
END
CS6312 Database Management Systems lab

PROCEDURES
SQL> create table ticket (ticket_number number, starting_place varchar2(20),
destination_place varchar2(22),total_fare number);

Table created.
SQL> insert into ticket values(&ticket_number, '&starting_place', '&destination_place',
&total_fare);

Enter value for ticket_number: 1

Enter value for starting_place: erode

Enter value for destination_place: chennai
Enter value for total_fare: 750

old 1: insert into ticket values(&ticket_number, '&starting_place',
'&destination_place', &total_fare)

new 1: insert into ticket values(1,'erode','chennai',750)

1 row created.
SQL> /

Enter value for ticket_number: 2
Enter value for starting_place: cbe

Enter value for destination_place: salem

Enter value for total_fare: 123

old 1: insert into ticket values(&ticket_number, '&starting_place',
'&destination_place', &total_fare)

new 1: insert into ticket values(2,'cbe','salem',123)

1 row created.

SQL> /

Enter value for ticket_number: 3
CS6312 Database Management Systems lab

Enter value for starting_place: chennai
Enter value for destination_place: hyd
Enter value for total_fare: 810

old 1: insert into ticket values(&ticket_number, '&starting_place',
'&destination_place', &total_fare)
new 1: insert into ticket values(3,'chennai','hyd',810)

1 row created.
SQL> select * from ticket;
TICKET_NUMBER STARTING_PLACE DESTINATION_PLACE TOTAL_FARE
-------------------------- -------------------------- ------------------------------ -------------------

1 erode chennai 750

2 cbe salem 123

3 chennai hyd 810

SQL> create or replace procedure change(tno number)is tfare number;

2 begin

3 select total_fare into tfare from ticket where ticket_number=tno;

4 if tfare>=100 then

5 update ticket set total_fare=total_fare*1.2 where
ticket_number=tno; 6 elsif tfare<100 then

7 update ticket set total_fare=total_fare*1.6

8 where ticket_number=tno;

9 end if;

10 dbms_output.put_line('table updated');

11 end;
CS6312 Database Management Systems lab

12 /

Procedure created.
SQL> exec change(1);

PL/SQL procedure successfully completed.
SQL> select * from ticket;

TICKET_NUMBER STARTING_PLACE DESTINATION_PLACE TOTAL_FARE
------------------------- --------------------------- -------------------------------- ------------------
1 erode chennai 900
2 cbe salem 123

3 chennai hyd 810
CS6312 Database Management Systems lab

VIVA QUESTIONS:
1. Define block.
2. What are the two types of sub programs in PL/SQL?
3. List the Advantages of Sub programs.
4. What is Procedure?
5. Explain about REPLACE and AUTHID.
6. Define Function.
7. Give the syntax for Function.
8. What are the Parameters in Procedure?
9. Discuss abput control structures.

RESULT:
Thus the procedure was executed successfully.
EX NO 10 a FUNCTIONS CS6312 Database Management Systems lab
IN PL/SQL

AIM:
To write PL/SQL(Functions)and to understand stored procedures in SQL.

FUNCTION:
A function is a subprogram that computes a value. The syntax for creating a
function is given Below

SYNTAX :
Create or replace function<function_name>[argument]
Return datatype is
(local declaration)
begin
(executable statements)
[Exception]
(exception handlers)
end

ALGORITHM :

Step 1: Create a table ticket with fields ticket_number, starting place, destination
place, and ticket_fare.

Step 2: create a function fun() which returns the tickets-fare of the ticket number
being passed.

Step 3 : call the function fun() in another program by passing a ticket-number.
CS6312 Database Management Systems lab

PROGRAM :
SQL> create function trainfn (trainnumber number) return number is trainfunction
ittrain.tfare % type;

2 begin

3 select tfare into trainfunction from ittrain where tno=trainnumber;

4 return(trainfunction);

5 end;

6 /

Function created.
SQL> set serveroutput on;

SQL> Declare

2 total number;

3 begin

4 total:=trainfn (101);

5 dbms_output.put_line('Train fare is Rs. '||total);

6 end;

7 /

Train fare is Rs. 485

PL/SQL procedure successfully completed.
CS6312 Database Management Systems lab

RESULT :
Thus the PL/SQL functions have been implemented successfully.
EX NO 10 CS6312
TRIGGERS IN Database Management Systems lab
PL/SQL
b

AIM :
To write a PL/SQL program to initiate Triggers under various conditions.

1. Create a trigger to insert a record into a table after each row is updated.
ALGORITHM :

Step 1 : Create two tables cust and order_new with attributes cid and cname.
Step 2 : Create a trigger named after _update_insert.
Step 3 : Update the cust table.
Step 4 : After each row is updated , a record must be inserted into the order_new
table.
Step 5 : End the trigger.

PROGRAM :
SQL> create or replace trigger after_update_insert
2 after
3 update
4 of cname
5 on cust
6 referencing old as o new as n
7 for each row
8 begin
9 insert into order_new values(:o.cid,:n.cname);
10 end;
11 /

OUTPUT :
Trigger created.

SQL> update cust set cname='Ramu' where cid=1;
1 row updated.

SQL> select * from cust;
CID CNAME
1 veena
CS6312 Database Management Systems lab

11

SQL> select * from order_new;
CID CNAME
11 kirthika

2.Create a trigger to delete a record from the table before SQL update statement is
executed.

ALGORITHM :
Step 1 : Create two tables cust and order_id.
Step 2 : Create a trigger named before_update_delete.
Step 3 : Delete a record from order_id table.
Step 4 : Update the cust table for the given condition.
Step 5 : End the trigger.

PROGRAM :
1 create or replace trigger before_update_delete
2 before
3 update on cust
4 begin
5 delete from order_new where cid=3;
CS6312 Database Management Systems lab

6 end;

OUTPUT :
Trigger created.

SQL> update cust set cname='siva' where cid=3;

1 row updated.

SQL> select * from cust;
CID CNAME
1 veena
3 siva

SQL> select * from order_new;

CID CNAME
1 veena
3 siva

3. Create a trigger to delete a record from the table after a SQL update statement
is executed.

ALGORITHM:
Step 1 : Create two tables named cust and order_new.
Step 2 : Create a trigger named after_update_delete.
Step 3 : update the table cust under given condition.
Step 4 : Delete the record from the table order_new.
Step 5 : End the trigger.

PROGRAM :
1 create or replace trigger after_update_delete
2 after
3 update on cust
4 begin
5 delete from order_new where cid=3;
6 end;

OUTPUT :
Trigger created.
CS6312 Database Management Systems lab

SQL> update cust set cname='mani' where cid=3;
1 row updated.

SQL> select * from cust;

CID CNAME
1 sita
3 mani

SQL> select * from order_new;

CID CNAME
1 sita

4. Create a trigger to delete the record from the table after each row is
updated.
ALGORITHM :
Step 1 : Create two tables cust and order_new.
Step 2 : Create a trigger named after_update_delete.
Step 3 : Update the table for the given condition.
Step 4 : After each row of updation, delete a row from the table order_new.
Step 5 : End the trigger.

PROGRAM :
1 create or replace trigger afterupdatedeleterows
2 after
3 update on cust
4 for each row
5 begin
6 delete from order_new where cname='sound';
7 dbms_output.put_line('1 row deleted');
8 end;
9 /

OUTPUT :
Trigger created.

SQL> update cust set cname='sound' where cid=2;
1 row deleted
1 row deleted
CS6312 Database Management Systems lab

2 rows updated.
SQL> select * from order_new;
CID CNAME
1 sita

SQL> select * from cust;
CID CNAME
2 sound
1 sita
2 sound

VIVA QUESTION
1. What is the need for triggers? Or List the requirements needed to design a trigger.
2. What is trigger?

RESULT :
Thus, the triggers using PL/SQL have been successfully executed.
EX NO 11 CS6312
MINI PROJECT - MENU Database Management Systems lab
DESIGN

AIM
To design a Note Pad Application menu using Visual Basic.

PROCEDURE
STEP 1: Start
STEP 2: Create the form with essential controls and insert the menu using menu editor.
STEP 3: Write the code for doing the appropriate functions.
STEP 4: Save the forms and project.
STEP 5: Execute the form.
STEP 6: Stop
EXECUTION

Coding:
Private Sub ab_Click()
RichTextBox1.SelFontName = "Arial Black"
End Sub

Private Sub al_Click()

End Sub

Private Sub bold_Click()
RichTextBox1.SelBold = True
End Sub

Private Sub cb_Click()
RichTextBox1.SelColor = vbblue
End Sub

Private Sub cl_Click()
RichTextBox1.SelColor = vbred
End Sub

Private Sub copy_Click() 'Clipboard.SetText
"richtextbox1.seltext", 1 'MsgBox
Clipboard.GetText Clipboard.SetText
RichTextBox1.SelText, 1
RichTextBox1.SelText = Clipboard.GetText
MsgBox Clipboard.GetText
CS6312 Database Management Systems lab

End Sub

Private Sub eighteen_Click()
RichTextBox1.SelFontSize = 18
End Sub

Private Sub exit_Click()
End
End Sub

Private Sub fcg_Click()
RichTextBox1.SelColor = vbgreen
End Sub

Private Sub fourteen_Click()
RichTextBox1.SelFontSize = 14
End Sub

Private Sub helpp_Click()
ans = MsgBox("visual basic sample notepad .....!", vbYes + vbinforamtion, "Help")
If ans = vbYes Then
Unload Me
End If
End Sub

Private Sub italic_Click()
RichTextBox1.SelItalic = True
End Sub

Private Sub MC_Click()
RichTextBox1.SelFontName = "Monotype Corsiva"
End Sub

Private Sub new_Click()
RichTextBox1 = ""
End Sub

Private Sub open_Click()
RichTextBox1.LoadFile ("C:\Notepad\Document.rtf")
End Sub
Private Sub paste_Click()
RichTextBox1.SelText = Clipboard.GetText
CS6312 Database Management Systems lab

End Sub

Private Sub save_Click()
RichTextBox1.SaveFile ("C:\Notepad\Document.rtf")
End Sub

Private Sub sixteen_Click()
RichTextBox1.SelFontSize = 16
End Sub

Private Sub Th_Click()
RichTextBox1.SelFontName = "Tahoma"
End Sub

Private Sub tn_Click()
RichTextBox1.SelFontName = "Times New Roman"
End Sub

Private Sub twele_Click()
RichTextBox1.SelFontSize = 12
End Sub

Private Sub underline_Click()
RichTextBox1.SelUnderline = True
End Sub

Private Sub vbblue_Click()
RichTextBox1.SelColor = vbblue
End Sub

Private Sub vbgreen_Click()
RichTextBox1.SelColor = vbgreen
End Sub

Private Sub vbred_Click()
RichTextBox1.SelColor = vbred
End Sub
CS6312 Database Management Systems lab

Output:
File Menu:

Fig.1. File Menu

Edit Menu

Fig.2. Edit Menu
CS6312 Database Management Systems lab

Format Menu:

Fig.3. Format Menu

VIVA QUESTIONS:
1. Explain about visual basic?
2. What is the size of .NET object?
3. What is the difference between DataTable and DataSet?
4. What are the namespace available in .net?
5. What are the two main parts of the .NET Framework?
6. What is serialization in .NET?
7. What are the advantages of VB.NET?

RESULT:
Thus the program has been loaded and executed successfully.
EX NO 11.1 CS6312 Database Management Systems lab
REPORT DESIGN

AIM
To design a report design using Visual Basic.

PROCEDURE
STEP 1: Start
STEP 2: Create the form with essential controls and insert the menu using menu editor.
STEP 3: Write the code for doing the appropriate functions.
STEP 4: Save the forms and project.
STEP 5: Execute the form and generate report
STEP 6: Stop
EXECUTION
Code for progress bar:
Private Sub Form_KeyPress(KeyAscii As Integer)
Unload Me
End Sub
Private Sub Frame1_Click()
Unload Me
frmLogin.Show
End Sub
Private Sub Timer1_Timer()
On Error Resume Next
ProgressBar1.Value = ProgressBar1.Value + 1
If ProgressBar1.Value = 100 Then
login.Show
Unload Me
End If
End Sub

Private Sub Timer2_Timer()
On Error Resume Next
ProgressBar2.Value = ProgressBar2.Value + 1
If ProgressBar2.Value = 100 Then
MsgBox ("welcome")
login.Show
Unload Me
End If
End Sub
CS6312 Database Management Systems lab

Code for login form:
Private Sub Command1_Click()
If (LCase(Text1.Text)) = "nagraaj" And (LCase(Text2.Text)) = "nagraaj" Then
Unload Me
Stock.Show
Else
MsgBox "Please Enter Correct Username and Password"
End If
End Sub

Private Sub Command2_Click()
End
End Sub
Private Sub Text2_KeyPress(KeyAscii As Integer)
If (LCase(Text1.Text)) = "nagraaj" And (LCase(Text2.Text)) = "nagraaj" Then
frmDataEnv.Show
Unload Me
End If
End Sub
Stock Form:
Private Sub cmadd_Click(Index As Integer)
Adodc1.Recordset.AddNew
a = InputBox("ENTER THE PRODUCT CODE")
Text1.Text = a
B = InputBox("ENTER THE PRODUCT NAME")
Text2.Text = B
C = InputBox("ENTER THE MAKE")
Text3.Text = C
D = InputBox("ENTER SUPPLIER")
Text4.Text = D
e = InputBox("ENTER THE QUANTITY")
Text5.Text = e
F = InputBox("ENTER THE PURCHASE DATE")
Text6.Text = F
G = InputBox("ENTER THE PRICE")
Text7.Text = G
H = InputBox("ENTER THE VAT %")
Text8.Text = H
Text8.Text = Val(Text7.Text) / 14
Text9.SetFocus
Text9.Text = Val(Text7.Text) + Val(Text8.Text)
'Adodc1.Recordset.Save
CS6312 Database Management Systems lab

'MsgBox ("UPDATED")
End Sub

Private Sub cmddelete_Click(Index As Integer)
Dim s As String
a = InputBox("Enter The product name")
a = Trim(a)
s = "product_TNAME='" & a '" "
Adodc1.Recordset.Delete

MsgBox ("deleted")
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
Text7.Text = ""
Text8.Text = ""
Text9.Text = ""
End Sub

Private Sub cmdmovl_Click(Index As Integer)
Adodc1.Recordset.MoveNext
End Sub

Private Sub cmdmovn_Click(Index As Integer)
'dodc1.Recordset.MoveNext
If (Adodc1.Recordset.EOF) = True Then
Adodc1.Recordset.MoveNext
Else
Adodc1.Recordset.MovePrevious
MsgBox ("THIS IS YOUR LAST RECORD")
End If

End Sub

Private Sub cmdmovp_Click(Index As Integer)
'dodc1.Recordset.MovePrevious
If Adodc1.Recordset.BOF = True Then
Adodc1.Recordset.MoveFirst
Else '
CS6312 Database Management Systems lab

Adodc1.Recordset.MoveNext
MsgBox ("THISIS YOUR FIRST RECORD")
End If
End Sub

Private Sub cmdsearch_Click(Index As Integer)

Dim a As String
a = InputBox("Enter Item Code")
s = "Item_code = '" + a + "'"
Adodc1.Recordset.MoveFirst
Adodc1.Recordset.Find s
If Adodc1.Recordset.EOF Then
MsgBox ("INVALID RECORD")
End If
End Sub
Private Sub cmdupadte_Click(Index As Integer)
Adodc1.Recordset.Update
MsgBox ("UPDATED")
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
Text7.Text = ""
Text8.Text = ""
Text9.Text = ""
End Sub
Private Sub commov_Click(Index As Integer)
Adodc1.Recordset.MoveFirst
End Sub
Private Sub Command1_Click()
Dim a As String
a = InputBox("Enter Item Code")
s = "Item_code = '" + a + "'"
Adodc1.Recordset.MoveFirst
Adodc1.Recordset.Find s
'Adodc1.Recordset ("select * from t1 where [ITEM_CODE] = " & Text1.Text(0) & "")
DataReport1.Show
If Adodc1.Recordset.EOF Then
MsgBox ("INVALID RECORD")
CS6312 Database Management Systems lab

End If
End Sub
Private Sub Command2_Click()
Adodc1.Recordset.Update
MsgBox ("UPDATED SUCCESSFULY")
End Sub
Private Sub Command3_Click()
Dim s As String
a = InputBox("Enter The student name")
a = Trim(a)
s = "STUDENTNAME='" & a '" "
Adodc1.Recordset.Delete
MsgBox ("deleted")
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
Text7.Text = ""
Text8.Text = ""
Text9.Text = ""
End Sub
Private Sub Command5_Click()
DataReport1.Show
End Sub
Private Sub EXIT_Click()
End
End Sub
Private Sub Image2_Click()
'Adodc1.Recordset (" * from t1 where [ITEM_CODE] = " & Text1.Text(0) & "")
DataReport1.Show
End Sub
Private Sub MSHFlexGrid1_Click()
'Adodc2.Refresh
End Sub
Private Sub VIEW_Click()
DataReport1.Show
End Sub
CS6312 Database Management Systems lab

Output:
Progress Bar

Login
CS6312 Database Management Systems lab

Stock Form:

Report Design:

RESULT:
Thus the program has been loaded and executed successfully.
CS6312 Database Management Systems lab

VIVA QUESTIONS:
1. How many .NET languages can a single .NET DLL contain?
2. What are the different types of applications supported in .NET (or) .NET Framework?
3. What is meant by .NET framework?
4. How many .NET languages can a single .NET DLL contain?
5. Which is the root namespace for fundamental types in .NET Framework?
6. Which method do you use to enforce garbage collection in .NET?
7. What are the namespace available in .net?
8. What are the two main parts of the .NET Framework?
9. What are the benefits of.NET Framework?
10. What are the advantages of VB.NET?

APPLICATIONS:

Airlines and railways: Airlines and railways use online databases for reservation, and for
displaying the schedule information.
Banking: Banks use databases for customer inquiry, accounts, loans, and other transactions.
Education: Schools and colleges use databases for course registration, result, and other
information.
Telecommunications: Telecommunication departments use databases to store information
about the communication network, telephone numbers, record of calls, for generating monthly
bills, etc.
Credit card transactions: Databases are used for keeping track of purchases on credit cards in
order to generate monthly statements.
E-commerce: Integration of heterogeneous information sources (for example, catalogs) for
business activity such as online shopping, booking of holiday package, consulting a doctor, etc.
Health care information systems and electronic patient record: Databases are used for
maintaining the patient health care details.
Digital libraries and digital publishing: Databases are used for management and delivery of
large bodies of textual and multimedia data.
Finance: Databases are used for storing information such as sales, purchases of stocks and
bonds or data useful for online trading.
Sales: Databases are used to store product, customer and transaction details.
Human resources: Organizations use databases for storing information about their employees,
salaries, benefits, taxes, and for generating salary checks.