Sunteți pe pagina 1din 52

G.

V ACHARYA INSTITUTE OF
ENGINEERING AND TECHNOLOGY
Department of Computer Engineering

LAB MANUAL
DBIR

Prepared by
Prof. Amit Chougule

DBIR LAB

1. Create a database with DDL Commands.

2. Create a database and manipulate it with DML and TCL Commands.


3. Perform nested queries using DML Commands.
4. Perform join queries and using DML Commands.
5. Perform Sub queries using DML Commands.
6. Triggers.
7. Views.
8. Write Procedures and functions using PL/SQL.
9. Implement a menu driven application to generate forms and reports using front
end tools
10. Mini Project
Contemporary Experiments (beyond syllabus)
1. PL/SQL Cursor.
2. Dynamic SQL
3. Design a database using ER model

Index

Ex. No

Name of the Experiment

Page
Number

BASIC DDL & DML COMMANDS

2.a

BASIC DDL & DML COMMANDS

10

2.b

BASIC DDL & DML COMMANDS

15

ER MODEL

21

TRIGGERS

23

NESTED SUBQUERIES

28

PL/SQL PROCEDURES AND FUNCTIONS

30

PL/SQL CURSOR

34

PL/SQL PROCEDURES AND FUNCTIONS

36

VIEWS

41

10

DYNAMIC SQL

45

11

MENU DRIVEN APPLICATION USING VB

48

INTRODUCTION TO SQL
SQL (Structured Query Language) is a database computer language designed for
the retrieval and management of data in relational database management systems

(RDBMS), database schema creation and modification, and database object access
control management.
SQL is a programming language for querying and modifying data and managing
databases. SQL was standardized first by the ANSI and (later) by the ISO. Most
database management systems implement a majority of one of these standards and
add their proprietary extensions. SQL allows the retrieval, insertion, updating, and
deletion of data.
A database management system also includes management and administrative
functions. Most -- if not all -- implementations also include a Command-line Interface
(SQL/CLI) that allows for the entry and execution of the language commands, as
opposed to only providing an API intended for access from a GUI.
The first version of SQL was developed at IBM by Donald D. Chamberlin and
Raymond F. Boyce in the early 1970s. This version, initially called SEQUEL, was
designed to manipulate and retrieve data stored in IBM's original relational database
product, System R. IBM patented their version of SQL in 1985, while the SQL
language was not formally standardized until 1986, by the American National
Standards Institute (ANSI) as SQL-86. Subsequent versions of the SQL standard have
been released by ANSI and as International Organization for Standardization (ISO)
standards.
Originally designed as a declarative query and data manipulation language,
variations of SQL have been created by SQL database management system (DBMS)
vendors that add procedural constructs, control-of-flow statements, user-defined data
types, and various other language extensions. With the release of the SQL:1999
standard, many such extensions were formally adopted as part of the SQL language
via the SQL Persistent Stored Modules (SQL/PSM) portion of the standard.
Common criticisms of SQL include a perceived lack of cross-platform portability
between vendors, inappropriate handling of missing data (see Null (SQL)), and
unnecessarily complex and occasionally ambiguous language grammar and semantics.
FEATURES OF SQL:
SQL is both an easy-to-understand language and a comprehensive tool for managing
data. Some of the major features of SQL are

Vendor independence

Portability across computer systems

SQL standards

IBM endorsement and commitment (DB2)

Microsoft commitment (SQL Server , ODBC, and ADO)

Relational foundation

High-level, English-like structure

Interactive, ad hoc queries

Programmatic database access

Multiple views of data

Complete database language

Dynamic data definition

Client/server architecture

Enterprise application support


Extensibility and object technology
Internet database access
Java integration (JDBC)
Industry infrastructure

SQL COMMANDS
SQL Consisting of DDL, DML, DCL, TCL COMMANDS.
DDL
Data Definition Language (DDL) statements are used to define the database structure
or schema.
DDL Commands: Create, Alter, Drop, Rename, Truncate
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from
spaces allocated for the records are removed
RENAME - rename an object

table,

including

all

DML
Data Manipulation Language (DML) statements are used for managing data within
schema objects
DML Commands:

Insert ,Update, Delete, Select

INSERT - insert data into a table


UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the

records

remain
SELECT - retrieve data from the a database
DCL
Data Control Language (DCL) statements is used to create roles, permissions, and
referential integrity as well it is used to control access to database by securing it.
DCL Commands:

Grant, Revoke

GRANT - gives user's access privileges to database


REVOKE - withdraw access privileges given
command
TCL

with

the

GRANT

Transaction Control (TCL) statements are used to manage the changes made by DML
statements. It allows statements to be grouped together into logical transactions.
TCL Commands:

Commit, Rollback, Save point

COMMIT - save work done


SAVEPOINT - identify a point in a transaction to which you can
later roll back
ROLLBACK - restore database to original since the last COMMIT
SYNTAXS OF COMMANDS
CREATE TABLE
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
);
ALTER A TABLE
To add a column in a table
ALTER TABLE table_name
ADD column_name datatype;
To delete a column in a table
ALTER TABLE table_name
DROP COLUMN column_name;
DROP TABLE
DROP TABLE table_name;
TRUNCATE TABLE
TRUNCATE TABLE table_name;

INSERT
INSERT INTO table_name
VALUES (value1, value2, value3,...);

( OR )
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...);
UPDATE
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value;
DELETE
DELETE FROM table_name
WHERE some_column=some_value;
SELECT
SELECT column_name(s)
FROM table_name;

Ex. No. 1.

BASIC DDL AND DML COMMANDS

AIM:

To create a college database with the following tables


o Student table with the fields rollno, name, mark1, mark2, mark3 and
the rollno must be unique.
o Dept table with the fields unique deptid and deptname
o Staff table with the fields staffid, name, designation
QUERIES:
SQL> create table student(rollno number(5) primary key, name varchar(20),mark1
number(3),mark2 number(3),mark3 number(3));
SQL>create table dept(deptid number(3) primary key,dname varchar(20));
SQL>create table staff(staffid number(3),name varchar(20), designation varchar(20));
SQL>insert into student values(&rollno,&name,&mark1,&mark2,&mark3);
SQL>insert into dept values(&deptid,&dname);
SQL>insert into staff values(&staffid,&name,&designation);
Write down the queries for the following.
i.
Describe the structure of all tables.
SQL> desc student;
SQL> desc dept;
SQL> desc staff;
ii.

Add a new column total, percentage in student table.\


SQL> alter table student add(total number(3),percentage number(5,2));
SQL> update student set total=mark1+mark2+mark3;
SQL> update student set percentage=total/3;

iii.

Add a new column dept in student table.


SQL> alter table student add(deptid number(3) references dept(deptid));

iv.

Add a new column grade in student table and update it as if


percentage >75 then first class with distinction, if percentage>60
and <75 then first class otherwise second class.
SQL> alter table student add(grade varchar(35));
SQL> update student set grade=case when percentage>75.0 then First
class with distinction when percentage>60.0 and percentage<75.0 then
first class else second class end;

