Anda di halaman 1dari 107

CS8481 DATABASE MANAGEMENT SYSTEMS LABORATORY LT P

C
0 0
42
AIM:

The aim of this laboratory is to inculcate the abilities of applying the principles of the
database management systems. This course aims to prepare the students for projects where a proper
implementation of databases will be required.

OBJECTIVES:
 To understand data definitions and data manipulation commands
 To learn the use of nested and join queries
 To understand functions, procedures and procedural extensions of data bases
 To be familiar with the use of a front end tool
 To understand design and implementation of typical database applications

LIST OF EXPERIEMENTS
1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating and
retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications
TOTAL: 60 PERIODS

OUTCOMES:

Upon completion of the course, the students will be able to:

 Use typical data definitions and manipulation commands.


 Design applications to test Nested and Join Queries
 Implement simple applications that use Views
 Implement applications that require a Front-end Tool
 Critically analyze the use of Tables, Views, Functions and Procedures

1
LIST OF EXPERIMENTS:

1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating and
retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications

BEYOND SYLLABUS

1. Embedded SQL programs.


2. Packages

MINI PROJECT

1. Time Table Management System

2
VEL TECH MULTI TECH
Dr. RANGARAJAN Dr. SAKUNTHALA ENGINEERING COLLEGE

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


COURSE PLAN
Regulation – 2017
Course/Branch : B.E/ CSE Total no. of hours given in
syllabus:
Subject Code : CS 8481 Lecture : 0
Subject Title : Database Management Systems Laboratory Tutorials : 0
Year/Semester : II/IV Practical : 60
Faculty Name : TOTAL : 60

COURSE OBJECTIVES:

1. To understand data definitions and data manipulation commands


2. To learn the use of nested and join queries
3. To understand functions, procedures and procedural extensions of data bases
4. To be familiar with the use of a front end tool
5. To understand design and implementation of typical database applications

Ex. Allotted
Experiment Name CO Mapping
No. hours
Data Definition Commands, Data Manipulation Commands for
6 Hours
1 inserting, deleting, updating and retrieving Tables and CO1
Transaction Control statements.

2 Database Querying – Simple queries, Nested queries, Sub 6 Hours


CO2
queries and Joins.
3 Hours
3 Views, Sequences, Synonyms. CO2
3 Hours
4 Database Programming: Implicit and Explicit Cursors. CO3

6 Hours
5 Procedures and Functions. CO3

6 Triggers. 6 Hours CO3

3
6 Hours
7 Exception Handling . CO3

8 Database Design using ER modeling, normalization and 9 Hours CO5


Implementation for any application.
6 Hours
9 Database Connectivity with Front End Tools. CO4

3 Hours
10 Case Study using real life database applications. CO4

Content Beyond Syllabus

1. Embedded SQL 3 Hours PSO2

2. Packages 3 Hours PSO1

Course Outcome:

Course Name: Database Management Systems Lab Year of Study: 2018-19

CS8481.1 Use typical data definitions and manipulation commands.

CS8481.2 Design applications to test Nested and Join Queries


SEM
IV CS8481.3 Implement simple applications that use Views

CS8481.4 Implement applications that require a Front-end Tool

CS8481.5 Critically analyze the use of Tables, Views, Functions and Procedures
CS8481.6 Normalized database design to ensure the quality

4
Ex. 1. Data Definition Commands, Data Manipulation Commands for
inserting, deleting, updating and retrieving Tables and Transaction Control
statements

Aim : To create database and perform DML and TCL queries to retrieve information from the
database.

BACKGROUND THEORY:

Different types of commands in SQL:

 DDL commands: - To create a database objects.


 DML commands: - To manipulate data of a database objects.
 TCL Commands – To manage changes and save a database

Data Definition Language (DDL): To specify the database schema.


DDL Commands:
 Create
 Alter
 Rename
 Drop

1. Creation of Table: Creates a table with specified attributes and its data type along with
constraints.
Syntax:
Create table r (A1 D1 , A2 D2,………An Dn,
(integrity-constraint1),
….,
(integrity-constraintk));
where r – relation name(Table name),
Ai – Attribute name,
Di – Data type.
Data Types in SQL:

5
1. char(n) : Fixed-length character string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255 characters
2. varchar(n) : Variable-length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note:
If you put a greater value than 255 it will be converted to a TEXT type
3. int : Integer -2147483648 to 2147483647 normal. 0 to 4294967295. The maximum
number of digits may be specified in parenthesis
4. smallint : Small Integer -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
5. numeric(p,d) : The number consists of p digits(plus a sign), d of the p digits are to
the right of the decimal point.
6. float(n,d) : Floating-point number. The maximum number of digits may be
specified in the size parameter. The maximum number of digits to the right of the decimal point
is specified in the d parameter
7. double (size,d): A large number with a floating decimal point. The maximum
number of digits may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter.
8. date : The date containing a date, month and year. Used to store date value as
DD-MON-YY, data size is 9 byte
Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
9. time : The time in hours, minutes and seconds.
Format: HH:MM:SS
10. timestamp : The combination of date and time.
Format: YYYY-MM-DD HH:MM:SS

Eg: Create a customer table which consists of 4 columns:


i) custID - Customer ID – Integer – Primary Key
ii) custname – Customer Name – varchar2 (15)
iii) custstreet – Customer Street – varchar2 (20)
iv) custcity – Customer City – varchar2 (10)
create table customer (
custID int,
custname varchar2(15),
custstreet varchar2(20),
custcity varchar2(10),Primary key (CustID));

2. To view the table structure:


Syntax:
desc r;
Ex:
Desc customer;

3. Retrieval of Information by Select Command

6
Syntax-
(i) Select A1,A2.. ,An from r1
(ii) Select * from r1;
(iii) Select A1,A2.. ,An from r1,r2,..,rn;
(iv) Select A1,A2.. ,An from r1,r2,..,rn where condition;

Example-
(i) Select CustID,Custname from customer ;
(ii) Select CustID,Custname from customer where Custname=’Arun’);

DDL Commands:

 Create
 Alter
 Rename
 Drop

Altering the Table Schema: Add or delete or change the attribute and data type.
It also can add or drop the integrity constraints.
Syntax:
1. Alter table r add (Ai Di);
2. Alter table r drop(Ai);
3. Alter table r modify(Ai Di);
4. Alter table r add primary key(Ai);
5. Alter table r enable primary key;
6. Alter table r disable primary key;
Eg:
Alter table customer add ( phoneno int(12));
Alter table customer drop( custcity);
Alter table customer modify( custname varchar2(20));
Alter table depositor add primary key(acctno);
Alter table depositor disable primary key;
Alter table depositor enable primary key;

Rename: Change the table name


Syntax:
Rename <tablename> to <newtablename>;
Eg:
Rename emp to employee;

Dropping the Table: Deletes all information and structure about that table(relation)
Syntax:

7
Drop table r;
Eg:
Drop table customer;

Data Manipulation Language (DML) – to express database queries and updates.

List of DML Commands:


1. Insertion of information
2. Retrieval of information
3. Deleting information
4. Modifying information

Two types of DML –

1. Procedural DMLs – requires a user to specify what data are needed and how to get
those data.
2. Declarative DMLs ( nonprocedural language) - requires a user to specify what data are
needed without specifying how to get those data.
DML Component of SQL language is nonprocedural language.

Query is a statement requesting the retrieval of information.

1. Insertion of information can be done in two ways -


(i) Syntax-
Insert into r values(V1, V2,…,Vn); // where Vi – Attribute Values
r - relation name (Table name)
Example-
Insert into customer values(101,’Arun’, ‘Bharathi Street’,’Chennai’);

(ii) Syntax-
Insert into r values(‘&A1’,’&A2’,….,’&An’); // where Ai – Attribute
Example-
Insert into customer values (‘&CustID’, ’&Custname’, ’&Custstreet’,
’&Custcity’);
2. Retrieval of Information by Select Command
(i) Syntax-
Select A1,A2.. ,An from r1,r2,..,rn where condition;
Example-
Select CustID,Custname from customer where Custname=’Arun’);

3. Modifying information by Update


Syntax-
Update r set A1=values;
Example-
Update customer set Custname=’babu’ where CustID=101;

8
4. Deletion of information-
Syntax-
Delete from r where condition;
Example-
Delete from customer where Custname=’Arun’;
5. Truncating a Table: Deletes the records and not the structure of a table.
Syntax:
Truncate table r;
Ex:
Truncate table customer;

Adding Constraints to the table


Constraints in SQL:
 NOT NULL
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
 CHECK
 DEFAULT

NOT NULL Constraints

 The NOT NULL constraint enforces a column to NOT accept NULL values.
 The NOT NULL constraint enforces a field to always contain a value. The following SQL
enforces the "P_Id" column and the "LastName" column to not accept NULL values:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(25)
)

UNIQUE Constraints

 The UNIQUE constraint uniquely identifies each record in a database table.


 The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness
for a column or set of columns.
 Note that you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.

9
Eg
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:

ALTER TABLE Persons


ADD UNIQUE (P_Id)

CHECK Constraints

 The CHECK constraint is used to limit the value range that can be placed in a column.
 If you define a CHECK constraint on a single column it allows only certain values for this
column.

 The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons"
table is created. The CHECK constraint specifies that the column "P_Id" must only include integers
greater than 0.

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)

To add a CHECK constraint, use the following SQL:

10
ALTER TABLE Persons
ADD CHECK (P_Id>0)

DEFAULT Constraints

 The DEFAULT constraint is used to insert a default value into a column.


 The following SQL creates a DEFAULT constraint on the "City" column when the
"Persons" table is created:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'chennai'
)

To create a DEFAULT constraint on the "City" column when the table is already created
without city column, use the following SQL:

ALTER TABLE Persons


add (City varchar(25) DEFAULT 'Chennai')

To drop a DEFAULT constraint, use the following SQL:

ALTER TABLE Persons


ALTER City DROP DEFAULT

PRIMARY KEY Constraints

 The PRIMARY KEY constraint uniquely identifies each record in a database table.
 Each table should have a primary key, and each table can have only one primary key.
 The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is
created:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
);

11
To add a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons


ADD PRIMARY KEY (P_Id)

Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s)
must already have been declared to not contain NULL values (when the table was first created).

To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons


DROP PRIMARY KEY

FOREIGN KEY Constraints

 The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
 The FOREIGN KEY constraint is used to prevent actions that would destroy link
between tables.

 The FOREIGN KEY constraint also prevents that invalid data is inserted into the foreign
key column, because it has to be one of the values contained in the table it points to

 A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

 Let's illustrate the foreign key with an example. Look at the following two tables:

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 2
4 24562 1

12
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons"
table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already
created, use the following SQL:

ALTER TABLE Orders


ADD FOREIGN KEY
REFERENCES Persons(P_Id)

Adding & Deleting the Constraints to the Table using constraint Names:

This example demonstrates how to specify constraints with constraint name during table
creation
create table salary_table (
fiscal_year varchar2(4) constraint nn_sal_year not null,
salary number constraint chk_sal_sal check (salary > 0 ),
fullname varchar2(64) constraint unq_sal_fullname unique,
emp_id varchar2(12) constraint fk_sal_emp_id references emp1(eno));

To disable a constraint, use the alter table command. To enable a disabled constraint, again
use the alter table command. The following examples disables and then re-enables the salary
check condition

alter table salary_table disable constraint chk_salary_salary;


alter table salary_table enable constraint chk_salary_salary;

The following example demonstrates how to drop the constraints using constraint name,
alter table salary_table drop constraint unq_sal_fullname;
alter table salary_table drop constraint chk_sal_sal;
alter table salary_table drop constraint nn_sal_year;
alter table salary_table drop constraint fk_sal_emp_id;

Transaction Control Language(TCL) commands


Transaction Control Language(TCL) commands are used to manage transactions in the database.
These are used to manage the changes made to the data in a table by DML statements. It also allows
statements to be grouped together into logical transactions.
COMMIT command
COMMIT command is used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by these
commands are not permanent, until the current session is closed, the changes made by these
commands can be rolled back.

13
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax,
COMMIT;
ROLLBACK command
This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and realise that
those changes were not required, then we can use the ROLLBACK command to rollback those
changes, if they were not commited using the COMMIT command.
Following is rollback command's syntax,
ROLLBACK TO savepoint_name;
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that
point whenever required.
Following is savepoint command's syntax,
SAVEPOINT savepoint_name;

In short, using this command we can name the different states of our data in any table and then
rollback to that state using the ROLLBACK command whenever required.
EXAMPLE :

SQL> select * from person;


PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ --------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.
SQL> commit;
Commit complete.

DELETE COMMAND
SQL> delete from person where lastname='Kumar';
2 rows deleted.
SQL> select * from person;

14
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------ --------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Hinn Benny Britain 55
5 Prakash Bhaskar Assam 40

SQL> rollback;
Rollback complete.

SQL> select * from person;


PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ -------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.
SQL> savepoint s1;
Savepoint created.
SQL> delete from person;
7 rows deleted.
SQL> select * from person;
no rows selected
SQL> rollback to savepoint s1;
Rollback complete.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------- -------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.

Lab Exercise

1. Create and describe the following tables:

15
A) NAME: branch
FIELDS DATATYPE
branch_name varchar2(30)
branch_city varchar2(30)
assets number(8,2)

B) NAME: account
FIELDS DATATYPE
account_no varchar2(11)
branch_name varchar2(30)
balance number(8)