v.

Make staffid in staff table as primary key and add new column
deptid as foreign key refers deptid in dept table.
SQL> alter table staff add primary key(staffid);
SQL> alter table staff add(deptid number(3));
SQL> alter table staff add constraint dpk foreign key(deptid) references
dept(deptid);

vi.

List the name and rollno of all the students.


SQL> select rollno,name from student;

vii.

List the name of students who scored 90 marks in all subject.


8

SQL>select name from student where mark1>90 and mark2>90 and


mark3>90;
viii.

List the name of students whose name starts with s and ends with a
SQL>select name from student where name likes%a;

ix.

List out the Asst professors in CSE dept


SQL>select name from staff where designation=asst.prof and deptid=1;

x.

Find the number of depts.


SQL>select count(deptid) from dept;

xi.

Find the student with minimum total


SQL>select min(total) from student;

xii.

Find the class average percentage and maximum percentage in a


class.
SQL>select avg(percentage),max(percentage) from student;

xiii.

List the number of students with grade First class with distinction
SQL>select count(rollno) from student where grade=first class with
distinction;

xiv.

List rollno, name of the student in descending order of total


SQL>select rollno,name from student order by total desc;

xv.

Find the number of students in each dept


SQL>select count(rollno) from student group by deptid;

xvi.

Find the depts in which the students are enrolled


SQL>select distinct deptid from student;

xvii.

Find all lecturers in the college


SQL>Select * from staff where designation=lecturer;

xviii. Find the student whose name is ends with i.


SQL>select * from student where name like %i;
xix.

Delete the student details whose name is Raju


SQL>delete from student where name=raju;

xx.

Delete all staffs belongs to EEE dept


SQL>delete from staff where deptid=6;

Ex. No.
2.a

BASIC DDL AND DML COMMANDS

AIM:

To Create employee table with the fields EMPNO(Primary key), ENAME,


JOB, MGR, HIREDATE, SAL, COMM, DEPTNO,AGE. Dept table with fields
DEPTNO(pk),DNAME,LOC
QUERIES:
SQL> create table employee(empno number(5)primary key,ename varchar(20),job
varchar(20),mgr number(5),doj date,salary number(7),deptno number(2),age
number(3));
Table created.
SQL> create table department(deptno number(2) primary key,dname
varchar(20),location varchar(20));
Table created.
SQL> alter table employee add constraint fk foreign key(deptno) references
department(deptno);
Table altered.
SQL> desc employee;
Name
Null? Type
----------------------------------------- -------- ---------------------EMPNO
NOT NULL NUMBER(5)
ENAME
VARCHAR2(20)
JOB
VARCHAR2(20)
MGR
NUMBER(5)
DOJ
DATE
SALARY
NUMBER(7)
DEPTNO
NUMBER(2)
AGE
NUMBER(3)
SQL> desc department;
Name
Null? Type
----------------------------------------- -------- ---------------------DEPTNO
NOT NULL NUMBER(2)
DNAME
VARCHAR2(20)
LOCATION
VARCHAR2(20)
SQL> insert into department values(&deptno,'&dname','&location');
Enter value for deptno: 1
Enter value for dname: account
Enter value for location: madurai
old 1: insert into department values(&deptno,'&dname','&location')
new 1: insert into department values(1,'account','madurai')
1 row created.
SQL> select * from department;

10

DEPTNO DNAME
LOCATION
---------- -------------------- -------------------1 account
madurai
2 sales
madurai
3 production
sivakasi
SQL> insert into employee
values(&empno,'&ename','&job',&mgr,'&doj',&salary,&deptno,&age);
Enter value for empno: 101
Enter value for ename: siva
Enter value for job: manager
Enter value for mgr: 0
Enter value for doj: 01-mar-2005
Enter value for salary: 24000
Enter value for deptno: 1
Enter value for age: 23
old 1: insert into employee
values(&empno,'&ename','&job',&mgr,'&doj',&salary,&deptno,&age)
new 1: insert into employee values(101,'siva','manager',0,'01-mar-2005',24000,1,23)
1 row created.
SQL> select * from employee;
EMPNO ENAME
JOB
MGR DOJ
---------- -------------------- -------------------- ---------- --------SALARY DEPTNO
AGE
---------- ---------- ---------101 siva
manager
0 01-MAR-05
24000
1
23
102 mani
10000
1

clerk
34

103 sarpa
250000
3

manager
24

101 01-SEP-05
0 23-MAR-06

EMPNO ENAME
JOB
MGR DOJ
---------- -------------------- -------------------- ---------- --------SALARY DEPTNO
AGE
---------- ---------- ---------104 rajan
supervisor
103 10-OCT-07
14000
3
30
105 viji
20000

106 ramya
14000
2

manager
25

0 04-JUN-00

salesrep
27

105 01-JUL-01

11

EMPNO ENAME
JOB
MGR DOJ
---------- -------------------- -------------------- ---------- --------SALARY DEPTNO
AGE
---------- ---------- ---------107 kalai
worker
103 02-APR-03
1600
2
26
7 rows selected.
1. List all employee names and their salaries, whose salary lies between 1500/and 3500/- both inclusive.
SQL> select ename from employee where salary between 1500 and 3500;
ENAME
-------------------Kalai
2. List all employee names and their and their manager whose manager is 7902
or 7566 0r 7789.
SQL> select ename from employee where mgr in(7902,7566,7789);
ENAME
-------------------mani
rajan
kalai
3. List all employees which starts with either J or T.
SQL> select ename from employee where ename like 'J%' or ename like 'T%';
ENAME
-------------------rajan
ramya
kalai
4. List all jobs available in employee table.
SQL> select distinct job from employee;
JOB
-------------------clerk
manager
salesrep
supervisor
worker
5. List all employee names , salary and 15% rise in salary.
SQL> select ename,salary,salary+0.15*salary from employee;
ENAME
SALARY SALARY+0.15*SALARY
-------------------- ---------- -----------------siva
24000
27600
12

mani
sarpa
rajan
viji
ramya
kalai

10000
250000
14000
20000
14000
1600

11500
287500
16100
23000
16100
1840

7 rows selected.
6. Find how many job titles are available in employee table.
SQL> select count(distinct job) from employee;
COUNT(DISTINCTJOB)
-----------------5
7. What is the difference between maximum and minimum salaries of
employees in the organization?
SQL>SQL> select max(salary)-min(salary) from employee;
MAX(SALARY)-MIN(SALARY)
----------------------248400
8. Display all employee names and salary whose salary is greater than minimum
salary of the company and job title starts with M.
SQL> select ename,salary from employee where job like 'm%' and salary>(select
min(salary) from employee);
ENAME
SALARY
-------------------- ---------siva
24000
sarpa
250000
viji
20000
9. Display lowest paid employee details under each manager.
SQL> select min(salary) from employee group by mgr
10. Display number of employees working in each department and their
department name.
SQL> select dname,count(ename) from employee,department where
employee.deptno=department.deptno group by dname;
DNAME
COUNT(ENAME)
-------------------- -----------account
2
production
2
sales
3
11. Find all managers in each dept appointed after year 2000
SQL> select ename from employee where job='manager' and extract(year from
doj)>2000;
ENAME
-------------------13