C) NAME: customer
FIELD DATATYPE
customer_id varchar2(11)
customer_name varchar2(20)
customer_street varchar2(15)
customer_city varchar2(15)

D) NAME: depositor
FIELD DATATYPE
customer_id varchar2(11)
account_no varchar2(11)

E) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4)
branch_name varchar2(30)
amount number(8,2)

F) NAME: borrower
FIELDS DATATYPE
customer_id varchar2(11)
loan_no varcahr2(4)

2. Describe the structure of all database schemas.

3. Alter the structure of the Database

a. Add a new column ‘account opening date’ in the account table, which is of type Date.
b. Increase the width of the column customer_street in table customer to 20.

4. Add primary keys to all the tables for the specified attributes

16
A) NAME: branch
FIELDS DATATYPE
branch_name varchar2(30) primary key
branch_city varchar2(30)
assets number(8,2)

B) NAME: account
FIELDS DATATYPE
account_no varchar2(11) primary key
branch_name varchar2(30)
balance number(8)

C) NAME: customer
FIELD DATATYPE
customer_id varchar2(11) primary key
customer_name varchar2(20)
customer_street varchar2(15)
customer_city varchar2(15)

D) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4) primary key
branch_name varchar2(30)
amount number(8,2)

5. Add foreign keys to the following tables for the specified attributes with mentioned
reference table

B) NAME: account
FIELDS DATATYPE
account_no varchar2(11) primary key
branch_name varchar2(30) references branch(branch_name)
balance number(8)

C) NAME: depositor
FIELD DATATYPE
customer_id varchar2(11)references customer (customer_id)
account_no varchar2(11)references account (account_no)

D) NAME: loan
FIELDS DATATYPE

17
loan_no varchar2(4) primary key
branch_name varchar2(30) references branch(branch_name) (Create constraint
with constraint name)
amount number(8,2)

6. Drop foreign key constraint from loan table


7. Set loan_no attribute of borrower table as foreign key with cascade deletion,
which refers to loan table loan_no column.
8. Add foreign key for the customer_id of borrower table which refers to customer table with
constraint name.

9. Insert the following values into the tables

1. branch :

BRANCH_NAME BRANCH_CITY ASSETS


Perryridge Rye 5000000
Downtown Stamford 1000000
Brighton Paloalto 2500000
Redwood Harrison 1500000
Mianus Pitsfield 4500000
Roundhill Princeton 1500000

2. account :

ACCOUNT_NO BRANCH_NAME BALANCE


019_28_3746 Perryridge 15000
182_73_6091 Downtown 23000
192_83_7465 Brighton 18000
321_12_3123 Redwood 5000
336_66_9999 Mianus 5000
963_96_3963 Roundhill 5000
376_66_9999 Mianus 9000
963_96_3964 Mianus 13000

3. loan :

LOAN BRANCH_NAME AMOUNT


1_11 Roundhill 9000
1_14 Downtown 15000
1_15 Perryridge 15000
1_16 Perryridge 13000
1_17 Downtown 10000
1_23 Redwood 20000

18
1_93 Mianus 500
4. depositor
CUSTOMER_ID ACCOUNT_NO
c_08 182_73_6091
c_03 192_83_7465
c_05 321_12_3123
c_07 336_66_9999
c_08 963_96_3963
c_02 376_66_9999

5. customer
CUSTOMER_ID CUSTOMER_NAME CUSTOMER_STREET CUSTOMER_CITY
c_01 smith north rye
c_02 turner putnam stamford
c_03 johnson alma palo alto
c_04 curry north rye
c_05 jones main harrisdon
c_06 adoms spring pittsfield
c_07 lindsay park pittsfield
c_08 hayes main harrison
c_09 williams nassau Princeton

6. borrower
CUSTOMER_ID LOAN_NO
c_01 1_11
c_01 1_23
c_03 1_93
c_05 1_17
c_03 1_16
c_05 1_14

10. Create the Database Schema for a Employee-pay scenario

a) employee(emp_id : integer, emp_name: string, address: string, city: string)


b) department(dept_id: integer, dept_name:string)
c) paydetails(emp_id : integer, dept_id: integer, basic: integer, deductions: integer,
additions: integer, DOJ: date)
d) payroll(emp_id : integer, pay_date: date)

For the above schema, perform the following:

11. Create PRIMARY KEY for employee(emp_id) and department(dept_id).


12. Enforce NOT NULL constraint for emp_name.

19
13. Creates a DEFAULT constraint on the "City" column of employee table.
14. Create NOT NULL for dept_id on department table.
15. Create NOT NULL for basic in pay details.
16. Enforce CHECK constraints for (deductions > 780) on pay details.

EX. 2. Database Querying – Simple queries, Nested queries, Sub queries and
Joins

Aim : To perform data manipulation operations such as Insertion, Deletion, Updating,


Viewing records based on conditions and data definition operation for Altering the structure of
the database.

Simple Queries
1. Create Employee table and insert the values like given below
Emplo First_ Last_ Email Phone_Nu Hire_d Salary Comm Man Depar
yee_id Name Name mber ate ission_ ager_ tment
pct id _id
101 selva kumar selva@xyz. 9350454613 05- 20000 .20 104 201
com JAN-

20
1990
102 muthu Kumar muthu@xyz 7250548158 08- 30000 .10 104 201
.com FEB-
1991
103 selva laksh Selva1@xyz 8795458162 40000 104 201
mi .com
104 anu Sree anu@xyz.co 8495188645 22- 60000 .10 104 202
m MAR-
1989
105 bharath Rajan bharathi@x 6548521486 25- 20000 105 202
i yz.com MAR-
1989
106 muthu Selvi 9874525842 26- 80000 .10 105 202
APR-
1994
107 devi Priya devi@xyz.c 8547962140 70000 .20 105 203
om
108 selva Kumar 7589632410 31- 30000 .10 108 203
i SEP-
1990
109 Tamil Arasi tamil@xyz. 8546231189 29- 50000 .50 108 204
com OCT-
1997
110 maha laxmi maha@xyz. 8745962311 70000 .10 108 204
com

2. Create a query to display the last name, hire date, and employee number for each
employee, with employee number appearing first.

SOLUTION:

SQL> select Employee_id,Last_Name,Hire_date from EMPLOYEES_TABLE;

EMPLOYEE_ID LAST_NAME HIRE_DATE


----------- ------------------------- ---------------------
104 Sree 22-MAR-89
105 Rajan 25-MAR-89

21
108 Kumari 30-SEP-90
101 Kumar 05-JAN-90
102 Kumar 08-FEB-91
103 lakshmi
106 Selvi 26-APR-94
107 Priya
109 Arasi 29-OCT-97
110 laxmi

10 rows selected.

3. Display employees records whose salary is greater than 20000.

SOLUTION:
SQL> select * from EMPLOYEES_TABLE where Salary>20000;

EMPLO FIRS LAST EMAI PHONE_ HIR SALA COMMI MAN DEPA
YEE_ID T_NA _NA L NUMBE E_D RY SSION_ AGE RTM
ME ME R ATE PCT R_ID ENT_
ID
---------------------------------------------------------------------------------------------------------------------
---------------------
104 anu Sree anu@ 8495188 22- 60000 .1 104 202
xyz.co 645 MAR
m -89
108 selva Kuma NULL 7589632 30- 30000 .1 108 203
ri 410 SEP-
90
102 muthu Kuma muthu 7250548 08- 30000 .1 104 201
r @xyz. 158 FEB-
com 91
103 selva laksh Selva1 8795458 40000 104 201
mi @xyz. 162
com
106 muthu Selvi NULL 9874525 26- 80000 .1 105 202
842 APR-
94
107 devi Priya devi@ 8547962 70000 .2 105 203
xyz.co 140
m

22
109 Tamil Arasi tamil 85426311 29- 50000 .5 108 204
@xyz. 89 OCT-
com 97
110 maha laxmi maha 8754962 70000 .1 108 204
@xyz. 311
com
8 rows selected.
4. Create a query to display the last name and salary of employees whose salary is not in
the range of 2000 and 80000. (hints: not between )

SOLUTION:
SQL> select Last_Name,Salary from EMPLOYEES_TABLE where Salary not between 20000
and 60000;

LAST_NAME SALARY
------------------------- ----------
Selvi 80000
Priya 70000
laxmi 70000

5. Display the employee last name, job ID, and start date of employees hired between 01-
MAR-1989 and May 1,1995. (hints: between)

SOLUTION:
SQL> select Last_Name,Employee_id,Hire_date from EMPLOYEES_TABLE where Hire_date
between '01-MAR-1989' and '01-MAY-1995';
LAST_NAME EMPLOYEE_ID HIRE_DATE
------------------------- ----------- -----------------
Sree 104 22-MAR-89
Rajan 105 25-MAR-89
Kumari 108 30-SEP-90
Kumar 101 05-JAN-90
Kumar 102 08-FEB-91
Selvi 106 26-APR-94
6 rows selected.
8. Display the last name and salary of all employees who earn between 60000 and 80000
and are in departments 201 and 204 .

(hints: between, in)

SOLUTION:
SQL> select Last_Name,Salary from EMPLOYEES_TABLE where Salary between 60000 and
80000 and Department_id in (201,204);

23
LAST_NAME SALARY
------------------------- ----------
laxmi 70000

9. Display the last name and hire date of every employee who was hired in 1994.
(hints: like)
SOLUTION:
SQL> select Last_Name,Hire_date from EMPLOYEES_TABLE where Hire_date like '%94';
LAST_NAME HIRE_DATE
------------------------- ---------
Selvi 26-APR-94
10. Display employee details who does not have mail-id.
SOLUTION:
SQL> select * from EMPLOYEES_TABLE where email=’NULL’;
No rows selected

SubQueries
A subquery is a SQL query nested inside a larger query.

 A subquery may occur in :


 - A SELECT clause
 - A FROM clause
 - A WHERE clause
 The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside
another subquery.
 A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
 You can use the comparison operators, such as >, <, or =. The comparison operator can also be a
multiple-row operator, such as IN, ANY, or ALL.
 A subquery is also called an inner query or inner select, while the statement containing a subquery is
also called an outer query or outer select.
 The inner query executes first before its parent query so that the results of an inner query can be
passed to the outer query.

You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to


perform the following tasks:

 Compare an expression to the result of the query.


 Determine if an expression is included in the results of the query.
 Check whether the query selects any rows.

Syntax :

24
 The subquery (inner query) executes once before the main query (outer query) executes.
 The main query (outer query) use the subquery result.

SQL Subqueries Example :


In this section, you will learn the requirements of using subqueries. We have the
following two tables 'student' and 'marks' with common field 'StudentID'.

student marks
Now we want to write a query to identify all students who get better marks than that of
the student who's StudentID is 'V002', but we do not know the marks of 'V002'.
- To solve the problem, we require two queries. One query returns the marks (stored in
Total_marks field) of 'V002' and a second query identifies the students who get better
marks than the result of the first query.
First query:
SELECT *
FROM `marks`
WHERE studentid = 'V002';
Copy
Query result:

25
The result of the query is 80.
- Using the result of this query, here we have written another query to identify the
students who get better marks than 80. Here is the query :
Second query:
SELECT a.studentid, a.name, b.total_marks
FROM student a, marks b
WHERE a.studentid = b.studentid
AND b.total_marks >80;
Copy
Query result:

Above two queries identified students who get the better number than the student who's
StudentID is 'V002' (Abhay).
You can combine the above two queries by placing one query inside the other. The
subquery (also called the 'inner query') is the query inside the parentheses. See the
following code and query result :
SQL Code:
SELECT a.studentid, a.name, b.total_marks
FROM student a, marks b
WHERE a.studentid = b.studentid AND b.total_marks >
(SELECT total_marks
FROM marks
WHERE studentid = 'V002');
Copy
Query result:

Pictorial Presentation of SQL Subquery:

26
Subqueries: General Rules
A subquery SELECT statement is almost similar to the SELECT statement and it is used
to begin a regular or outer query. Here is the syntax of a subquery:
Syntax:
(SELECT [DISTINCT] subquery_select_argument
FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY aggregate_expression [, aggregate_expression] ...]
[HAVING search_conditions])

Subqueries: Guidelines
There are some guidelines to consider when using subqueries :

 A subquery must be enclosed in parentheses.


 A subquery must be placed on the right side of the comparison operator.

27
 Subqueries cannot manipulate their results internally, therefore ORDER BY clause cannot be added
into a subquery. You can use an ORDER BY clause in the main SELECT statement (outer query) which will be
the last clause.
 Use single-row operators with single-row subqueries.
 If a subquery (inner query) returns a null value to the outer query, the outer query will not return any
rows when using certain comparison operators in a WHERE clause.

Type of Subqueries

 Single row subquery : Returns zero or one row.


 Multiple row subquery : Returns one or more rows.
 Multiple column subqueries : Returns one or more columns.
 Correlated subqueries : Reference one or more columns in the outer SQL statement. The subquery is
known as a correlated subquery because the subquery is related to the outer SQL statement.
 Nested subqueries : Subqueries are placed within another subquery.

In the next session, we have thoroughly discussed the above topics. Apart from the above
type of subqueries, you can use a subquery inside INSERT, UPDATE and DELETE
statement. Here is a brief discussion :

Subqueries with INSERT statement


INSERT statement can be used with subqueries. Here are the syntax and an example of
subqueries using INSERT statement.
Syntax:
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ];
If we want to insert those orders from 'orders' table which have the advance_amount 2000
or 5000 into 'neworder' table the following SQL can be used:

SQL Code:
INSERT INTO neworder
SELECT * FROM orders
WHERE advance_amount in(2000,5000);
Output:
2 rows inserted

28
Subqueries with UPDATE statement
In a UPDATE statement, you can set new column value equal to the result returned by a
single row subquery. Here are the syntax and an example of subqueries using UPDATE
statement.
Syntax:
UPDATE table SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
If we want to update that ord_date in 'neworder' table with '15-JAN-10' which have the
difference of ord_amount and advance_amount is less than the minimum ord_amount of
'orders' table the following SQL can be used:

SQL Code:
UPDATE neworder
SET ord_date='15-JAN-10'
WHERE ord_amount-advance_amount<
(SELECT MIN(ord_amount) FROM orders);
Output:
7 rows updated

Subqueries with DELETE statement


DELETE statement can be used with subqueries. Here are the syntax and an example of
subqueries using DELETE statement.
Syntax:
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
If we want to delete those orders from 'neworder' table which advance_amount are less
than the maximum advance_amount of 'orders' table, the following SQL can be used:

SQL Code:
DELETE FROM neworder
WHERE advance_amount<
(SELECT MAX(advance_amount) FROM orders);
Output:
34 rows deleted.

29
Correlated Subqueries

SQL Correlated Subqueries are used to select data from a table referenced in the outer
query. The subquery is known as a correlated because the subquery is related to the outer
query. In this type of queries, a table alias (also called a correlation name) must be used to
specify which table reference is to be used.

The alias is the pet name of a table which is brought about by putting directly after the
table name in the FROM clause. This is suitable when anybody wants to obtain
information from two separate tables.

Example: SQL Correlated Subqueries

The following correlated subqueries retrive ord_num, ord_amount, cust_code and


agent_code from the table orders ( 'a' and 'b' are the aliases of orders and agents table)
with following conditions -

the agent_code of orders table must be the same agent_code of agents table and
agent_name of agents table must be Alex,the following SQL statement can be used:

SQL Code:
SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code
FROM orders a
WHERE a.agent_code=(
SELECT b.agent_code
FROM agents b WHERE b.agent_name='Alex');
Output:

ORD_NUM ORD_AMOUNT CUST_CODE AGENT_CODE


---------- ---------- ---------- ----------
200127 2500 C00015 A003
200100 1000 C00015 A003
The inner of the above query returns the 'agent_code' A003.
The simplified form of above code is:
SQL Code:
SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code
FROM orders a
WHERE a.agent_code='A003';

30
Using EXISTS with a Correlated Subquery

We have already used the EXISTS operator to check the existence of a result of a
subquery. EXISTS operator can be used in correlated subqueries also. Using EXISTS the
following query display the employee_id, manager_id, first_name and last_name of those
employees who manage other employees.

31
SQL Code:
SELECT employee_id, manager_id, first_name, last_name

FROM employees a

WHERE EXISTS

(SELECT employee_id

FROM employees b

WHERE b.manager_id = a.employee_id)

Output:

EMPLOYEE_ID MANAGER_ID FIRST_NAME LAST_NAME


----------- ---------- -------------------- ---------------
100 Steven King
101 100 Neena Kochhar
102 100 Lex De Haan
103 102 Alexander Hunold
108 101 Nancy Greenberg
114 100 Den Raphaely
120 100 Matthew Weiss
121 100 Adam Fripp
122 100 Payam Kaufling
123 100 Shanta Vollman
124 100 Kevin Mourgos
145 100 John Russell
146 100 Karen Partners
147 100 Alberto Errazuriz
148 100 Gerald Cambrault
149 100 Eleni Zlotkey
201 100 Michael Hartstein
205 101 Shelley Higgins
Using NOT EXISTS with a Correlated Subquery
NOT EXISTS is logically opposite of EXISTS operator. NOT EXISTS is used when we
need to check if rows do not exist in the results returned by a subquery. Using NOT
EXISTS the following query display the employee_id, manager_id, first_name and
last_name of those employees who have no manager status. This query is opposite to the
previous one.

32
SQL Code:
SELECT employee_id, manager_id, first_name, last_name

FROM employees a

WHERE NOT EXISTS

(SELECT employee_id

FROM employees b

WHERE b.manager_id = a.employee_id);

Output:

EMPLOYEE_ID MANAGER_ID FIRST_NAME LAST_NAME


----------- ---------- -------------------- --------------
104 103 Bruce Ernst
105 103 David Austin
106 103 Valli Pataballa
107 103 Diana Lorentz
109 108 Daniel Faviet
110 108 John Chen
111 108 Ismael Sciarra
112 108 Jose Manuel Urman
113 108 Luis Popp
115 114 Alexander Khoo
116 114 Shelli Baida
117 114 Sigal Tobias
118 114 Guy Himuro
119 114 Karen Colmenares
125 120 Julia Nayer
126 120 Irene Mikkilineni
127 120 James Landry
128 120 Steven Markle
129 121 Laura Bissot
130 121 Mozhe Atkinson
131 121 James Marlow
........
.......

33
Create a table for the following schema using attributes from EMPLOYEES table

Emp_training (Employee_id,First_Name,email,Phone_number); and display its structure.


SOLUTION:
SQL> create table Emp_training as(select Employee_id,First_Name,Email,Phone_Number from
EMPLOYEES_TABLE);
Table created.
SQL> desc Emp_training;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPLOYEE_ID NUMBER(6)
FIRST_NAME NOT NULL VARCHAR2(20)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER NOT NULL VARCHAR2(10)
1. Display the content of emp_training table

SOLUTION:
SQL> select * from emp_training;

EMPLOYEE_ID FIRST_NAME EMAIL PHONE_NUMB


---------------------------------------------------------------------------------
104 anu anu@xyz.com 9876543212
105 bharathi bharathi@xyz.com 9087093245
108 selva NULL 9345678987
101 selva selva@xyz.com 9345986723
102 muthu muthu@xyz.com 9345091276
103 selva selval@xyz.com 9876543212
106 muthu NULL 8987654321
107 devi devi@xyz.com 9809876543
109 tamil tamil@xyz.com 7898098765
110 maha maha@xyz.com 9809231456

10 rows selected.

2. Copy records from the EMPLOYEES table whose salary is less than 60000 in to
Emp_training2 relation.
SOLUTION:
SQL> create table Emp_training2 as(select Employee_id,First_Name,Email,Phone_Number
from EMPLOYEES_TABLE where salary<60000);

34
Table created.
SQL> select * from emptraning2;
EMPID FNAME EMAILID PHNO
---------- -------------------- ---------------------------------------
105 bharathi bharathi@xyz.com 9442952654
108 selva NULL 9086543489
101 SELVA selva@xyz.com 9346790056
102 muthu muthu@xyz.com 9876545787
109 tamil tamil@xyz.com 9887654456

5 rows selected.

JOIN

SQL joins are used to fetch data from two or more tables, based on conditions between
tables.
There are various type of joins. Like
Equi-Joins
Self-Join
Outer-Join
Cross-Join
Exercise:
1. Fetch records from two tables emp, dept where deptno of employee is equal to dept
no of dept.

SELECT * FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO;


2. Suppose there are two tables category and product.Both table contains category_id.
We want to fetch the records where both tables contain same category_id .

SELECT * FROM CATEGORIES C ,PRODUCTS P where P.CATEGORYID = C.CATEGORYID;


Another way to write it,like
SELECT * FROM CATEGORIES C INNER JOIN PRODUCTS P ON P.CATEGORYID =
C.CATEGORYID;
3. There are two table emp and dept. We want to fetch records of emp where deptno
between 10 and 20.

SELECT * FROM EMP E, DEPT D WHERE D.DEPTNO BETWEEN 10 AND 20;


4. In Emp table there are two columns empno and mgr. Fetch the records where
empno and mgr are same.

SELECT * FROM EMP E1, EMP E2 WHERE E1.EMPNO=E2.MGR;


5. In Employee_details table retrieve the record whose city are same.

SELECT * FROM EMPLOYEE_DETAILS E1,EMPLOYEE_DETAILS E2 WHERE


E1.CITY=E2.CITY;

35
6. Select an employee's department where they have not been assigned to a
department.

SELECT * FROM EMP LEFT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;


(OR)
SELECT * FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO(+);
7. List dept no., Dept name for all the departments in which there are no employees in
the department.

SELECT * FROM EMP RIGHT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;


(OR)
SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO;

8. Retrieve each employee who is in a department and each department that has an
employee and also each employee who is not part of a department and each department
which doesn't have an employee.

SELECT * FROM EMP FULL OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;


(OR)
SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO(+);

Lab Exercise Questions

Update, Delete & Retrieval operation-

a. Modify the balance attribute alone such that it decreases the amount by 10% for the
account table
b. Delete all the account tuples in the ‘Redwood’ branch.
c. Delete all loans with loan amounts between 15000 to 20000.
d. Find the names of all branches in the loan relation.
e. Display all the Customer names whose come from either pittsfield or stamford.
f. Find all loan numbers for loans made at the ‘Perryridge’ branch with loan amount greater
than 1200.
g. Find loan numbers of those loans with loan amount between 10000 and 20000.
h. Display the customer name in alphabetical order
i. Display all the customer names ordered by customer city
j. Give a count of how many account holds are in each branch.

36
EX. 3. CREATION OF VIEWS, SYNONYMS AND SEQUENCE

Aim : To create views, synonyms, sequence, indexes and save point for the database.
VIEWS

A view is a virtual table. In SQL, a view is a virtual table based on the result-set of an SQL
statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if
the data were coming from one single table.

Syntax:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.

Examples

If you have the Northwind database you can see that it has several views installed by default.

The view "Current Product List" lists all active products (products that are not discontinued)
from the "Products" table. The view is created with the following SQL:

37
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No

Update a view by using the following syntax:

Syntax
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Example:

Now we want to add the "Category" column to the "Current Product List" view. We will update
the view with the following SQL:

CREATE or Replace VIEW [Current Product List] AS


SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No

You can delete a view with the DROP VIEW command.

DROP VIEW view_name

.SYNONYM S (alias name for a table, view or sequence)

CREATE SYNONYM <SYNONYMS NAME> FOR <TABLENAME>;

Samples

1) SYNONYM S

CREATING A SYNONYM FOR A TAB LE ORDER_LIST

AFTER INSERTING THE RECORDS TO ORDER_LIST

SQL> select * from order_list;

38
ORDER_NO ISBN QUANTITY SHIP_DATE
-------------------- ---------- ---------- ---------
N121 1-101 100 12-MAR-14
N122 2-102 200 11-FEB-12
N123 3-103 200 22-FEB-13
N124 3-103 300 12-JAN-11
SQL>
CREATE SYNONYM ordernew FOR order_list;
Synonym created.
SQL> select * from ordernew;

ORDER_NO ISBN QUANTITY SHIP_DATE


-------------------- ---------- ---------- ---------
N121 1-101 100 12-MAR-14
N122 2-102 200 11-FEB-12
N123 3-103 200 22-FEB-13
N124 3-103 300 12-JAN-11

SQL>drop SYNONYM ordernew;


Synonym dropped.

SEQUENCE (automatic generation of primary unique key integer value)

CREATE SEQUENCE<SEQUENCENAME> START WITH <VALUE> MINVALUE


<VALUE> INCREMENT BY <VALUE>;

create a sequence and design the student table with the given attributes.
SQL> create table student(student_id number, name varchar2(10),result varchar2(10));

Table created.

SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
STUDENT_ID NUMBER
NAME VARCHAR2(10)
RESULT VARCHAR2(10)
Se que nce Cre ation

39
SQL> create sequence student_seq start with 100 increment by 1;
Sequence created.
SQL> insert into student values(student_seq.nextval,'Alex','pass'); 1
row created.
SQL> insert into student values(student_seq.nextval,'Joel','pass'); 1
row created.
SQL> select * from student;

STUDENT_ID NAME RESULT


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

100 Alex Pass


101 Joel Pass

INDEXES

CREATE [UNIQUE] INDEX INDEX_NAME ONTABLE_NAME(COLUMN_NAME[,


COLUMN_NAM E...]) TABLESPACE TABLE_SPACE;

To cre ate an inde x on the Last Name column of the student table

SQL> create table student(student_id number, name varchar2(10),result varchar2(10));


SQL> se lect * from stude nt;
STUDENT_ID NAME RESULT
---------- ---------- ---------
100 Alex pass
101 Joel pass

SQL> CREATE INDEX LastNameIndex ON student (name);

Index created.

SQL> drop index LastNameIndex;


Index dropped.

Lab Exercise Questions

1. View the customers whose Account Opening date is after 12th Jan 2006.

40
2. View the employee names whose salary is greater than 10000.
3. View for loans made at the ‘Perryridge’ branch with loan amount greater than 1200.
4. Create a view of customer table that prevents modification of the views.

41
EX. 4 DATABASE PROGRAMMING: IMPLICIT AND EXPLICIT CURSORS

Aim : To create cursor for fetching records from the given table based on the requirement
A database cursor can be thought of as a pointer to a specific row within a query result. The
pointer can be moved from one row to the next. Depending on the type of cursor, you may be
even able to move it to the previous row.

1. Implicit Cursor
 Implicit cursors are automatically generated by the Oracle engine. If the Oracle Engine
opens a cursor for its internal processing, it is known as Implicit cursor.
 Implicit cursors are created by default to process the statements when DML
statements(INSERT, UPDATE, DELETE) are executed.
2. Explicit Cursor
 If a cursor is opened for processing data through a PL/SQL block as per requirement like
user defined cursor, is known as an Explicit cursor.
 Explicit cursor is created while executing a SELECT statement that returns more than
one row.
 These cursor should be defined in the declaration section of the PL/SQL block and
created on a SELECT statement which returns more than one row.
Attribute Name Description
%ISOPEN It is true if cursor is open and FALSE if cursor is not open or cursor is
closed.
It is used only with Explicit Cursors.
%FOUND TRUE if at least one row was processed or a record was fetched
successfully from the opened cursor and FALSE otherwise.
%NOTFOUND TRUE if no row were processed or if record was not fetched successfully
and FALSE otherwise.
%ROWCOUNT It returns the number of rows/records processed by a cursor Consider the
following tables to complete the following assignment.

The most commonly used loop with in a PL/SQL block is the FOR variable IN value construct.
This is an example of machine defined loop exit i.e. when all the values in FOR construct are
exhausted looping stops. Syntax: FOR variable IN cursorname Here, the verb FOR automatically
creates the variable of type %rowtype. Each record in the opened cursor becomes a value for the
memory variable of %rowtype. The FOR verb ensures that a row from the cursor is loaded in
declared variable and loop executes once. This goes until all the rows of the cursor have been
loaded into the variable. After this loop stops.
A CURSOR FOR LOOP automatically does the following:
• Implicitly declares its loop index as a %rowtype record.
• Open a cursor.
• Fetches a row from the active set for each loop iteration.

42
• Closes the cursor when all rows have been processed.

Example 1:
Cursor can be closed even when an exit or goto statement is used to leave the loop prematurely,
or an exception is raised inside the loop. Example The HRD manager has decided to raise the
salary for all employees in department number 30 by 0.05.
Emp(empno, deptno,sal)

DECLARE
CURSOR c_emp IS
SELECT empno,sal
FROM emp
WHERE deptno=30;
BEGIN
FOR rec IN c_emp
LOOP
UPDATE emp
SET sal=rec.sal+(rec.sal * .05)
WHERE empno=rec.empno;
END LOOP;
COMMIT;
END;

Example 2
Table 1: 'Emp_Detail'

Employee_id First_Name Last_name Salary DEPT_ID


1 Shruti Shrabya 50000 1
2 Jaya Singh 10000 2
3 Mangala Thokal 60000 3
4 Surendra Maurya 70000 4

Table2: 'Department'

Dept_ID Dept_Name Manager_ID


1 Accounting 1
2 Shipping 3
3 Store 3

43
Q. Write a PL/SQL block to Create a table based record.

Answer:

In table based record the entire structure is similar to columns of table.

Note: To create a table based record/ cursor based record always preferred %ROWTYPE.

DECLARE
vr_emp emp_detail %ROWTYPE;
BEGIN
SELECT *
INTO vr_emp
FROM emp_detail
WHERE employee_id = 1;
DBMS_OUTPUT.PUT_LINE('Employee Details : '||vr_emp.employee_id ||' '||
vr_emp.first_name||' '||vr_emp.last_name||' '||vr_emp.salary);
END;

The above code will display the employee whose id = 1.

Output:

Lab Exercise:
1.Write a PL/SQL code to display the Empno, Ename and Job of employees of DeptNo 10 with
CURSOR FOR LOOP Statement.
Employee table schema (Empno, Ename, Job, Sal, DeptNo, Commission)

44
Ex. 5. PROCEDURES AND FUNCTIONS

Study of PL/SQL block.

PL/SQL PROGRAMMING

Procedural Language/Structured Query Language (PL/SQL) is an extension of SQL.

Basic Syntax of PL/SQL


DECLARE
/* Variables can be declared here */
BEGIN
/* Executable statements can be written here */
EXCEPTION
/* Error handlers can be written here. */
END;
Comments: - In Oracle we can have two types of comments i.e Single Line & Multiline
comments.
Single line comment: - It starts with --.
-- Comment here
Multiline comment is same as C/C++/JAVA comments where comments are present in the pair
of /* & */.
/* Comment here */

Steps to Write & Execute PL/SQL


1. As we want output of PL/SQL Program on screen, before Starting writing anything
type (Only Once per session)
SQL> SET SERVEROUTPUT ON
2. To write program, use Notepad through Oracle using ED command.
SQL> ED ProName
3. Type the program Save & Exit. To Run the program
SQL> @ProName
Ex :- PL/SQL to find addition of two numbers
DECLARE
A INTEGER := &A;
B INTEGER := &B;
C INTEGER;
BEGIN
C := A + B;
DBMS_OUTPUT.PUT_LINE('THE SUM IS '||C);
END;
/

45
Decision making with IF statement :- The general syntax for the using IF-ELSE statement
is IF(TEST_CONDITION) THEN
SET OF STATEMENTS
ELSE
SET OF STATEMENTS
END IF;
For Nested IF—ELSE Statement we can use IF--ELSIF—ELSE as follows
IF(TEST_CONDITION) THEN
SET OF STATEMENTS
ELSIF (CONDITION)
SET OF STATEMENTS
END IF;

Ex:- Largest of three numbers.


This program can be written in number of ways, here are the two different ways to write
the program.
DECLARE
A NUMBER := &A;
B NUMBER := &B;
C NUMBER := &C;
BEGIN
IF (A > B AND A > C) THEN
DBMS_OUTPUT.PUT_LINE('BIGGEST IS ' || A);
ELSIF (B > C) THEN
DBMS_OUTPUT.PUT_LINE('BIGGEST IS ' || B);
ELSE
DBMS_OUTPUT.PUT_LINE('BIGGEST IS ' || C);
END IF;
END;
/
LOOPING STATEMENTS:- For executing the set of statements repeatedly we can use loops.
The oracle supports number of looping statements like GOTO, FOR, WHILE & LOOP.
Here is the syntax of these all the types of looping statements.
GOTO STATEMENTS
<<LABEL>>
SET OF STATEMENTS
GOTO LABEL;
FOR LOOP
FOR <VAR> IN [REVERSE] <INI_VALUE>..<END_VALUE>
SET OF STATEMENTS
END LOOP;
WHILE LOOP
WHILE (CONDITION) LOOP
SET OF STATEMENTS

46
END LOOP;
LOOP STATEMENT
LOOP
SET OF STATEMENTS
IF (CONDITION) THEN
EXIT
SET OF STATEMENTS
END LOOP;
While using LOOP statement, we have take care of EXIT condition, otherwise it may go into
infinite loop.

Example :- Here are the example for all these types of looping statement where each program
prints numbers 1 to 10.

GOTO EXAMPLE
DECLARE
I INTEGER := 1;
BEGIN
<<OUTPUT>>
DBMS_OUTPUT.PUT_LINE(I);
I := I + 1;
IF I<=10 THEN
GOTO OUTPUT;
END IF;
END;
/
FOR LOOP EXAMPLE
BEGIN
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(I);
END LOOP;
END;
/
WHILE EXAMPLE
DECLARE
I INTEGER := 1;
BEGIN
WHILE(I<=10) LOOP
DBMS_OUTPUT.PUT_LINE(I);
I := I + 1;
END LOOP;
END;
/
LOOP EXAMPLE
DECLARE

47
I INTEGER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(I);
I := I + 1;
EXIT WHEN I=11;
END LOOP;
END;
/

DATA TYPES
Already we know following data types. NUMBER, INTEGER, VARCHAR2, DATE,
BOOLEAN, etc. Now let’s see few more data types that are useful for writing PL/SQL programs
in Oracle.
%TYPE :- %TYPE is used to give data type of predefined variable or database column.

Eg:-
itemcode Number(10);
icode itemcode%Type;
The database column can be used as
id customer.cid%type

%ROWTYPE :- %rowtype is used to provide record data type to a variable. The variable can
store row of the table or row fetched from the cursor.
Eg:-
If we want to store a row of table Sailors then we can declare variable as customer %Rowtype

Inserting values to table :- Here is the example for inserting the values into a database through
PL/SQL Program. Remember that we have to follow all the rules of SQL like Primary Key
Constraints, Foreign Key Constraints, Check Constraints, etc.

Ex:- Insert the record into Accounts table by reading the values from the Keyboard.
DECLARE
ACCNO NUMBER (5):=& ACCNO;
BRANCH_NAME VARCHAR2(30):='& BRANCH_NAME ';
BALACE NUMBER(5):=& BALACE;
BEGIN
INSERT INTO ACCOUNS VALUES(ACCNO, BRANCH_NAME,BALANCE);
END;
/
Reading from table
DECLARE
SID VARCHAR2(10); -- or can be defined SID Sailors.SID%Type
SNAME VARCHAR2(30);
RATING NUMBER(5);

48
AGE NUMBER(4,2);
BEGIN
SELECT SID, SNAME, RATING, AGE INTO SID, SNAME, RATING, AGE FROM
SAILORS WHERE SID='&SID';
DBMS_OUTPUT.PUT_LINE(SID || ' '|| SNAME || ' '|| RATING ||' '|| AGE );
END;
/

FUNCTIONS
SYNTAX
Create [or replace] function function name[(argument1,argument2,....., argument
n)]
Return function- datatype is
[local- variable-declarations]
Begin
Executable-section [exception-section]
Return-function value
End[function-name];

Exercise
Create a function for withdrawing money from an account in a bank management
system which uses bank table

SQL> create or replace function withdraw (n in number, amt in number)


2 return number is
3 b number
4 begin
5 select balance into b from bank where acc-no=n;
6 if b-500>amt then
7 b:=b-amt
8 update bank set balance=b where acc-no=n;
9 else
10 dbms_output.put_line(‘can not withdraw’);
11 endif
12 return b;
13 End;
14 / Function created

49
SQL> select * from bank
ACC-NO B_NAME BALANCE
101 SBI 25000
102 SBT 5000
103 FEDERAL 10000
104 AXIS 15000
105 CANARA 50000
Calling function from a PL\SQL block:

SQL> declare
2 n number
3 begin
4 n:=withdraw(101,20000);
5 end
6/
PL/SQL procedure successfully completed.

SQL> select *from bank;


ACC-NO B_NAME BALANCE
101 SBI 5000
102 SBT 5000
103 FEDERAL 10000
104 AXIS 15000
105 CANARA 50000

Create a function for depositing money to an account in a bank management


system which uses bank table

SQL> create or replace function deposit(n in number, amt in number)


2 return number is
3 b number
4 Begin
5 select balance into b from bank where acc_no=n;
6 b:=b+amt;
7 update bank set balance=b where acc_no=n;
8 return b;
9 end
10 /

50
Function created Calling function from a PL/SQL block
SQL> declare
2 n number
3 begin
4 n:=deposit(104,5000);
5 end
6 / PL/SQL procedure successfully completed.

SQL> select * from bank


ACC-NO B_NAME BALANCE
101 SBI 5000
102 SBT 5000
103 FEDERAL 10000
104 AXIS 20000
105 CANARA 50000

Function with implicit Cursors:

Create a function for calculating the total marks and percentage of the student in a
student management system which uses a student table:

SQL> create or replace function stud_update


2 return number is
3 cursor c is select * from student;
4 ctot number
5 cper number
6 begin
7 for i in c
8 loop
9 ctot:=i.m1+i.m2+i.m3;
10 cper:=ctot/3;
11 update student set total=ctot where id_no=i.id_no;
12 update student set per=cper where id_no=id_no;
13 end loop;
14 Return 1;
15 End;

51
16 /
Function created

SQL> select * from student;

ID_NO NAME GR DE M1 M2 M3 TOTAL PER


10 Gouri a it 89 56 74 0 0
11 Akashaj s it 95 91 93 0 0
23 Lithik b bt 78 67 71 0 0
27 Pallavi s bt 90 98 96 0 0
30 Navaj a ph 88 81 89 0 0

SQL> declare
2 n number
3 begin
4 n:=stud_update;
5 end;
6/
PL/sql Procedure successfully completed

SQL> select * from student

ID_NO NAME GR DE M1 M2 M3 TOTAL PER

10 Gouri a it 89 56 74 219 73

11 Akashaj s it 95 91 93 279 93

23 Lithik b bt 78 67 71 216 72

52
27 Pallavi s bt 90 98 96 284 94.6667

30 Navaj a ph 88 81 89 258 86

Function with explicit Cursors:

Creating a function for calculating net salary for all employees in an organization
using an employee table

SQL> create or replace function salary


2 return number is
3 cursor c is select * from employee;
4 i employee%rowtype;
5 netsalary number;
6 begin
7 open c;
8 loop
9 fetch c into i;
10 If c%notfound then exit
11 end if
12 netsalary=i.basic+i.hra+i.da-i.pf;
13 update employee set netsal=netsalary where e_no=i.e_no;
14 end loop;
15 return netsalary;
16 close c;
17 end
18 /

SQL> select * from employee

53
E_NO E_NAME HRA DA PF BASIC NETSAL

100 Adithya 500 200 350 10000 0


101 Anusha 250 300 410 12000 0
102 Sara 250 300 100 20000 0
103 Ragul 295 600 480 8500 0
104 Pooja 100 100 200 7500 0
Function created

SQL> declare
2 n number
3 begin
4 n:=salary;
5 end
6/

PL/SQL procedure successfully completed

SQL> select * from employee

E_NO E_NAME HRA DA PF BASIC NETSAL


100 Adithya 500 200 350 10000 10350
101 Anusha 250 300 410 12000 12140
102 Sara 250 300 100 20000 20450
103 Ragul 295 600 480 8500 8915
104 Pooja 100 100 200 7500 7500