siva
sarpa
12. Find all manager and his working place whose age is above 35 with salary
more than 1 lakh.
SQL> select ename from employee where job='manager' and age>35 and
salary>100000;
ENAME
-------------------Sarpa

Ex. No.
2.b

BASIC DDL AND DML COMMANDS

AIM:

14

To create the table employee with attributes ESSN, sname, mname, lname,
DOB, address, gender, salary, deptno. Create the table department with the attributes
depno, dname, mssn, deptloc. Create the table project entity set with attributes
prono(P.K) proname, Proloc,depno. Create the workson entity set with the attributes
ESSN(F.K) prono(F.K), Hours per week. Create the dependant entity set with the
attributes essn(F.K),depname, Gender, dob, relationship
QUERIES:
SQL> create table deptmt(depno number(3) primary key,dname varchar(20),mssn
number(4),deptloc varchar(20));
Table created.
SQL> create table emp(essn number(4) primary key,sname varchar(20),mname
varchar(10),lname varchar(20),dob date,address varchar(25),gender varchar(1),salary
number(5),depno number(3) references deptmt (depno));
Table created.
SQL> create table project(prono number(3) primary key,proname varchar(20),proloc
varchar(20),depno number(3) references deptmt(depno));
Table created.
SQL> create table workson(essn number(4) references emp(essn),prono number(5)
references project,hoursperweek number(2));
Table created.
SQL> create table dependent(essn number(4) references emp(essn),depname
varchar(20),gender varchar(1),dob date,relationship varchar(20));
Table created.
SQL> insert into deptmt values(&depno,'&dname',&mssn,'&deptloc');
Enter value for depno: 1
Enter value for dname: research
Enter value for mssn: 1001
Enter value for deptloc: madurai
old 1: insert into deptmt values(&depno,'&dname',&mssn,'&deptloc')
new 1: insert into deptmt values(1,'research',1001,'madurai')
1 row created.
SQL> insert into emp
values(&essn,'&sname','&mname','&lname','&dob','&address','&gender',&salary,&de
pno);
Enter value for essn: 1001
Enter value for sname: john
Enter value for mname: b

15

Enter value for lname: smith