PROCEDURES

SYNTAX
SQL> create[or replace] procedure procedure_name [(argument1, argument2,…( argument n)]
is
[local –variable - declarations]
begin
executable-section
[exception- section]
End[procedure-name];

SQL> create table bank(acc_no number, br_name varchar2(10), bal number);


Table created.

54
1. Create a procedure for deposit and withdrawal of money in an account in a Bank
Management System which uses bank table.

SQL> create or replace procedure bank_up(opt_number, amount number, n


number) from bank where accno= n;
2 as
3 balance number
4 begin
5 select bal into balance from bank where accno = n;
6 if opt=1 then
7 balance:= balance + amount;
8 update bank set bal = balance where accno= n;
9 commit;
10 dbms_output.put_line(‘balance after deposition is ‘ || balance);
11 elsif opt=2 then
12 balance:= balance-amount;
13 if balance <1000 then
14 dbms_output.put_line(‘cannot withdraw… balance low…!(‘|| balance||’)’);
15 else
16 update bank set bal = balance where accno= n;
17 commit; dbms_output.put_line (‘balance after withdrawal is ‘||balance);
18 end if;
19 end if;
20 end;
21 / Procedure created.

SQL> select * from bank;


ACC_NO NAME BAL
100 Anil 50000
101 Abi 10000
102 Bavi 2500
103 Chandru 1000
104 Divakar 20000

SQL>exec bank_up(1, 40000, 100);


balance after deposition is 80900
PL/ SQL procedure successfully completed.

55
SQL> select * from bank;
ACC_NO NAME BAL
100 Anil 90000
101 Abi 10000
102 Bavi 2500
103 Chandru 1000
104 Divakar 20000

SQL >exec bank_up(2,1500,102);


Cannot withdraw… balance low..!(500)

PL/ SQL procedure successfully completed.

SQL> select * from bank;

ACC_NO NAME BAL


100 Anil 90000
101 Abi 10000
102 Bavi 500
103 Chandru 1000
104 Divakar 20000

Example2:
The subsequent procedure is used to increase the salary of all employees who work in the
department given by the procedure's parameter. The percentage of the salary increase is given by
a parameter, too.

create procedure raise salary(dno number, percentage number DEFAULT 0.5) is


cursor emp cur (dept no number) is
select SAL from EMP where DEPTNO = dept no
for update of SAL;
empsal number(8);
begin
open emp cur(dno); - - Here dno is assigned to dept no
loop
fetch emp cur into empsal;
exit when emp cur%NOTFOUND;
update EMP set SAL = empsal _ ((100 + percentage)/100)
where current of emp cur;
end loop;

56
close emp cur;
commit;
end raise salary;

PROCEDURES WITH IMPLICIT CURSORS:


SQL> create table emp1(empno number, empname varcgar2(10), deptno number,
sal number exp number);

Table created.
SQL> select * from emp1;
EMPNO EMPNAME DEPTNO SAL EXP
1000 Akshay 250 22000 3
1010 Akshay 230 18000 2
1012 Abhirami 250 20000 2
1015 Bavi 240 34000 6
1200 Akshay 250 32000 4
1017 Lakshmi 200 28000 3
1019 Sundar 200 30000 3
1045 Sreeram 260 42000 4
7 rows selected.
2. Create a procedure for incrementing rupees 1500 for those with experience less
than 4 years and 4000 for rest of all employees in an organization which uses
employee table.

SQL > create or replace procedure emp1_bonus


2is
3 cursor c is select * from emp1;
4 bsal number;
5 begin
6 for I in c
7 loop
8 if i.exp<4 then
9 bsal:=sal+1500;
10 update emp1 set sal = bsal where empno =i.empno;
11 else
12 sal:=i.sal+5000;
13 update emp1 set sal = bsal where empno =i.empno;
14 end if;

57
15 end loop;
16 end;
17 /
Procedure created.
PL/ SQL procedure successfully completed.
SQL> select * from emp1;

EMPNO EMPNAME DEPTNO SAL EXP


1000 Akshay 250 23500 3
1010 Akshay 230 19500 2
1012 Abhirami 250 21500 2
1015 Bavi 240 39000 6
1200 Akshay 250 37000 4
1017 Lakshmi 200 29500 3
1019 Sundar 200 31500 3
1045 Sreeram 260 47000 4
8 rows selected.

PROCEDURES WITH EXPLICIT CURSORS:

SQL> create table invent1(itcode number, itname varchar2(10), no_of_indiv


number);
Table created.

SQL> select * from invent1;


ITCODE ITNAME NO_OF_INDIV
1001 FLOPPY 10
1067 DVD ROM 100
500 CD ROM 500
1000 PEN DRIVE 5
249 ZIP DRIVE 3

3. Create a procedure for checking the stock of an agency to order items which
uses inventory and orderit tables.

58
SQL > create or replace procedure invent_check
2 is
3 cursor c select * from invent1;
4 j invent% rowtype;
5 che number;
6 begin
7 open c
8 loop
9 fetch c into j;
10 if c%notfoun then exit;
11 end if;
12 che:= j.no_of_indiv;
13 if che<=5 then
14insert into orderit values(j.itname, j.no_of_indiv);
15 end if;
16 end loop;
17 close c;
18 end;
/
Procedure created.

SQL> exec invent_check

PL/ SQL procedure successfully completed.


SQL> select * from orderit;
ITNAME NO_OF_INDIV
PEN DRIVE 5
ZIP DRIVE 3

Lab Exercise:

1. Write the PLSQL program to find the square of a number.


2. Write the PLSQL program to find the loan amount for loan_no ‘L_15’.
3. Write the PLSQL program to find the give number is even or odd.
4. Write the PL SQL program to find the factorial of a number.
5. Write the PLSQL program to find sum of N numbers.
6. Create a table stock to contain the item Code, item name, current stock and date of last
purchase. Write a stored procedure to seek for an item using item code & delete if, if the date of
last purchased is before one year from the current date. If not update the current stock.

59
EX. 6. TRIGGERS
Aim :
To implement and execute trigger in Oracle database using Procedural Language concepts.

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 can be defined on the table, view, schema, or database with which the event is
associated.
-It is a stored sub program associated with a table
-It is used to keep an audit trial of a table, to prevent invalid transaction, enforce complex
security authorization, to generate data automatically

60
-ie.)A trigger is a statement that the system executes automatically as a side effect of a
modification to the database. Eg., Instead of allowing negative account balances, the bank deals
with overdrafts by setting the account balance to zero, and creating a loan in the amount of the
overdraft.

Benefits of Triggers
Triggers can be written for the following purposes −

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

Trigger consists of three parts:


Event : It causes the trigger to be checked
Condition : It must be satisfied for trigger execution to proceed.
Action : It occurs when the trigger executes.

Syntax:

Create or replace trigger <trigger_name>


{ before / after / instead of }
{ insert / update / delete [of column] }
on <tablename / viewname>
referencing { old as old / new as new }
[for each statement / for each row [ when <condition>]]
Declare
Variable declaration
Constant declaration
Begin
PL / SQL Sub program body
Exception
Exception PL / SQL Block (or) user defined exception
End

EXAMPLE

61
1. Create a trigger for invent table which triggers while updating operations are performed on the
invent table
SQL> create or replace triggers inve before update on invent
2 for each row
3 declare
4 begin
5 if: new.no_of_indiv<=10 then
6 Insert into orderit values(:new.itname,:new.no_of_indiv);
7 else
8 delete from orderit where itname=:new.itname;
9 end if;
10 end;

11 / Trigger created

SQL>select* from orderit;

ITNAME NO_OF_INDIV
hard disk 3
cd rom 5
ipod 2

2. Create a trigger while insert or update or delete operations are performed on the table employ.

SQL> select * from employ


No rows selected

SQL> select * from emp_log;


No rows selected

SQL> create or replace trigger LOG_EMP


2 after insert or update or delete on employ
3 begin
4 if inserting then
5 insert into EMP_LOG values(user,’INSERT’,sysdate);
6 end if;
7 if updating then
8 insert into EMP_LOG values(user,’UPDATE’,sysdate);
9 end if;
10 if deleting then
11 insert into EMO_LOG values(user,’DELETE’,sysdate);
12 end if;
13 end;
14 /

62
Trigger created

SQL>insert into employ values(„sachin‟,101);


1 row created

SQL>select *from emp_log;


USEDBY OPERATION SYSDATE
SCOTT INSERT 25-MAR-13

SQL>update employ set id=103 where id=101;


1 row updated.

SQL>select * from emp_log;


USEDBY OPERATION SYSDATE
SCOTT INSERT 25-MAR-13
SCOTT UPDATE 25-MAR-13

SQL> delete from employ where id=103;


1 row deleted
SQL>select *from emp_log;
USEDBY OPERATION SYSDATE
SCOTT INSERT 25-MAR-13
SCOTT UPDATE 25-MAR-13
SCOTT DELETE 25-MAR-13

Lab Exercise:

1. Create the trigger for negative balance.


Insert a new tuple s in the loan relation with
s[loan_no] = t[acctno]
s[br_name] = t[br_name]
s[amount] = -t[balance]

2. Create a trigger for new employee.


i) Insert an new employee to the employee relation
ii) Check the dno of the new employee tuple is not null or not.
iii) If it is not null, update the department relation with newly inserted employee
by adding their salary to the total salary attribute of their related department.
3. Write a PLSQL function to find square of a given number.
4. Create a table contain phone number, user name and address of the phone user. Write the
function to search for address using phone number.

63
Ex. 7. EXCEPTION HANDLING

Aim : To write a PL/SQL programs to handle pre defined and user defined exceptions in the
PLSQL block.

SELECT --- INTO STATEMENT

We have to ensure that the SELECT….INTO statement should return one & only one row. If no
row is selected then exception NO_DATA_FOUND is raised. If more than one row is selected
then exception TOO_MANY_ROWS is raised.
To handle the situation where no rows selected or so many rows selected we can use Exceptions.
We have two types of exception, User-Defined and Pre-Defined Exceptions.

User-Defined Exception

64
DECLARE
N INTEGER:=&N;
A EXCEPTION;
B EXCEPTION;
BEGIN
IF MOD(N,2)=0 THEN
RAISE A;
ELSE
RAISE B;
END IF;
EXCEPTION
WHEN A THEN
DBMS_OUTPUT.PUT_LINE('THE INPUT IS EVEN.....');
WHEN B THEN
DBMS_OUTPUT.PUT_LINE('THE INPUT IS ODD.....');
END;
/
Pre-Defined Exception
DECLARE
ACC_NO VARCHAR2(10);
BEGIN
SELECT ACCOUNT_NO INTO ACC_NO FROM ACCONTS WHERE BRANCH_NAME
='&BRANCH_NAME’;
DBMS_OUTPUT.PUT_LINE(ACC_NO);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘No Account with given ACCOUNT NO found’);
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE(‘More than one ACCOUNTS with same BRANCH NAME
found’);
END;/
SQL> create or replace function stud_update
2 return number is
3 cursor c is select * from student;
4 ctot number
5 cper number
6 begin
7 for i in c
8 loop
9 ctot:=i.m1+i.m2+i.m3;
10 cper:=ctot/3;
17 update student set total=ctot where id_no=i.id_no;
18 update student set per=cper where id_no=id_no;
19 end loop;
20 Return 1;

65
21 End;
22 /
Function created

SQL> select * from student;

ID_NO NAME GR DE M1 M2 M3 TOTAL PER


10 Gouri a it 89 56 74 0 0
11 Akashaj s it 95 91 93 0 0
23 Lithik b bt 78 67 71 0 0
27 Pallavi s bt 90 98 96 0 0
30 Navaj a ph 88 81 89 0 0

SQL> declare
2 n number
3 begin
4 n:=stud_update;
5 end;
6/

PL/sql Procedure successfully completed

SQL> select * from student

ID_NO NAME GR DE M1 M2 M3 TOTAL PER


10 Gouri a it 89 56 74 219 73
11 Akashaj s it 95 91 93 279 93
23 Lithik b bt 78 67 71 216 72
27 Pallavi s bt 90 98 96 284 94.6667
30 Navaj a ph 88 81 89 258 86

Function with explicit Cursors:

Creating a function for calculating net salary for all employees in an organization using an
employee table
SQL> create or replace function salary
2 return number is
3 cursor c is select * from employee;
4 i employee%rowtype;
5 netsalary number;
6 begin
7 open c;
8 loop

66
9 fetch c into i;
10 If c%notfound then exit
11 end if
12 netsalary=i.basic+i.hra+i.da-i.pf;
13 update employee set netsal=netsalary where e_no=i.e_no;
14 end loop;
15 return netsalary;
19 close c;
20 end
21 /
SQL> select * from employee

E_NO E_NAME HRA DA PF BASIC NETSAL


100 Adithya 500 200 350 10000 0
101 Anusha 250 300 410 12000 0
102 Sara 250 300 100 20000 0
103 Ragul 295 600 480 8500 0
104 Pooja 100 100 200 7500 0
Function created
SQL> declare
2 n number
3 begin
4 n:=salary;
5 end
6/

PL/SQL procedure successfully completed


SQL> select * from employee
E_NO E_NAME HRA DA PF BASIC NETSAL
100 Adithya 500 200 350 10000 10350
101 Anusha 250 300 410 12000 12140
102 Sara 250 300 100 20000 20450
103 Ragul 295 600 480 8500 8915
104 Pooja 100 100 200 7500 7500

Ex.8. ER DIAGRAM AND NORMALIZATION

To Construct E-R diagrams including:


Entities (strong, weak, associative)
Attributes (simple, multi-valued, derived)
Relations (unary, binary, ternary)

Roadway Travels:

67
Roadway travels is in business since 1997 with several buses connecting different places in india.
Its main office is located in Hyderabad. The company wants to computerize its operations in the
following areas.

The company wants to computerize its operations in the following areas:

1. Reservations and Ticketing


2. Cancellations

Reservations & Cancellation:


Reservations are directly handled by booking office. Reservations can be made 30
days in advance and tickets issued to passenger. One passenger/ person can book
many tickets (to his/her family).Cancellations are also directly handed at the booking
office.
In the process of Computerization of Roadway Travels you have to design and
develop a Database which consists the data of Buses, Passengers, Tickets and
Reservation and cancellation details. You should also develop query‘s using SQL to
retrieve the data from the database.

Following steps are involved in the process:


1. Analyzing the problem and identifying the Entities and Relationships
2. E-R Model
3. Normalised Relational Model
4. Creating the database
5. Querying.

1. E-R Model:
Analyze the problem carefully and come up with the entities in it. Identify what data
has to be persisted in the database. This contains the entities, attributes etc. In this
we wqill analyze different types of entities with attributes of “Roadways Travels”.
Entity: An Entity is an object or concept about which you want to
store information Relationship: A relationship is an association
between several entities.
Attributes: An object is characterized by its properties or attributes. In relational
database systems attributes correspond to fields.

The Road Way Travels Consists Of The Following Entities:


 BUS
 Ticket

68
Passenger
 Reservation
 Cancellation/modification
These Entities have following
attributes
Bus:
 Bus_id
Bus_name
 Bus_type
 Bus_totalseats

Ticket:
 Ticket_booking
 Ticket_datejourney
 Ticket_to
Ticket_from
 Ticket_id
 Ticket_no of tickets

Passenger:
 Pid
Pname
 Pgender
 Page
 precancel

Bus
Sourc
No
Bus e
2. Concept design with E-R Model and apply cardinalities for each
Destinatio
relationship. Identify strong entities and weak entities for
Departure Time n specialization.
relationships like generalization, aggregation,

E_R diagram: Date of Journey

Sex
Ticket No Reservation
Ticket Source

Departure
Time Age
69
Arrival Time
3. Relation Model represents attributes as columns in tables and
different types of attributes like composite, Multi-valued and
Derived.

Example: The passenger tables look as below. This is an example. You can add more
attributes based on your E-R model. This is not a normalized table. Passenger

70
Tickets
#tickets_no
no of tkts
From_place
To_place
#Bus_no
#jrny_date

71
EX 9. DATABASE CONNECTIVITY WITH FRONT END TOOLS

Introduction to VISUAL BASIC (FRONT END TOOL)

VISUAL BASIC is a high level programming language which was evolved


from the earlier DOS version called BASIC. BASIC means Beginners' All-
purpose Symbolic Instruction Code. VISUAL BASIC is a VISUAL and
events driven Programming Language. These are the main divergence from
the old BASIC. In BASIC, programming is done in a text-only environment
and the program is executed sequentially. In VB, programming is done in a
graphical environment. In the old BASIC, you have to write program codes
for each graphical object you wish to display it on screen, including its
position and its color. However, In VB , you just need to drag and drop any
graphical object anywhere on the form, and you can change its color any
time using the properties windows.

On the other hand, because users may click on a certain object randomly, so
each object has to be programmed independently to be able to response to
those actions (events). Therefore, a VB Program is made up of many
subprograms, each has its own program codes, and each can be executed
independently and at the same time each can be linked together in one way
or another.

1.1 FORMS

The Visual Basic form is a primary element of an application that functions


as the visual "window." It can include a lot of code. Setting up a form
impacts the way you choose to develop any application in Visual Basic.

Step 1 Open Microsoft Visual Basic environment and select "New Form."
Step 2 Make the form the size that you want by clicking on the corner and
dragging. Then add any form properties that you will need (like a name: Ex:
frmOpener).
Step 3 Add all of the elements, such as control buttons and text boxes, that
you will need on the form for the user. Arrange them exactly the way you
want them to appear for the user.
Step 4 Double-click on the form to enter the code section. A coding window
will open up where the Form Load command represents the point where the
software will open and begin working.
Step 5 Within the code window, add functions for anything that you want to
happen when the form loads, before the user does anything.

72
Step 6 Add variables. The Form Load section of your code is a great place to
dimension variables, known as "global" variables, that you will use
throughout the program. Add variables by name and specify type: Ex. for an
integer to count clicks, use the command: dim click as integer
Step 7 You're not done yet. Most of the function code should be within user-
generated events. Don't try to program the whole thing within the form code
module. The application will do most of its work through functions that are
called between different objects (command buttons) and the form itself. A
programmer has to know how to "pass" variables. When you do dimension
variables in the form load, think about how they will be passed to various
functions.

1.2. Creating Your First Application

First of all, you have to launch Microsoft Visual Basic 6. Normally, a default
form with the name Form1 will be available for you to start your new
project. Now, double click on Form1, the source code window for Form1 as
shown in figure 1 will appear. The top of the source code window consists
of a list of objects and their associated events or procedures. In following
figure1, the object displayed is Form and the associated procedure is Load.

When you click on the object box, the drop-down list will display a list of
objects you have inserted into your form as shown in figure 2

Here, you can see a form with the name Form1, a command button with the
name Command1, a Label with the name Label1 and a Picture Box with the

73
name Picture1. Similarly, when you click on the procedure box, a list of
procedures associated with the object will be displayed as shown in figure 3.

Some of the procedures associated with the object Form1 are Activate,
Click, DblClick (which means Double-Click) , DragDrop, keyPress and
more. Each object has its own set of procedures. You can always select an
object and write codes for any of its procedure in order to perform certain
tasks.

Private Sub Form_Load


...... { Write your code here }
End Sub

Example 1
Private Sub Form_Load ( )
Form1.show
Print “Welcome to Visual Basic tutorial”
End Sub

When you press F5 to run the program, the output screen will appear as shown below in
figure 4

You can also perform arithmetic calculations as shown in example 2.

Example 2

Private Sub Form_Activate ( )

74
Print 20 + 10
Print 20 - 10
Print 20 * 10
Print 20 / 10
End Sub

the output screen will appear as shown below in figure 5

1.3. The Control Properties

Before writing an event procedure for the control to response to a user's


input, you have to set certain properties for the control to determine its
appearance and how it will work with the event procedure. You can set the
properties of the controls in the properties window or at runtime. Figure is a
typical properties window for a form. You can rename the form caption to
any name that you like best. In the properties window, the item appears at
the top part is the object currently selected (in Figure 6, the object selected is
Form1). At the bottom part, the items listed in the left column represent the
names of various properties associated with the selected object while the
items listed in the right column represent the states of the properties.
Properties can be set by highlighting the items in the right column then
change them by typing or selecting the options available.

75
For example, in order to change the caption, just highlight Form1 under the
name Caption and change it to other names. You may also try to alter the
appearance of the form by setting it to 3D or flat. Other things you can do
are to change its foreground and background color, change the font type and
font size, enable or disable minimize and maximize buttons and etc.

You can also change the properties at runtime to give special effects such
as change of color, shape, animation effect and so on. For example the
following code will change the form color to red every time the form is
loaded.

Private Sub Form_Load()


Form1.Show
Form1.BackColor = &H000000FF&
End Sub
End Sub

Few important points about setting up the properties.


 You should set the Caption Property of a control clearly so that a
user knows what to do with that command. For example, in the calculator
program, all the captions of the command buttons such as +, - , MC, MR are
commonly found in an ordinary calculator, a user should have no problem in
manipulating the buttons.
 A lot of programmers like to use a meaningful name for the Name
Property may be because it is easier for them to write and read the event
procedure and easier to debug or modify the programs later. However, it is
not a must to do that as long as you label your objects clearly and use
comments in the program whenever you feel necessary. T
 One more important property is whether the control is enabled or
not.

76
Finally, you must also considering making the control visible or invisible at
runtime, or when should it become visible or invisible.

2. Handling some of the common controls

2.1 The Text Box


The text box is the standard control for accepting input from the user as well
as to display the output. It can handle string (text) and numeric data but not
images or pictures. String in a text box can be converted to a numeric data
by using the function Val(text). The following example illustrates a simple
program that processes the input from the user.
Example 1
Private Sub Command1_Click()
Sum = Val(Text1.Text) + Val(Text2.Text) ‘To add the values in text box 1 and text
box 2
Label1.Caption = Sum ‘To display the answer on label 1
End Sub
In this program, two text boxes are inserted into the form together with a
few labels. The two text boxes are used to accept inputs from the user and
one of the labels will be used to display the sum of two numbers that are
entered into the two text boxes. Besides, a command button is also
programmed to calculate the sum of the two numbers using the plus
operator. The program use creates a variable sum to accept the summation of
values from text box 1 and text box 2.The procedure to calculate and to
display the output on the label is shown below. The output is shown in
Figure 2.1
Figure 2.1

2.2 The Label


The label is a very useful control for Visual Basic, as it is not only used to
provide instructions and guides to the users, it can also be used to display
outputs. One of its most important properties is Caption. Using the syntax
label.Caption, it can display text and numeric data . You can change its
caption in the properties window and also at runtime. Please refer to
Example 3.1 and Figure 3.1 for the usage of label.
2.3 The Command Button

77
The command button is one of the most important controls as it is used to
execute commands. It displays an illusion that the button is pressed when
the user click on it. The most common event associated with the command
button is the Click event, and the syntax for the procedure is
Private Sub Command1_Click ()
Statements
End Sub

2.4 The Picture Box


The Picture Box is one of the controls that is used to handle graphics. You
can load a picture at design phase by clicking on the picture item in the
properties window and select the picture from the selected folder. You can
also load the picture at runtime using the LoadPicture method. For
example, the statement will load the picture grape.gif into the picture box.
Picture1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")

You will learn more about the picture box in future lessons. The image in the
picture box is not resizable.
2.5 The Image Box
The Image Box is another control that handles images and pictures. It
functions almost identically to the picture box. However, there is one major
difference, the image in an Image Box is stretchable, which means it can be
resized. This feature is not available in the Picture Box. Similar to the
Picture Box, it can also use the LoadPicture method to load the picture. For
example, the statement loads the picture grape.gif into the image box.
Image1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")

2.6 The List Box

The function of the List Box is to present a list of items where the user can
click and select the items from the list. In order to add items to the list, we
can use the AddItem method. For example, if you wish to add a number of
items to list box 1, you can key in the following statements

Example 2.2
Private Sub Form_Load ( )

List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”

End Sub

78
The items in the list box can be identified by the ListIndex property, the
value of the ListIndex for the first item is 0, the second item has a ListIndex
1, and the second item has a ListIndex 2 and so on

2.7 The Combo Box


The function of the Combo Box is also to present a list of items where the
user can click and select the items from the list. However, the user needs to
click on the small arrowhead on the right of the combo box to see the items
which are presented in a drop-down list. In order to add items to the list, you
can also use the AddItem method. For example, if you wish to add a
number of items to Combo box 1, you can key in the following statements

Example 2.3

Private Sub Form_Load ( )


Combo1.AddItem “Item1”
Combo1.AddItem “Item2”
Combo1.AddItem “Item3”
Combo1.AddItem “Item4”
End Sub

2.8 The Check Box

The Check Box control lets the user selects or unselects an option. When
the Check Box is checked, its value is set to 1 and when it is unchecked, the
value is set to 0. You can include the statements Check1.Value=1 to mark
the Check Box and Check1.Value=0 to unmark the Check Box, as well as
use them to initiate certain actions. For example, the program will change
the background color of the form to red when the check box is unchecked
and it will change to blue when the check box is checked. You will learn
about the conditional statement If….Then….Elesif in later lesson. VbRed
and vbBlue are color constants and BackColor is the background color
property of the form.

Example 2.4

Private Sub Command1_Click()


If Check1.Value = 1 And Check2.Value = 0 Then
MsgBox "Apple is selected"
ElseIf Check2.Value = 1 And Check1.Value = 0 Then
MsgBox "Orange is selected"
Else
MsgBox "All are selected"
End If
End Sub

79
2.9 The Option Box

The Option Box control also lets the user selects one of the choices.
However, two or more Option Boxes must work together because as one of
the Option Boxes is selected, the other Option Boxes will be unselected. In
fact, only one Option Box can be selected at one time. When an option box
is selected, its value is set to “True” and when it is unselected; its value is
set to “False”. In the following example, the shape control is placed in the
form together with six Option Boxes. When the user clicks on different
option boxes, different shapes will appear. The values of the shape control
are 0, 1, and 2,3,4,5 which will make it appear as a rectangle, a square, an
oval shape, a rounded rectangle and a rounded square respectively.

Example 2.5
Private Sub Option1_Click ( )
Shape1.Shape = 0
End Sub
Private Sub Option2_Click()
Shape1.Shape = 1
End Sub
Private Sub Option3_Click()
Shape1.Shape = 2
End Sub
Private Sub Option4_Click()
Shape1.Shape = 3
End Sub
Private Sub Option5_Click()
Shape1.Shape = 4
End Sub
Private Sub Option6_Click()
Shape1.Shape = 5
End Sub
2.10 The Drive List Box
The Drive ListBox is for displaying a list of drives available in your
computer. When you place this control into the form and run the program,
you will be able to select different drives from your computer as shown in
Figure 2.2
Figure 2.2 The Drive List Box