Enter value for dob: 10-jan-1990
Enter value for address: madurai
Enter value for gender: m
Enter value for salary: 20000
Enter value for depno: 1
old 1: insert into emp
values(&essn,'&sname','&mname','&lname','&dob','&address','&gender',&salary
new 1: insert into emp values(1001,'john','b','smith','10-jan1990','madurai','m',20000,1)
1 row created.
SQL> insert into workson values(&essn,&prono,&hoursperweek);
Enter value for essn: 1001
Enter value for prono: 101
Enter value for hoursperweek: 5
old 1: insert into workson values(&essn,&prono,&hoursperweek)
new 1: insert into workson values(1001,101,5)
1 row created.
SQL> insert into dependent
values(&essn,'&depname','&gender','&dob','&relationship');
Enter value for essn: 1001
Enter value for depname: kalai
Enter value for gender: f
Enter value for dob: 29-jan-1984
Enter value for relationship: daughter
old 1: insert into dependent
values(&essn,'&depname','&gender','&dob','&relationship')
new 1: insert into dependent values(1001,'kalai','f','29-jan-1984','daughter')
1 row created.
SQL> desc deptmt;
Name
Null? Type
----------------------------------------- -------- -------------------DEPNO
NOT NULL NUMBER(3)
DNAME
VARCHAR2(20)
MSSN
NUMBER(4)
DEPTLOC
VARCHAR2(20)
SQL> desc emp;
Name
Null? Type
----------------------------------------- -------- -------------------ESSN
NOT NULL NUMBER(4)
SNAME
VARCHAR2(20)
MNAME
VARCHAR2(10)
LNAME
VARCHAR2(20)
DOB
DATE

16

ADDRESS
GENDER
SALARY
DEPNO

VARCHAR2(25)
VARCHAR2(1)
NUMBER(5)
NUMBER(3)

SQL> desc project;


Name
Null? Type
----------------------------------------- -------- -------------------PRONO
NOT NULL NUMBER(3)
PRONAME
VARCHAR2(20)
PROLOC
VARCHAR2(20)
DEPNO
NUMBER(3)
SQL> desc workson;
Name
Null? Type
----------------------------------------- -------- -------------------ESSN
NUMBER(4)
PRONO
NUMBER(5)
HOURSPERWEEK
NUMBER(2)
SQL> desc dependent;
Name
Null? Type
----------------------------------------- -------- -------------------ESSN
NUMBER(4)
DEPNAME
VARCHAR2(20)
GENDER
VARCHAR2(1)
DOB
DATE
RELATIONSHIP
VARCHAR2(20)
SQL> select * from emp;
ESSN SNAME
MNAME LNAME
DOB
---------- -------------------- ---------- -------------------- --------ADDRESS
G SALARY DEPNO
------------------------- - ---------- ---------1001 john
b
smith
10-JAN-50
madurai
m
20000
1
2001 sam
sivakasi
3001 siva
new houston

b
raj
30000

e
m

raja
15000

18-AUG-81
2
10-DEC-92
3

SQL> select * from deptmt;


DEPNO DNAME
MSSN DEPTLOC
---------- -------------------- ---------- -------------------1 research
1001 madurai
2 sales
2001 sivakasi
3 accounts
3001 theni

17

SQL> select * from project;


PRONO PRONAME
PROLOC
---------- -------------------- -------------------- ---------101 securityservice
madurai
1
102 productx
stafford
1
103 payrollprocessing theni
3

DEPNO

SQL> select * from workson;


ESSN
PRONO HOURSPERWEEK
---------- ---------- -----------1001
101
5
1001
102
8
3001
103
7
SQL> select * from dependent;
ESSN DEPNAME
G DOB
RELATIONSHIP
---------- -------------------- - --------- -------------------1001 kalai
f 29-JAN-84 daughter
2001 sam
m 02-MAR-90 son
3001 fathima
f 03-JUN-76 wife
Write the queries to do the following
1. Retrieve the birthdate and address of the employee(s) whose name is John B.
Smith
SQL> select dob,address from emp where sname='john' and mname='b' and
lname='smith';
DOB
ADDRESS
--------- ------------------------10-JAN-90 madurai
2. Retrieve the name and address of all employees who work for the Research
department
SQL> select sname,lname,address from emp,deptmt where dname='research' and
emp.depno=deptmt.depno;
SNAME
LNAME
ADDRESS
-------------------- -------------------- ------------------------john
smith
madurai
3. For every project located in Stafford, list the project number, the controlling
department number, and the department managers last name, address, and
birthdate.
SQL> select p.prono,d.depno,e.lname,e.address,e.dob from emp e,project p,deptmt d
where p.proloc='stafford' and e.depno=d.depno and e.depno=p.depno and
d.mssn=e.essn;
PRONO
DEPNO LNAME
ADDRESS
DOB
---------- ---------- -------------------- ------------------------- --------102
1 smith
madurai
10-JAN-90
18

4.Retrieve all employees whose address is in Houston


SQL> select sname,lname from emp where address like '%houston';
SNAME
LNAME
-------------------- -------------------siva
raja
5. Show the resulting salaries if every employee working on the ProductX
project is given a 10 percent raise.
SQL> select sname,lname,1.1*salary from emp e,workson w,project p where
e.essn=w.essn and p.prono=w.prono and p.proname='productx';
SNAME
LNAME
1.1*SALARY
-------------------- -------------------- ---------john
smith
22000
6. Retrieve all employees in department 5 whose salary is between $30,000 and
$40,000.
SQL> select * from emp where salary between 30000 and 40000 and depno=5;
ESSN SNAME
MNAME LNAME
DOB
---------- -------------------- ---------- -------------------- --------ADDRESS
G SALARY DEPNO
------------------------- - ---------- ---------3001 siva
e
raja
10-DEC-92
new houston
m
15000
3
7. Retrieve a list of employees and the projects they are working on, ordered by
department and, within each department, ordered alphabetically by last name,
first name.
SQL> select d.dname,e.lname,e.sname,p.proname from deptmt d,emp e,workson
w,project p where e.depno=d.depno and e.essn=w.essn and p.prono=w.prono order by
d.dname,e.lname,e.sname;
DNAME
LNAME
SNAME
-------------------- -------------------- -------------------PRONAME
-------------------accounts
raja
siva
payrollprocessing
research
smith
securityservice

john

research
smith
john
productx
8. Retrieve the name of each employee who has a dependent with the same first
name and same sex as the employee
SQL> select e.sname,e.lname from emp e where e.essn in(select essn from dependent
where e.sname=depname and e.gender=gender);
SNAME
LNAME
19

-------------------- -------------------sam
raj
9. Find the sum of the salaries of all employees of the Research department, as
well as the maximum salary, the minimum salary, and the average salary in this
department.
SQL> select sum(salary),max(salary),min(salary),avg(salary) from emp,deptmt where
deptmt.depno=emp.depno and deptmt.dname='research';
SUM(SALARY) MAX(SALARY) MIN(SALARY) AVG(SALARY)
----------- ----------- ----------- ----------20000
20000
20000
20000
10. Count the number of distinct salary values in the database
SQL> select count(distinct salary) from emp;
COUNT(DISTINCTSALARY)
--------------------3
11. Retrieve the total number of employees in the company and the number of
employees in the Research department.
SQL> select count(*) from emp,deptmt where deptmt.depno=emp.depno and
deptmt.dname='research';
COUNT(*)
---------1
12. Find all employees who were born during the 1950s
SQL> select sname,lname from emp where extract(year from dob)=1950;
SNAME
LNAME
-------------------- -------------------john
smith

Ex. No. 3

ER MODEL

20

AIM:

To construct ER Diagram for the following situations.


The company is organized into departments. Each department has unique
name, unique number and a particular employee who manages the department.
Keep track of the start date when the employee begins managing the
departments. The department may be in several locations. The department
controls no.of projects each of which has unique number and single location.
Store each employees name, number, address, salary, gender and date of birth.
An employee is assigned to one department but may work on several projects
which are not necessarily controlled by the same department. Keep track of
the no.of hours per week that an employee works on each project. Also keep
track of the direct supervisor of each employee. Keep track of the dependence
of each employee for insurance purpose. Keep each dependence first name,
gender, date of birth and relationship to that employee.

USER REQUIREMENTS:
ENTITIES:
Employee(name,number,address,gender,dob);
Department(name,deptno,location)
Project(projname,projno,location)
Dependence(name,gender,dob,relationship)
RELATIONSHIP:

Worksfor(number,deptno)
Workson(hours,projno,number)
Supervises(number)
Manages(startdate,deptno,number,name)
Controlledby(deptno,projno)
Dependent(number,name)

ER MODEL FOR EMPLOYEE DATABASE


Street
City
21

Gender

address

nam
e

nam
e

dep
tno
Employee

Department
w
fo orks
r

name

DOJ
e
nag
ma
s

location
pro
jno

Project
o ll
r
t
n
Co by
ed

Dependence
Wo
s o rk
n

Su
ise perv
s

Number

hours
Gender

22

DOB

relationshi
p

Name

De
s o pen
n d

DO
B

locatio
n

Ex. No. 4

TRIGGERS

AIM:
To Create the following table
1. Books(ISBN,Title,Author,Price,Pub_year)
2. Stock(ISBN,Stock_quantity,reorderlevel,reorderquantity)
3. Customers(Custid,custname,address)
4. Orders(orderno,custid,orderdate)
5. Orderlist(orderno,ISBN,quantity,totalprice,shipdate)
QUERIES:
SQL> create table books(isbn number(5) primary key,title varchar(25),author
varchar(20),price number (5,2),pubyear number(4));
Table created.
SQL> create table stock(isbn number(5) references books(isbn));
Table created.
SQL> alter table stock add(stockquantity number(4),reorderlevel
number(3),reorderquantity number(4));
Table altered.
SQL> create table customers(custid number(5) primary key,cname
varchar(25),address varchar(25));
Table created.
SQL> create table orders(orderno number(4) primary key,custid number(5)
references customers(custid) ,orderdate date);
Table created.
SQL> create table orderlist(orderno number(4) references orders(orderno),isbn
number(5) primary key, quantity number(5),totalprice number(5,2),shipdate date);
Table created.
SQL> insert into books values(&isbn,'&title','&author',&price,&pubyear);
Enter value for isbn: 10001

23

Enter value for title: dbms


Enter value for author: date
Enter value for price: 500
Enter value for pubyear: 2005
old 1: insert into books values(&isbn,'&title','&author',&price,&pubyear)
new 1: insert into books values(10001,'dbms','date',500,2005)
1 row created.
SQL> select * from books;
ISBN TITLE

AUTHOR

PRICE PUBYEAR

---------- ------------------------- -------------------- ---------- ---------10001 dbms

date

10002 data structure

500

weiss

10003 cryptography

2005

700

stallings

400

2002
2006

SQL> insert into stock


values(&isbn,&stockquantity,&reorderlevel,&reorderquantity);
Enter value for isbn: 10001
Enter value for stockquantity: 10
Enter value for reorderlevel: 3
Enter value for reorderquantity: 5
old 1: insert into stock
values(&isbn,&stockquantity,&reorderlevel,&reorderquantity)
new 1: insert into stock values(10001,10,3,5)
1 row created.
SQL> select * from stock;
ISBN STOCKQUANTITY REORDERLEVEL REORDERQUANTITY
---------- ------------- ------------ --------------10001

10

10002

20

10

10

10003

15

SQL> insert into customers values(&custid,'&cname','&address');


Enter value for custid: 1
Enter value for cname: siva
Enter value for address: madurai

24

old 1: insert into customers values(&custid,'&cname','&address')


new 1: insert into customers values(1,'siva','madurai')
1 row created.
SQL> select * from customers;
CUSTID CNAME

ADDRESS

---------- ------------------------- ------------------------1 siva

madurai

2 raja

theni

3 kalai

salem

SQL> insert into orders values(&orderno,&custid,'&orderdate');


Enter value for orderno: 101
Enter value for custid: 1
Enter value for orderdate: 01-jan-2010
old 1: insert into orders values(&orderno,&custid,'&orderdate')
new 1: insert into orders values(101,1,'01-jan-2010')
1 row created.
SQL> select * from orders;
ORDERNO

CUSTID ORDERDATE

---------- ---------- --------101

1 01-JAN-10

102

1 05-JUN-10

103

3 18-AUG-10

a. Fire a trigger before insert whenever the ordered quantity is less than the
available stock quantity or the shipdate is less than the orderdate then
display the message The ordered quantity is not available or shipping date
should be greater than order date respectively.
SQL> set serveroutput on;
SQL> create or replace trigger trigger1
2 before insert on orderlist for each row
3 declare
4 qn number(5);
5 dat date;
6 begin
7 select stockquantity into qn from stock where isbn=:new.isbn;
25

8 select orderdate into dat from orders where orderno=:new.orderno;


9 if :new.quantity>qn then
10 dbms_output.put_line('ordered quantity is not available');
11 end if;
12 if months_between(:new.shipdate,dat)<0 then
13 dbms_output.put_line('ordered date is greater than shipment date');
14 end if;
15 end;
16 /
Trigger created.
SQL> insert into orderlist
values(&orderno,&quantity,&totalprice,'&shipdate',&isbn);
Enter value for orderno: 102
Enter value for quantity: 15
Enter value for totalprice: 1000
Enter value for shipdate: 01-mar-2010
Enter value for isbn: 10001
old 1: insert into orderlist
values(&orderno,&quantity,&totalprice,'&shipdate',&isbn)
new 1: insert into orderlist values(102,15,1000,'01-mar-2010',10001)
1 row created.
b. Fire a trigger after update of price, when the new price is greater than the old
price, update the total price of the corresponding isbn number.
SQL> Create or replace trigger trigger3
2 After update on books for each row
3 When(new.price>old.price)
4 Begin
5 Update orderlist set totalprice=:new.price*quantity where isbn=:new.isbn;
6 End;
7
8 /
Trigger created.
SQL> update books set price=600 where isbn=10001;

26

1 row updated.
SQL> select * from orderlist;
ORDERNO QUANTITY TOTALPRICE SHIPDATE

ISBN

---------- ---------- ---------- --------- ---------101

1800 01-MAR-10

10001

102

15

9000 01-MAR-10

10001

101

1200 01-JAN-09

10001

c. Fire a trigger after delete of an order from the orders table, which would
delete the corresponding order from the orderlist table.
SQL> Create or replace trigger trigger4
2 After delete on orders for each row
3 Begin
4 Delete from orderlist where orderno=:old.orderno;
5 End;
6 /
Trigger created.
SQL> select * from orders;
ORDERNO

CUSTID ORDERDATE

---------- ---------- --------101

1 01-JAN-10

102

1 05-JUN-10

103

3 18-AUG-10

SQL> delete from orders where orderno=102;


1 row deleted.
SQL> select * from orderlist;
ORDERNO QUANTITY TOTALPRICE SHIPDATE
---------- ---------- ---------- --------- ---------101

1800 01-MAR-10

101

1200 01-JAN-09

10001
10001

27

ISBN

Ex. No. 5

NESTED SUBQUERIES

AIM:
To perform nested sub queries in book database.
QUERIES:
1. Find the books whose price is between 300 and 400
SQL> select * from books where price between 300 and 400;
ISBN TITLE
AUTHOR
PRICE PUBYEAR
---------- ------------------------- -------------------- ---------- ---------10003 cryptography
stallings
400
2006
2. Find the title, author name, stock quantity and price and pub year of the
books which are ordered.
SQL> select * from books b where exists(select * from orderlist o where
b.isbn=o.isbn);
ISBN TITLE
AUTHOR
PRICE PUBYEAR
---------- ------------------------- -------------------- ---------- ---------10001 dbms
date
600
2005
3. Find the sum of the price of the books published in the year.
SQL> select sum(price) from books group by pubyear;
SUM(PRICE)
---------700
600
400
4. Find the sum of the price of the books published in the year and having price
>500
SQL> select sum(price),pubyear from books group by pubyear having
sum(price)>500;
SUM(PRICE) PUBYEAR
---------- ---------700
2002
600
2005
5. Find the isbn of the books which may or may not ordered using union
operation
SQL> (select isbn from books)union(select isbn from orderlist);
ISBN
---------10001

28

10002
10003
6. Find the isbn of the books which are ordered using intersect operations
SQL> (select isbn from books)intersect(select isbn from orderlist);
ISBN
---------10001
7. Find the customer name,orderdate,orderno using natural join.
SQL> select c.cname,c.address,o.orderdate,o.orderno from customers c,orders
o where c.custid=o.custid;
CNAME
ADDRESS
ORDERDATE ORDERNO
------------------------- ------------------------- --------- ---------siva
madurai
01-JAN-10
101
kalai
salem
18-AUG-10
103
8. Retrieve customername,orderno using left outer join.
SQL> select c.cname,o.orderno from customers c,orders o where
c.custid=o.custid(+);
CNAME
ORDERNO
------------------------- ---------siva
101
raja
kalai
103
9. Retrieve orderno,customername using right outer join
SQL> select c.cname,o.orderno from customers c,orders o where
c.custid(+)=o.custid;
CNAME
ORDERNO
------------------------- ---------siva
101
kalai
103

29

Ex. No. 6

PL/SQL PROCEDURES AND FUNCTIONS

AIM:
To write a PL/SQL procedure and functions for various operations
PL/SQL PROCEDURES:
a) WRITE A PL/SQL PROGRAM TO FIND THE SUM OF DIGITS IN A
GIVEN NUMBER
SQL> ed armstrong.sql
declare
a number;
t number;
arm number;
d number;
begin
a:=&a;
t:=a;
arm:=0;
while t>0
loop
d:=mod(t,10);
arm:=arm+power(d,3);
t:=trunc(t/10);
end loop;
if arm=a then
dbms_output.put_line('given no is an armstrong no'|| a);
else
dbms_output.put_line('given no is not an armstrong no');
end if;
end;
/
SQL> @ armstrong.sql
Input truncated to 1 characters
Enter value for a: 2342
old 7: a:=&a;
new 7: a:=2342;
given no is not an armstrong no
PL/SQL procedure successfully completed.
SQL> /
Enter value for a: 153
old 7: a:=&a;
new 7: a:=153;
given no is an armstrong no153
PL/SQL procedure successfully completed.
30

b) WRITE A PL/SQL PROGRAM TO DISPLAY THE NUMBER IN REVERSE


ORDER
SQL> ed reverse.sql
declare
a number;
rev number;
d number;
begin
a:=&a;
rev:=0;
while a>0
loop
d:=mod(a,10);
rev:=(rev*10)+d;
a:=trunc(a/10);
end loop;
dbms_output.put_line('no is'|| rev);
end;
/
SQL> @ reverse.sql
Input truncated to 1 characters
Enter value for a: 34566
old 6: a:=&a;
new 6: a:=34566;
no is66543
PL/SQL procedure successfully completed.
c) WRITE A PL/SQL PROGRAM TO CHECK WHETHER THE GIVEN
NUMBER IS PRIME OR NOT
SQL> ed prime.sql
declare
a number;
c number:=0;
i number;
begin
a:=&a;
for i in 1..a
loop
if mod(a,i)=0 then
c:=c+1;
end if;
end loop;
if c=2 then
dbms_output.put_line(a ||'is a prime number');
else
dbms_output.put_line(a ||'is not a prime number');
end if;
end;

31

/
SQL> @ prime.sql
Input truncated to 1 characters
Enter value for a: 11
old 6: a:=&a;
new 6: a:=11;
11is a prime number
PL/SQL procedure successfully completed.
d) WRITE A PL/SQL PROGRAM TO FIND THE FACTORIAL OF A GIVEN
NUMBER
SQL> ed factorial.sql
declare
n number;
f number:=1;
begin
n:=&n;
for i in 1..n
loop
f:=f*i;
end loop;
dbms_output.put_line('the factorial is'|| f);
end;
/
SQL> @ factorial.sql
Input truncated to 1 characters
Enter value for n: 5
old 5: n:=&n;
new 5: n:=5;
the factorial is120
PL/SQL procedure successfully completed.
e) WRITE A PL/SQL PROGRAM TO GENERATE FIBONACCI SERIES
SQL> ed fibo.sql
declare
a number;
b number;
c number;
n number;
i number;
begin
n:=&n;
a:=0;
b:=1;
dbms_output.put_line(a);
dbms_output.put_line(b);
for i in 1..n-2
loop