80
2.11 The Directory List Box

The Directory List Box is for displaying the list of directories or folders in a
selected drive. When you place this control into the form and run the
program, you will be able to select different directories from a selected drive
in your computer as shown in Figure 2.3

Figure 2.3 The Directory List Box

3. Visual Basic Data Types


3.1. Numeric Data Types
Numeric data types are types of data that consist of numbers, which can be
computed mathematically with various standard operators such as add,
minus, multiply, divide and more. Examples of numeric data types are
examination marks, height, weight, the number of students in a class, share
values, price of goods, monthly bills, fees and others. In Visual Basic,
numeric data are divided into 7 types, depending on the range of values they
can store.

Table 3.1: Numeric Data Types

Type Storage Range of Values


Byte 1 byte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648

81
-3.402823E+38 to -1.401298E-45 for negative values
Single 4 bytes
1.401298E-45 to 3.402823E+38 for positive values.
-1.79769313486232e+308 to -4.94065645841247E-324 for negative values
Double 8 bytes
4.94065645841247E-324 to 1.79769313486232e+308 for positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
+/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use
Decimal 12 bytes
+/- 7.9228162514264337593543950335 (28 decimal places).
3.2 Non-numeric Data Types
Nonnumeric data types are data that cannot be manipulated mathematically
using standard arithmetic operators. The non-numeric data comprises text
or string data types, the Date data types, the Boolean data types that store
only two values (true or false), Object data type and Variant data type .They
are summarized in Table

Table 3.2: Nonnumeric Data Types


Data Type Storage Range
String(fixed length) Length of string 1 to 65,400 characters
String(variable length) Length + 10 bytes 0 to 2 billion characters
Date 8 bytes January 1, 100 to December 31, 9999
Boolean 2 bytes True or False
Object 4 bytes Any embedded object
Variant(numeric) 16 bytes Any value as large as Double
Variant(text) Length+22 bytes Same as variable-length string
3.3 Suffixes for Literals
Literals are values that you assign to data. In some cases, we need to add a
suffix behind a literal so that VB can handle the calculation more accurately.
For example, we can use num=1.3089# for a Double type data. Some of the
suffixes are displayed in Table 3.3.
Table 3.3

Suffix Data Type

& Long

! Single

# Double

@ Currency

82
In addition, we need to enclose string literals within two quotations and date
and time literals within two # sign. Strings can contain any characters,
including numbers. The following are few examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#

3.2 Managing Variables

Variables are like mail boxes in the post office. The contents of the variables
changes every now and then, just like the mail boxes. In term of VB,
variables are areas allocated by the computer memory to hold data. Like the
mail boxes, each variable must be given a name. To name a variable in
Visual Basic, you have to follow a set of rules.

3.2.1 Variable Names

The following are the rules when naming the variables in Visual Basic
 It must be less than 255 characters
 No spacing is allowed
 It must not begin with a number
 Period is not permitted

Examples of valid and invalid variable names are displayed in Table 3.4

Table 3.4

Valid Name Invalid Name


My_Car My.Car
ThisYear 1NewBoy
He&HisFather
Long_Name_Can_beUSE
*& is not acceptable

3.2.2 Declaring Variables

In Visual Basic, one needs to declare the variables before using them by
assigning names and data types. They are normally declared in the general
section of the codes' windows using the Dim statement.
The format is as follows:
Dim Variable Name As Data Type

83
Example 3.1

Dim password As String


Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date

You may also combine them in one line , separating each variable with a
comma, as follows:

Dim password As String, yourName As String, firstnum As Integer,.............

If data type is not specified, VB will automatically declare the variable as a


Variant.
For string declaration, there are two possible formats, one for the variable-
length string and another for the fixed-length string. For the variable-length
string, just use the same format as example 3.1 above. However, for the
fixed-length string, you have to use the format as shown below:

Dim VariableName as String * n, where n defines the number of characters


the string can hold.

Example 3.2:

Dim yourName as String * 10

yourName can holds no more than 10 Characters.

3.2.3 Assigning Values to Variables


After declaring various variables using the Dim statements, we can assign
values to those variables. The general format of an assignment is
Variable=Expression
The variable can be a declared variable or a control property value. The
expression could be a mathematical expression, a number, a string, a
Boolean value (true or false) and more. The following are some examples:
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text

84
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber
3.2.4 Constants

Constants are different from variables in the sense that their values do not
change during the running of the program.

Declaring a Constant

The format to declare a constant is

Const Constant Name As Data Type = Value

Example 5.3
Const Pi As Single=3.142
Const Temp As Single=37
Const Score As Single=100

4. Operators in Visual Basic

To compute inputs from users and to generate results, we need to use


various mathematical operators. In Visual Basic, except for + and -, the
symbols for the operators are different from normal mathematical operators,
as shown in Table 4.1.

Table 4.1: Arithmetic Operators

Mathematical function Example


Operator
Exponential 2^4=16
^
Multiplication 4*3=12, (5*6))2=60
*
Division 12/4=3
/
Modulus(return the remainder from an 15 Mod 4=3
Mod integer division)

Integer Division(discards the decimal


19\4=4
\ places)
String concatenation "Visual"&"Basic"="Visual Basic"
+ or &

Example 4.1

85
Dim firstName As String
Dim secondName As String
Dim yourName As String
Private Sub Command1_Click()
firstName = Text1.Text
secondName = Text2.Text
yourName = secondName + " " + firstName
Label1.Caption = yourName
End Sub

In this example, three variables are declared as string. For variables


firstName and secondName will receive their data from the user’s input into
textbox1 and textbox2, and the variable yourName will be assigned the data
by combining the first two variables. Finally, yourName is displayed on
Label1.

Example 4.2

Dim number1, number2, number3 as Integer


Dim total, average as variant
Private sub Form_Click
number1=val(Text1.Text)
number2=val(Text2.Text)
number3= val(Text3.Text)
Total=number1+number2+number3
Average=Total/5
Label1.Caption=Total
Label2.Caption=Average
End Sub

In the example above, three variables are declared as integer and two
variables are declared as variant. Variant means the variable can hold any
data type. The program computes the total and average of the three numbers
that are entered into three text boxes.

5. Conditional Operators

To control the VB program flow, we can use various conditional operators.


Basically, they resemble mathematical operators. Conditional operators are
very powerful tools, they let the VB program compare data values and then
decide what action to take, whether to execute a program or terminate the
program and more. These operators are shown in Table 5.1.

86
Logical Operators

In addition to conditional operators, there are a few logical


operators which offer added power to the VB programs.
There are shown in Table 5.2.

Table 5.1: Conditional Operators Table 5.2:Logical Operators

Operator
Meaning Operator Meaning
=
Equal to And Both sides must be true
>
More than One side or other must be
or
true
<
Less Than
One side or other must be
>= Xor
More than and equal true but not both
<= Not Negates truth
Less than and equal
<>
Not Equal to

* You can also compare strings with the above operators. However, there are
certain rules to follows: Upper case letters are less than lowercase letters,
"A"<"B"<"C"<"D".......<"Z" and number are less than letters.
5.2 Using If.....Then.....Else Statements with Operators

To effectively control the VB program flow, we shall use If...Then...Else


statement together with the conditional operators and logical operators.
The general format for the if...then...else statement is

If conditions Then
VB expressions
Else
VB expressions
End If

* any If..Then..Else statement must end with End If. Sometime it is not
necessary to use Else.

87
Example:

Private Sub OK_Click()


firstnum=Val(usernum1.Text)
secondnum=Val(usernum2.Text)
If total=firstnum+secondnum And Val(sum.Text)<>0 Then
correct.Visible = True
wrong.Visible = False
Else
correct.Visible = False
wrong.Visible = True
End If
End Sub
The format of the Select Case control structure is show below:
Select Case expression
Case value1
Block of one or more VB statements
Case value2
Block of one or more VB Statements
Case value3
.
Case Else
Block of one or more VB Statements
End Select
Example 5.1

Dim grade As String


Private Sub Compute_Click( )
grade=txtgrade.Text
Select Case grade
Case "A"
result.Caption="High Distinction"
Case "A-"
result.Caption="Distinction"
Case "B"
result.Caption="Credit"
Case "C"
result.Caption="Pass"
Case Else
result.Caption="Fail"
End Select
End Sub
Example 5.2
Dim mark As Single

88
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text
Select Case mark
Case Is >= 85
comment.Caption = "Excellence"
Case Is >= 70
comment.Caption = "Good"
Case Is >= 60
comment.Caption = "Above Average"
Case Is >= 50
comment.Caption = "Average"
Case Else
comment.Caption = "Need to work harder"
End Select
End Sub
Example 5.3

Example 5.2 could be rewritten as follows:

Dim mark As Single


Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text
Select Case mark
Case 0 to 49
comment.Caption = "Need to work harder"
Case 50 to 59
comment.Caption = "Average"
Case 60 to 69
comment.Caption = "Above Average"
Case 70 to 84
comment.Caption = "Good"
Case Else
comment.Caption = "Excellence"
End Select
End Sub
6. LOOPING
Visual Basic allows a procedure to be repeated many times as long as the
processor until a condition or a set of conditions is fulfilled. This is
generally called looping . Looping is a very useful feature of Visual Basic
because it makes repetitive works easier. There are two kinds of loops in
Visual Basic, the Do...Loop and the For.......Next loop
6.1 Do Loop
The formats are

89
a) Do While condition
Block of one or more VB statements
Loop
b) Do
Block of one or more VB statements
Loop While condition
c) Do Until condition
Block of one or more VB statements
Loop
d) Do
Block of one or more VB statements
Loop Until condition
6.2 Exiting the Loop
Sometime we need exit to exit a loop prematurely because of a certain
condition is fulfilled. The syntax to use is known as Exit Do. You can
examine Example 6.1 & 6.2 for its usage.
Example 6.1
Do while counter <=1000
num.Text=counter
counter =counter+1
Loop
* The above example will keep on adding until counter >1000.
The above example can be rewritten as
Do
num.Text=counter
counter=counter+1
Loop until counter>1000
Example 6.2
Dim sum, n As Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
Do
n=n+1
Sum = Sum + n
List1.AddItem n & vbTab & Sum
If n = 100 Then
Exit Do
End If
Loop
End Sub
Explanation

90
In the above example, we compute the summation of 1+2+3+4+……+100.
In the design stage, you need to insert a ListBox into the form for displaying
the output, named List1. The program uses the AddItem method to populate
the ListBox. The statement List1.AddItem "n" & vbTab & "sum" will
display the headings in the ListBox, where it uses the vbTab function to
create a space between the headings n and sum.

6.3 For....Next Loop


The format is:

For counter=startNumber to endNumber (Step increment)


One or more VB statements
Next
Please refer to example 6.3a,6.3b and 6.3 c for its usage.
Sometimes the user might want to get out from the loop before the whole
repetitive process is executed, the command to use is Exit For. To exit a
For….Next Loop, you can place the Exit For statement within the loop; and
it is normally used together with the If…..Then… statement. Let’s examine
example 6.3
Example 6.3 a
For counter=1 to 10
display.Text=counter
Next
Example 6.3 b
For counter=1 to 1000 step 10
counter=counter+1
Next
Example 6.3 c
For counter=1000 to 5 step -5
counter=counter-10
Next
*Notice that increment can be negative
Example 6.3 d
Private Sub Form_Activate( )
For n=1 to 10
If n>6 then
Exit For
End If
Else
Print n
End If
End Sub

91
7. VB Built-in Functions
A function is similar to a normal procedure but the main purpose of the
function is to accept a certain input from the user and return a value
which is passed on to the main program to finish the execution. There
are two types of functions, the built-in functions (or internal functions)
and the functions created by the programmers.

The general format of a function is


FunctionName (arguments)

The arguments are values that are passed on to the function. We will learn
two very basic but useful internal functions of Visual basic , i.e. the
MsgBox( ) and InputBox ( ) functions. MsgBox ( ) Function

The objective of MsgBox is to produce a pop-up message box and prompt


the user to click on a command button before he /she can continues. This
format is as follows: yourMsg=MsgBox(Prompt, Style Value,
Title)
The first argument, Prompt, will display the message in the
message box. The Style Value will determine what type of
command buttons appear on the message box, please refer
table 7.1 for types of command button displayed. The Title
argument will display the title of the message board.

Table 7.1: Style Values


Named Constant Buttons Displayed
Style Value
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons

We can use named constant in place of integers for the second argument to
make the programs more readable. In fact, VB6 will automatically shows up
a list of names constant where you can select one of them.

Example: yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup


Menu")

and yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup


Menu")

92
are the same. yourMsg is a variable that holds values that are returned by
the MsgBox ( ) function. The values are determined by the type of buttons
being clicked by the users. It has to be declared as Integer data type in the
procedure or in the general declaration section. Table 7.2 shows the values,
the corresponding named constant and buttons

Table 7.2: Return Values and Command Buttons


Value Named Constant Button Clicked
1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button

To make the message box looks more sophisticated, you can add an icon
besides the message. There are four types of icons available in VB as shown
in table 7.3
Table 10.3
Value Named Constant
Icon
16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation
Example 7.1
Private Sub test2_Click()
Dim testMsg2 As Integer
testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation,
"Test Message")
If testMsg2 = 6 Then
display2.Caption = "Testing successful"
ElseIf testMsg2 = 7 Then
display2.Caption = "Are you sure?"
Else
display2.Caption = "Testing fail"
End If