32

c:=a+b;
dbms_output.put_line(c);
a:=b;
b:=c;
end loop;
end;
/
SQL> @ fibo.sql
Input truncated to 1 characters
Enter value for n: 5
old 8: n:=&n;
new 8: n:=5;
0
1
1
2
3
PL/SQL procedure successfully completed.
f) WRITE A FUNCTION TO FIND FACTORIAL OF A NUMBER
SQL> ed func.sql
create or replace function fact(n number)return number
as
fac number:=1;
begin
for i in 1..n
loop
fac:=fac*i;
end loop;
return fac;
end;
/
SQL> @ func.sql
Input truncated to 1 characters
Function created.
SQL> select fact(7) from dual;
FACT(7)
---------5040
SQL>

33

Ex. No. 7

PL/SQL CURSOR

AIM :
To create PL/SQL cursor for payroll processing of an employee.
QUERIES:
SQL> create table empl(empno number(5),ename varchar(20),dob date,basicpay
number(5),da number(5),al
lowance number(5),tax number(5),lic number(5),grosspay number(5));
Table created.
SQL> insert into empl
values(&empno,'&ename','&dob',&basicpay,&da,&allowance,&tax,&lic,&grosspay);
Enter value for empno: 101
Enter value for ename: siva
Enter value for dob: 01-aug-2000
Enter value for basicpay: 10000
Enter value for da: 4000
Enter value for allowance: 2000
Enter value for tax: 1000
Enter value for lic: 1200
Enter value for grosspay: 0
old 1: insert into empl
values(&empno,'&ename','&dob',&basicpay,&da,&allowance,&tax,&lic,&grosspay
new 1: insert into empl values(101,'siva','01-aug2000',10000,4000,2000,1000,1200,0)
1 row created.
SQL> select * from empl;
EMPNO ENAME
DOB
BASICPAY
DA ALLOWANCE
---------- -------------------- --------- ---------- ---------- ---------TAX
LIC GROSSPAY
---------- ---------- ---------101 siva
01-AUG-00
10000
4000
2000
1000
1200
0
102 raja
2000
2600

11-MAR-01
0

20000

7000

SQL> declare
2 cursor c is select * from empl order by grosspay desc;
3 rec empl % rowtype;
4 cnt integer:=0;
5 begin
34

3000

6 open c;
7 loop
8 fetch c into rec;
9 exit when c% notfound;
10 if(cnt<5) then
11 update empl set grosspay=(rec.basicpay+rec.da+rec.allowance)-(rec.lic+rec.tax)
where empno=rec.empno;
12 dbms_output.put_line('Employee no:'||rec.empno);
13 dbms_output.put_line('name:'||rec.ename);
14 dbms_output.put_line('Basic pay:'||rec.basicpay);
15 dbms_output.put_line('DA:'||rec.da);
16 dbms_output.put_line('allowance:'||rec.allowance);
17 dbms_output.put_line('Tax:'||rec.tax);
18 dbms_output.put_line('LIC:'||rec.lic);
19 dbms_output.put_line('Grosspay:'||rec.grosspay);
20 cnt:=cnt+1;
21 end if;
22 end loop;
23 close c;
24 end;
25 /
Employee no:101
name:siva
Basic pay:10000
DA:4000
allowance:2000
Tax:1000
LIC:1200
Grosspay:0
Employee no:102
name:raja
Basic pay:20000
DA:7000
allowance:3000
Tax:2000
LIC:2600
Grosspay:0
PL/SQL procedure successfully completed.
SQL> select * from empl;
EMPNO ENAME
DOB
BASICPAY
DA ALLOWANCE
---------- -------------------- --------- ---------- ---------- ---------TAX
LIC GROSSPAY
---------- ---------- ---------101 siva
01-AUG-00
10000
4000
2000
1000
1200
13800
102 raja
11-MAR-01
20000
7000
3000
2000
2600
25400

35

Ex. No. 8

PL/SQL FUNCTIONS & PROCEDURES

AIM:
To write PL/SQL functions and procedures to retrieve records from table.
QUERIES:
1.

a) Create the table account with attributes accno, date, balance.


b) Create the table branch with attributes branch name,location,assets.
c) Create the table customer with the attributes ID, name, address.
d) Create the table depositer with the attributes accno, custid, bname.
e) Create the table employee with the attributes empno, name, address,
Pay, qualification and department .

create table branch( bname varchar(30), loc char(20), assets varchar(30));


create table account(accno integer primary key,accdate date,balance integer);\
create table customer(custid integer primary key, cname char(20), address char(20));
create table depositer(accno integer references account(accno), custid integer
references customer(custid), bname char(20));
create table emp1(empno integer primary key, empname char(20), address
char(20),Pay integer, qualification varchar(30));
SQL> insert into branch values('&bname','&loc','&assets');
Enter value for bname: TMB VNR
Enter value for loc: virudhunagar
Enter value for assets: 10 lakh
old 1: insert into branch values('&bname','&loc','&assets')
new 1: insert into branch values('TMB VNR','virudhunagar','10 lakh')
1 row created.
SQL> select * from branch;
BNAME
LOC
------------------------------ -------------------ASSETS
-----------------------------TMB VNR
virudhunagar
10 lakh
SBI MDU
50 lakh
AXIS CHN
50 lakh

madurai
Chennai

36

SQL> insert into account values(&accno,'&accdate',&balance);


Enter value for accno: 30501
Enter value for accdate: 10-mar-2010
Enter value for balance: 4000
old 1: insert into account values(&accno,'&accdate',&balance)
new 1: insert into account values(30501,'10-mar-2010',4000)
1 row created.
SQL> select * from account;
ACCNO ACCDATE
BALANCE
---------- --------- ---------30501 10-MAR-10
4000
20301 05-APR-10
5000
10304 07-JAN-11 12000
SQL> insert into customer values(&custid,'&cname','&address');
Enter value for custid: 10
Enter value for cname: mani
Enter value for address: madurai
old 1: insert into customer values(&custid,'&cname','&address')
new 1: insert into customer values(10,'mani','madurai')
1 row created.
SQL> select * from customer;
CUSTID CNAME
ADDRESS
---------- -------------------- -------------------10 mani
madurai
102 hari
sivakasi
302 anu
theni
SQL> insert into depositer values(&accno,&custid,'&bname');
Enter value for accno: 30501
Enter value for custid: 10
Enter value for bname: TMB VNR
old 1: insert into depositer values(&accno,&custid,'&bname')
new 1: insert into depositer values(30501,10,'TMB VNR')
1 row created.
SQL> select * from depositer;
ACCNO CUSTID BNAME
---------- ---------- -------------------30501
10 TMB VNR
20301
302 SBI MDU
SQL> insert into emp1
values(&empno,'&empname','&address',&pay,'&qualification');
Enter value for empno: 151
Enter value for empname: rahul
Enter value for address: virudhunagar

37

Enter value for pay: 20000


Enter value for qualification: asst.manager
old 1: insert into emp1
values(&empno,'&empname','&address',&pay,'&qualification')
new 1: insert into emp1 values(151,'rahul','virudhunagar',20000,'asst.manager')
1 row created.
SQL> select * from emp1;
EMPNO EMPNAME
ADDRESS
---------- -------------------- -------------------- ---------QUALIFICATION
-----------------------------151 rahul
virudhunagar
20000
asst.manager
157 lilly
manager
200 gayathri
clerk

madurai

PAY

40000

madurai

10000

2. Write a PL/SQL function to display assets if the branch name is given.


SQL> create or replace function f1(newbname varchar)
2 return varchar
3 is
4 newassets varchar(30);
5 BEGIN
6 select assets into newassets from branch where bname=newbname;
7 return newassets;
8 END;
9 /
Function created.
Output
SQL> set serveroutput on;
SQL> BEGIN
2 dbms_output.put_line(f1('TMB VNR')); end;
3 /
10 lakh
PL/SQL procedure successfully completed.
3. Write a PL/SQL function to calculate income tax for given employee
number calculations as
a) If pay is between 0 to 10000 then no income tax is charged.
b) If pay is between 10000 to 20000 then 20% of pay is charged as tax.
c) If pay is between 21000 to 50000 then 35% of pay is charged as tax.
d) If pay is greater than 50,000 then 40% of pay is charged as tax.

38

SQL> create or replace function f2(neweno integer)


2 return integer
3 is
4 newitax integer;
5 pay1 integer;
6 BEGIN
7 select pay into pay1 from emp1 where empno=neweno;
8 if(pay1<10000) then
9 newitax:=0.1*pay1;
10 elsif(pay1>10000 and pay1<20000) then
11 newitax:=0.2*pay1;
12 elsif(pay1>20000 and pay1<50000) then
13 newitax:=0.35*pay1;
14 else
15 newitax:=0.4*pay1;
16 return newitax;
17 end if;
18 end;
19 /
Function created.
output
SQL> BEGIN
2 dbms_output.put_line(f2(151));
3 END;
4 /
8000
PL/SQL procedure successfully completed.
4. Write a PL/SQL function to display the number of accounts in the
Particular branch.
SQL> create or replace function f3(nbname char)
2 return integer
3 is
4 naccno integer;
5 begin
6 select count(accno) into naccno from depositer where bname=nbname;
7 return naccno;
8 end;
9 /
Function created.
SQL> begin
2 dbms_output.put_line(f3('TMB VNR'));
3 end;
4 /

39

2
PL/SQL procedure successfully completed.
5. Write a PL/SQL procedure to display the number of accounts opened by a
customer.
SQL> create or replace procedure cusa(vcname char)
2 is
3 vno integer;
4 BEGIN
5 select count(*) into vno from depositer,customer where
depositer.custid=customer.custid and cus
tomer.cname=vcname;
6 dbms_output.put_line(vno);
7 END;
8 /
Procedure created.
SQL> exec cusa('mani');
3
PL/SQL procedure successfully completed.
6. Write a PL/SQL procedure to display the total amount deposited in branch.
SQL> create or replace procedure bal(nbname char)
2 is
3 namt integer;
4 begin
5 select sum(balance) into namt from depositer,account where
6 depositer.bname=nbname and account.accno=depositer.accno;
7 dbms_output.put_line(namt);
8 end;
9 /
Procedure created.
SQL> exec bal('TMB VNR');
16000
PL/SQL procedure successfully completed.

40

Ex. No. 9

VIEWS

AIM:
To create view for the bank database and do manipulation on that view.
QUERIES;
1. Create a view with the attributes accno,custid,balance,bname from the table
account.depositor
SQL> create view view1 as (select
account.accno,account.balance,depositer.custid,depositer.bname fro
m account,depositer where account.accno=depositer.accno);
View created.
SQL> select * from view1;
ACCNO BALANCE CUSTID BNAME
---------- ---------- ---------- -------------------30501
4000
10 TMB VNR
20301
5000
302 SBI MDU
2. Create a view view2 with a all attributes from the table customer and
depositor
SQL> create view view2 as select c.custid,c.cname,c.address,d.accno,d.bname
from customer c,depositer d where c.custid=d.custid;
View created.
SQL> select * from view2;
CUSTID CNAME
ADDRESS
ACCNO
---------- -------------------- -------------------- ---------BNAME
-------------------10 mani
madurai
30501
TMB VNR
302 anu
SBI MDU

theni

10 mani
AXIS CHN

madurai

20301
10304

CUSTID CNAME
ADDRESS
ACCNO
---------- -------------------- -------------------- ---------BNAME
-------------------10 mani
madurai
10304
41

TMB VNR
SQL>
3. Create a View view3 for the employee residing at madurai
SQL> create view view3 as select * from emp1 where address='madurai';
View created.
SQL> select * from view3;
EMPNO EMPNAME
ADDRESS
---------- -------------------- -------------------- ---------QUALIFICATION
-----------------------------157 lilly
madurai
40000
manager
200 gayathri
clerk