93
End Sub ;

In this example, the following message box will be displayed

Figure 7.1

The InputBox( ) Function


An InputBox( ) function will display a message box where the user can enter
a value or a message in the form of text. The format is
myMessage=InputBox(Prompt, Title, default_text, x-position, y-
position)
myMessage is a variant data type but typically it is declared as string, which
accept the message input by the users. The arguments are explained as
follows:
Prompt - The message displayed normally as a question asked.
 Title - The title of the Input Box.
 default-text - The default text that appears in the input field where
users can use it as his intended input or he may change to the message he
wish to key in.
 x-position and y-position - the position or the coordinate of the input
box.

Example 7.2
Create the following Interface
Figure 7.2

The procedure for the OK button


Private Sub OK_Click()
Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form",
"Enter your messge here", 500, 700)

94
If userMsg <> "" Then
message.Caption = userMsg
Else
message.Caption = "No Message"
End If

End Sub

When a user click the OK button, the input box as shown in Figure 10.5 will
appear. After user entering the message and click OK, the message will be
displayed on the caption, if he click Cancel, "No message" will be
displayed.

8. Mathematical Functions
The mathematical functions are very useful and important in programming
because very often we need to deal with mathematical concepts in
programming such as chance and probability, variables, mathematical
logics, calculations, coordinates, time intervals and etc. The common
mathematical functions in Visual Basic are Rnd, Sqr, Int, Abs, Exp,
Log, Sin, Cos, Tan , Atn, Fix and Round.
Rnd is very useful when we deal with the concept of chance and
probability. The Rnd function returns a random value between 0 and 1. In
Example 1. When you run the program, you will get an output of 10
random numbers between 0 and 1. Randomize Timer is a vital statement
here as it will randomize the process.

The Numeric Functions


The numeric functions are Int, Sqr, Abs, Exp, Fix, Round and Log.

a) Int is the function that converts a number into an integer by truncating its
decimal part and the resulting integer is the largest integer that is smaller
than the number. For example, Int(2.4)=2, Int(4.8)=4, Int(-4.6)= -5,
Int(0.032)=0 and so on.
b) Sqr is the function that computes the square root of a number. For
example, Sqr(4)=2, Sqr(9)=2 and etc.

95
c) Abs is the function that returns the absolute value of a number. So Abs(-
8) = 8 and Abs(8)= 8.
d) Exp of a number x is the value of ex. For example, Exp(1)=e1 =
2.7182818284590
e) Fix and Int are the same if the number is a positive number as both
truncate the decimal part of the number and return an integer. However,
when the number is negative, it will return the smallest integer that is larger
than the number. For example, Fix(-6.34)= -6 while Int(-6.34)=-7.
f) Round is the function that rounds up a number to a certain number of
decimal places. The Format is Round (n, m) which means to round a number
n to m decimal places. For example, Round (7.2567, 2) =7.26
g) Log is the function that returns the natural Logarithm of a number. For
example,
Log 10= 2.302585
9.
String Manipulation Functions
In this lesson, we will learn how to use some of the string manipulation
function such as Len, Right, Left, Mid, Trim, Ltrim, Rtrim, Ucase, Lcase,
Instr, Val, Str ,Chr and Asc.
(i)The Len Function
The length function returns an integer value which is the length of a phrase
or a sentence, including the empty spaces. The format is
Len (“Phrase”)
For example,
Len (VisualBasic) = 11 and Len (welcome to VB tutorial) = 22
The Len function can also return the number of digits or memory locations
of a number that is stored in the computer. For example,
Private sub Form_Activate ( )
X=sqr (16)
Y=1234
Z#=10#
Print Len(x), Len(y), and Len (z)
End Sub
will produce the output 1, 4 , 8. The reason why the last value is 8 is
because z# is a double precision number and so it is allocated more memory
spaces.

96
(ii) The Right Function :The Right function extracts the right portion of a
phrase. The format is
Right (“Phrase”, n)
Where n is the starting position from the right of the phase where the portion
of the phrase is going to be extracted. For example,
Right(“Visual Basic”, 4) = asic
(iii)The Left Function
The Left$ function extract the left portion of a phrase. The format is
Left(“Phrase”, n)
Where n is the starting position from the left of the phase where the portion
of the phrase is going to be extracted. For example,
Left (“Visual Basic”, 4) = Visu
(iv) The Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the phrase.
The format is
Ltrim(“Phrase”)
.For example,
Ltrim (“ Visual Basic”, 4)= Visual basic
(v) The Rtrim Function
The Rtrim function trims the empty spaces of the right portion of the phrase.
The format is
Rtrim(“Phrase”)
.For example,
Rtrim (“Visual Basic ”, 4) = Visual basic
(vi) The Trim function
The Ttrim function trims the empty spaces on both side of the phrase. The
format is
Trim(“Phrase”)
.For example,
Trim (“ Visual Basic ”) = Visual basic
(viii) The Mid Function
The Mid function extracts a substring from the original phrase or string. It
takes the following format:
Mid(phrase, position, n)

97
Where position is the starting position of the phrase from which the
extraction process will start and n is the number of characters to be
extracted. For example,
Mid(“Visual Basic”, 3, 6) = ual Bas
(ix) The InStr function
The InStr function looks for a phrase that is embedded within the original
phrase and returns the starting position of the embedded phrase. The format
is
Instr (n, original phase, embedded phrase)
Where n is the position where the Instr function will begin to look for the
embedded phrase. For example
Instr(1, “Visual Basic”,” Basic”)=8
(x) The Ucase and the Lcase functions
The Ucase function converts all the characters of a string to capital letters.
On the other hand, the Lcase function converts all the characters of a string
to small letters. For example,
Ucase(“Visual Basic”) =VISUAL BASiC
Lcase(“Visual Basic”) =visual basic
(xi) The Str and Val functions
The Str is the function that converts a number to a string while the Val
function converts a string to a number. The two functions are important
when we need to perform mathematical operations.
(xii) The Chr and the Asc functions
The Chr function returns the string that corresponds to an ASCII code
while the Asc function converts an ASCII character or symbol to the
corresponding ASCII code. ASCII stands for “American Standard Code for
Information Interchange”. Altogether there are 255 ASCII codes and as
many ASCII characters. Some of the characters may not be displayed as
they may represent some actions such as the pressing of a key or produce a
beep sound. The format of the Chr function is
Chr(charcode)
and the format of the Asc function is
Asc(Character)
The following are some examples:
Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc(“B”)=66, Asc(“&”)=38
10. Creating User-Defined Functions
Creating Your Own Function
The general format of a function is as follows:
Public Function functionName (Arg As dataType,..........) As dataType

98
or
Private Function functionName (Arg As dataType,..........) As dataType
* Public indicates that the function is applicable to the whole project and
Private indicates that the function is only applicable to a certain module or
procedure.

99
CS8481 DATABASE MANAGEMENT SYSTEMS LAB

10. CASE STUDIES (APPLICATION DEVELOPMENT USING


ORACLE/ MYSQL )

Aim : Develop the following applications using Oracle as a back end and
Visual Basic as front end Tool.

a) Inventory Control System


b) Banking System
c) Library Management System
b) Material Requirement Processing.
c) Hospital Management System.
d) Railway Reservation System.
e) Personal Information System.
f) Web Based User Identification System.
g) Timetable Management System.
h) Hotel Management System

Example :-

Design and implementation of Inventory Control System.

1. Create a Employee database with all the constraints and relations.

2. Design a Form using VB, perform the database connectivity and do


the following operations:

a. Employee should be able to view his personal details and calculate


salary.
b. Administrator should be able to update the database(Eg. Salary
Details).
c. Employee may work in different branch and may be designated
different for different projects.
d. Employee should be able to view his tax details.

Design and implementation of Banking System.

1. Create a Banking database with all the constraints and relations.

2. Design a Form using VB, perform the database connectivity and do


the following operations:
(i) Bank Manager should be able to create and
delete an account.
CS8481 DATABASE MANAGEMENT SYSTEMS LAB

(ii) Customer should be able to deposit and


withdraw money from account
(iii) Customer should be able to view balance
enquiry.
(iv) Customer should be able to view the loan
details.
(v) Bank manager should check the loan payments
monthly.
Design and implementation of Library Information System.

1. Create a Library Information database with all the constraints and


relations.

2. Design a Form using VB, perform the database connectivity and do


the following operations:

(i) Librarian should be able to insert a new student


record or update student details.
(ii) Student can a search an book by using author
name or book name.
(iii) Librarian can check the identity of the student
(iv) Librarian can issue/return a book.
(v) Each student can take maximum of 5 books.
(vi) Fine should be calculated by librarian.( per day
25 paise for one book)
CS8481 DATABASE MANAGEMENT SYSTEMS LAB

Date: MINI PROJECT


TIME TABLE MANAGEMENT SYSTEMS
AIM:
To design and implement the application, ‘Time table management system’
using Oracle as a back end (data base) and Microsoft Visual Basic 6.0 as a
Front end.
PROCEDURE:
1. Create an class time table database with the following fields in Oracle
namely sno,day,period 1,period 2,period 3,period 4,period 5 and insert
some record into the database.
2. Design the corresponding form with labels ,text boxes and command
buttons.
Form1 Class time table
3. Connect the back end with the front end using DAO method by creating
a dsn as follows
a .Select Administrative Tools option from Control Panel . Then click on
Data
Sources (ODBC), which displays a dialog box named ODBC
DataSourceAdministrator in which click Add button.
b. In Create New Data Source dialog box, select “Microsoft ODBC for
ORACLE”and click finish button.
c. Give a suitable Data Source Name ,username and server name.
4. Perform the required operations like add,update,find,edit,delete,movefirst,
movenext,
moveprevious, movelast, deposit and withdraw.
5. Perform the transaction in banking system.
6. Execute the project.

TABLE DESIGN:
Table Name: Time table
Name Type
----------------------------------- ---------------------------
SNO NUMBER(4)
DAY VARCHAR2(15)
PERIOD 1 VARCHAR2(25)
CS8481 DATABASE MANAGEMENT SYSTEMS LAB

PERIOD 2 VARCHAR2(25)
PERIOD 3 VARCHAR2(25)
PERIOD 4 VARCHAR2(25)
PERIOD 5 VARCHAR2(25)

FORM 1:
Dim DB As Database
Dim RS AsRecordset

Private Sub Form_Load() //DATABASE CONNECTION AND RETRIEVAL


OF RECORD
Set DB = OpenDatabase("xyz",FALSE,FALSE,”ODBC;UID=system
;PWD= ;”)
Set RS = DB.OpenRecordset("SELECT * FROM CLASS1")
Text1.Text = RS(0)
Text2.Text = RS(1)
Text3.Text = RS(2)
Text4.Text = RS(3)
Text5.Text = RS(4)
Text6.Text = RS(5)
Text7.Text = RS(6)
End Sub

Private Sub add_Click()


rs.MoveLast
rs.AddNew
rs(0) = Text1.Text
rs(1) = Text2.Text
rs(2) = Text3.Text
rs(3) = Text4.Text
rs(4) = Text5.Text
rs(5) = Text6.Text
rs(6) = Text7.Text
MsgBox "record is inserted"
rs.update
End Sub

Private Sub update_Click()


rs.edit
rs(0) = Text1.Text
rs(1) = Text2.Text
rs(2) = Text3.Text
rs(3) = Text4.Text
rs(4) = Text5.Text
rs(5) = Text6.Text
rs(6) = Text7.Text
CS8481 DATABASE MANAGEMENT SYSTEMS LAB

rs.update
MsgBox "the record is updated"
End Sub

Private Sub find_Click()


I = InputBox("ENTER THE sno", "FIND")
rs.FindFirst "[sno]=" & I
If rs.NoMatch Then
MsgBox "no such records"
Else
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
Text5.Text = rs(4)
Text6.Text = rs(5)
Text7.Text = rs(6)
End If
End Sub

Private Sub delete_Click()


rs.delete
MsgBox "the record is deleted"
rs.MoveNext
If rs.EOF Then
MsgBox "no more records"
Else
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
Text5.Text = rs(4)
Text6.Text = rs(5)
Text7.Text = rs(6)
End If
End Sub

Private Sub exit_Click()


End
End Sub

Private Sub first_Click()


rs.MoveFirst
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
CS8481 DATABASE MANAGEMENT SYSTEMS LAB

Text4.Text = rs(3)
Text5.Text = rs(4)
Text6.Text = rs(5)
Text7.Text = rs(6)
End Sub

Private Sub next_Click()


rs.MoveNext
If rs.EOF Then
MsgBox "no more records"
Else
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
Text5.Text = rs(4)
Text6.Text = rs(5)
Text7.Text = rs(6)
End If
End Sub

Private Sub previous_Click()


rs.MovePrevious
If rs.BOF Then
MsgBox "no more records"
Else
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
Text5.Text = rs(4)
Text6.Text = rs(5)
Text7.Text = rs(6)
End If
End Sub

Private Sub last_Click()


rs.MoveLast
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
Text5.Text = rs(4)
Text6.Text = rs(5)
CS8481 DATABASE MANAGEMENT SYSTEMS LAB

Text7.Text = rs(6)
End Sub

OUTPUT:
CS8481 DATABASE MANAGEMENT SYSTEMS LAB

RESULT:
Thus, the application of time table management system has been
designed and implemented in visual basic 6.0.

https://www.javatpoint.com/pl-sql-cursor- cursor programs

Anda mungkin juga menyukai