madurai

PAY

10000

4. Insert a new record in view 3


SQL> insert into view3
values(&empno,'&empname','&address',&pay,'&qualification');
Enter value for empno: 120
Enter value for empname: sandeep
Enter value for address: sivakasi
Enter value for pay: 12000
Enter value for qualification: accountant
old 1: insert into view3
values(&empno,'&empname','&address',&pay,'&qualification')
new 1: insert into view3 values(120,'sandeep','sivakasi',12000,'accountant')
1 row created.
SQL> select * from view3;
EMPNO EMPNAME
ADDRESS
---------- -------------------- -------------------- ---------QUALIFICATION
-----------------------------157 lilly
madurai
40000
manager
200 gayathri
clerk

madurai

PAY

10000

SQL> select * from emp1;


EMPNO EMPNAME
ADDRESS
---------- -------------------- -------------------- ---------QUALIFICATION
-----------------------------151 rahul
virudhunagar
20000

42

PAY

asst.manager
157 lilly
manager
200 gayathri
clerk

madurai

40000

madurai

10000

EMPNO EMPNAME
ADDRESS
---------- -------------------- -------------------- ---------QUALIFICATION
-----------------------------120 sandeep
sivakasi
12000
accountant

PAY

5. Update the branch name of the customer anu to AXIS CHN in view2.
SQL> update view2 set bname='AXIS CHN' where cname='anu';
1 row updated.
SQL> select * from view2;
CUSTID CNAME
ADDRESS
ACCNO
---------- -------------------- -------------------- ---------BNAME
-------------------10 mani
madurai
30501
TMB VNR
302 anu
AXIS CHN

theni

10 mani
AXIS CHN

madurai

20301
10304

CUSTID CNAME
ADDRESS
ACCNO
---------- -------------------- -------------------- ---------BNAME
-------------------10 mani
madurai
10304
TMB VNR
SQL> select * from depositer;
ACCNO CUSTID BNAME
---------- ---------- -------------------30501
10 TMB VNR
20301
302 AXIS CHN
10304
10 AXIS CHN
10304
10 TMB VNR

43

6. Delete the account no 30501 details from view1.


SQL> delete from view1 where accno=30501;
1 row deleted.
SQL> select * from view1;
ACCNO BALANCE CUSTID BNAME
---------- ---------- ---------- -------------------20301
5000
302 AXIS CHN
10304
12000
10 AXIS CHN
10304
12000
10 TMB VNR
SQL> select * from depositer;
ACCNO CUSTID BNAME
---------- ---------- -------------------20301
302 AXIS CHN
10304
10 AXIS CHN
10304
10 TMB VNR

44

Ex. No. 10

DYNAMIC SQL

AIM:
To access and manipulate database through java program.
Program:
import java.io.*;
import java.sql.*;
class dynamicsql
{
public static void main(String s[]) throws Exception
{
Connection con;
Statement st;
ResultSet rs;
PreparedStatement ps,ps1;
int ch;
try
{
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
con=DriverManager.getConnection("jdbc:odbc:emp2","test","test");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("DB connected");
while(true)
{
System.out.println("1.insert\n2.display\n3.exit");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("enter employee id");
int empid=Integer.parseInt(br.readLine());
System.out.println("enter employee name");
String name=br.readLine();
System.out.println("enter address");
String address=br.readLine();
ps=con.prepareStatement("insert into emp2 values(?,?,?)");
ps1=con.prepareStatement("commit");
ps.setInt(1,empid);
ps.setString(2,name);
ps.setString(3,address);
ps.executeUpdate();
ps1.execute();
break;
case 2:
st=con.createStatement();
45

rs=st.executeQuery("select * from emp2");


System.out.println("\nempid\tname\taddress\n");
while(rs.next())
{
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.println();
}
st.close();
break;
case 3:
System.exit(0);
break;
default:
break;
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
C:\jdk1.3\bin>java dynamicsql
DB connected
1.insert
2.display
3.exit
1
enter employee id
101
enter employee name
siva
enter address
madurai
1.insert
2.display
3.exit
1
enter employee id
102
enter employee name
raja
enter address
sivakasi
1.insert

46

2.display
3.exit
2
empid name

address

101 siva madurai


102 raja sivakasi
1.insert
2.display
3.exit
C:\jdk1.3\bin>

47

Ex. No. 11

MENU DRIVEN APPLICATION USING VB

AIM:
To Access and manipulate database through visual basic.
PROCEDURE:

Click Start-> Settings-> Control panel.


Select Administrative tools -> Data sources(ODBC).
Click Add -> Select Microsoft ODBC for oracle -> Finish.
Click Program -> Microsoft Visual studio -> Select Visual studio basic
6.0
In this select standard project and Click Open.
In the form we can design using labels and Text boxes.
Find Select Project-> Components.
Select Microsoft ADO data control 6.0(OLE DB) and Click Apply.
Drag the ADODC and place in the form.
ADODC-> Properties -> Connection string-> Built.
In this Select Microsoft OLE DB provider for OLDBC driver -> Click
Next.
Give the table name in data source name and also give username and
password -> Click test connection -> Ok -> Apply.
Click Authentication -> Username, Password.
Click Record source -> Odcmd table -> Select the table name (EMP2)
-> Ok.
Set the textbox Property as Data Source -> Right click -> ADODC.
Data field -> <Column name> (empid)
Click project -> ADD MDI FORM.
MDI form will be displayed.
In this right click and select menu & editor create FORM & REPORT
Menu.
Click Project -> select Project1 Properties.
Set Startup Project as MDI form.
Set the form1 and report as child for MDI form by Form1 -> Properties> MDI child -> True.
Click Project- > Components->Designer select Data environment &
Data report -> Click apply ->Ok
Click Project->Data environment -> Connection1 right click select
properties right click select properties right click select ADD cmd
Click project -> Data report -> Add data report -> Add Data report

48

Data report properties set


Data source -> Data environment
Data member -> Command
In MDI form set the text box properties data members
Write the coding for each and every buttons
Run the project.
CODING:
ADD:
Private sub commands_click()
Adodc1.Recordset.Addnew
End sub
EDIT:
Private sub commands_click()
Adodc1.Recordset.Update
End sub
CLEAR:
Private sub commands_click()
Text1.text=
Text2.text=
Text3.text=
End sub
DELETE:
Private sub commands_click()
Adodc1.Recordset.Delete
End sub
FIRST:
Private sub commands_click()
Adodc1.Recordset.Move first
End sub
LAST:
Private sub commands_click()
Adodc1.Recordset.Move last
End sub
NEXT:
Private sub commands_click()
Adodc1.Recordset.Move next
End sub
PREVIOUS:
Private sub commands_click()
Adodc1.Recordset.Move previous
End sub
FORM:
Private sub mnu_depart_click()
Form1.show
49

End sub
REPORT:
Private sub-mnu employee_click()
Data report1.show
End sub

50

51

52

S-ar putea să vă placă și