Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DBMS Lab Manual PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

LOYOLA ICAM COLLEGE OF ENGINEERING AND

TECHNOLOGY
Loyola College campus, Nungambakkam, Chennai 34

Database Management Systems Laboratory


LAB MANUAL







DEPARTMENT OF INFORMATION TECHNOLOGY
SUBJECT CODE: IT 6312
SEMESTER: III
Document No:
LICET/IT/LAB
MANUAL/DBMS
LAB [IT6312]

Date of Issue:

Compiled By:

04.07.2016

Ms. Ramya Laurraine. U

Version: 1.1

Date of Revision:

Verified By:

Authorized By

Dr. R. Deepa

HoD IT

IT6312

DATABASE MANAGEMENT SYSTEMS LABORATORY

LTPC
0032

OBJECTIVES:
The student should be made to:
Learn to create and use a database
Be familiarized with a query language
Have hands on experience on DDL Commands
Have a good understanding of DML Commands and DCL commands
Familiarize advanced SQL queries.
Be Exposed to different applications
LIST OF EXPERIMENTS:
1. Creation of a database and writing SQL queries to retrieve information from the database.
2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based
on conditions.
3. Creation of Views, Synonyms, Sequence, Indexes, Save point.
4. Creating an Employee database to set various constraints.
5. Creating relationship between the databases.
6. Study of PL/SQL block.
7. Write a PL/SQL block to satisfy some conditions by accepting input from the user.
8. Write a PL/SQL block that handles all types of exceptions.
9. Creation of Procedures.
10. Creation of database triggers and functions
11. Mini project (Application Development using Oracle/ Mysql )
a) Inventory Control 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
REFERENCE:
spoken-tutorial.org
TOTAL: 45 PERIODS
OUTCOMES:
At the end of the course, the student should be able to:
Design and implement a database schema for a given problem-domain
Populate and query a database
Create and maintain tables using PL/SQL.
Prepare reports.
LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS
HARDWARE:
Standalone desktops
30 Nos.
(or)
Server supporting
30 terminals or more.
SOFTWARE:
Front end: VB/VC ++/JAVA or Equivalent
Back end: Oracle / SQL / MySQL/ PostGress / DB2 or Equivalent

What is a database?
In very simple terms a database is a collection of data stored in some organized fashion.

Database
What is database management system?
It is the database software that allows you to create and manipulate a database. You never access a
database directly. It is the DBMS which accesses the database for you.
What is a table?
A table is a structured file that can store data organized as columns and rows
Eg: for a retail store. You would definitely store customer information and product information in
separate files. Which means you cannot have the same table name twice in a database.
What is a schema?
It consists of the information about the database, table layout and properties and relationship between
the tables
What is a column?
A single field in a table. A table consists of one or more columns. Each column is a piece of
information in the table. Each column has an associated datatype. The datatype can be number, date,
text etc. Eg: customer name will a column in customer table
What is a row?
A record in a table. Eg each customer information will be stored as a single row in a customer table
What is a primary key?
It is a column which uniquely identifies each row in a table. Eg. Each customer will have a unique id
to identify him. So customer id will be the primary key in the customer table
A column can be made the primary if it satisfies the following conditions:

No two rows can have the same primary key value.


Every row must have a primary key value (primary key columns may not allow
NULL values).
Values in primary key columns can never be modified or updated.
Primary key values can never be reused. (If a row is deleted from the table, its
primary key may not be assigned to any new rows in the future.)

What is SQL?
Structured Query Language. It is a language designed specifically for communicating with databases.

Rules: extra white space is ignored.


Sql statements can be broken over multiple lines
Sql statements terminate with semicolon(;)
Sql statements are case-insensitive.
Spaces are not allowed for database or table names. You can use underscore

Common Data Types in SQL:


1. char(n) : Fixed-length character string where n is the no of characters to store.
2. varchar2(n) : Variable-length string
3. int : Integer
4. numeric(p,d) : The number consists of p digits, d of the p digits are to the right of
the decimal point.
5. float(n) : Floating-point number.
6. date : The date containing a date, month and year. Format stored in oracle is ddmon-yy
7. timestamp : The combination of date and time.
Ex. No: 1
Aim: To practice and implement data definition language commands and constraints.
List of DDL Commands
1.
2.
3.
4.
5.
6.

Creating a table
Deleting a table
Altering the contents of the table
Truncating a table
To view table structure
Dropping a table

Create Table
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
we are now going to create a table for the below
student_db table

student_id firstname lastname address








Example:


state


gender


year


dob


degree

CREATE TABLE student_db


( student_id varchar2(5) NOT NULL UNIQUE,
firstname varchar2(10),
lastname varchar2(10),
address varchar2(20),
state varchar2(10),
gender char,
year varchar2(10),
dob date,
degree varchar2(10)
);
Try now DESC table_name;
SQL> DESC student_db;
Name
Null?
Type
----------------------------------------- -------- ---------------STUDENT_ID
FIRSTNAME
LASTNAME
ADDRESS
STATE
GENDER
YEAR
DOB
DEGREE

NOT NULL VARCHAR2(5)


VARCHAR2(10)
VARCHAR2(10)
VARCHAR2(20)
VARCHAR2(10)
CHAR(1)
VARCHAR2(10)
DATE
VARCHAR2(10)

Create table using select statement


CREATE TABLE new_table_name(coulumn_name1, column_name2...)
AS (SELECT column_name1, column_name2... FROM old_table);
Example: CREATE TABLE STUD_DB(student_id,name,degree)
AS (SELECT student_id, firstname, degree FROM student_db);
Name
Null? Type
----------------------------------------- -------- --------------STUDENT_ID
NAME
DEGREE

NOT NULL CHAR(5)


VARCHAR2(10)
VARCHAR2(10)

Alter Table
It is used to used to add, delete, or modify columns in an existing table. it is also used to rename an
existing table.
Add a column:
ALTER TABLE table_name
ADD column_name datatype
Example: alter table stud_db add address varchar2(20); (immediately use desc stud_db)
Table altered.
SQL> desc stud_db;
Name
Null? Type
----------------------------------------- -------- ------------STUDENT_ID
NAME
DEGREE
ADDRESS
Delete a column

NOT NULL CHAR(5)


VARCHAR2(10)
VARCHAR2(10)
VARCHAR2(20)

ALTER TABLE table_name


DROP COLUMN column_name
Example: alter table stud_db drop column degree;(use desc stud_db)
Modify a column
ALTER TABLE table_name
MODIFY column_name datatype
Example: first add a column called gender to stud_db of datatype char, then try the below statement
alter table stud_db modify gender varchar2(6);
Rename a column
ALTER TABLE table_name
RENAME COLUMN old_column_name to new_column_name
Example: first add a column called dob to stud_db and then try the below
Alter table stud_db rename column dob to birthday;
Renaming a table
ALTER TABLE table_name
RENAME TO new_table_name

Example: Alter table stud_db rename to students;(try to run desc stud_db;)


Drop table
This command remove all traces of the table from the database and any other objects associated with
it.(* integrity constraint issue discussed next)
DROP TABLE table_name;
Example:
First create a table called students using create table statement with the select statement;
Drop table students; (try to run desc students;)
Truncate table
This command is used when you want to only delete the data inside the table.(* integrity constraint
issue discussed next)
TRUNCATE TABLE table_name;
Example : you can do this only when you have data inside the table
Truncate table students;
INTEGRITY CONSTRIANTS
Constraints can be defined in two ways:
1. Column level constraint: the constraint is specified immediately after the column definition.
2. Table level constraint: the constraints are specified after all the columns are defined.
Types of constraints
5 types
1.
2.
3.
4.
5.

Not Null
Primary Key
Foreign Key
Check
Unique

1. NOT NULL
This ensures the column will always have a value. Be careful when defining this constraint.
CREATE TABLE table_name
(
column_name1 data_type(size) NOT NULL,
column_name2 data_type(size),
column_name3 data_type(size),
....
);

2. Primary Key: uniquely identifies each row in a table. Does not allow null values. Ensures no
duplicate rows exists
a)
b)
c)
d)

Choose a column whose data values are unique.


This key rarely changes.
Choose a column that does not contain any null values.
Use a sequence number as primary key

In column level
CREATE TABLE table_name
(
column_name1 data_type(size) CONSTRAINT constraint_name PRIMARY KEY,
column_name2 data_type(size),
column_name3 data_type(size),
....
);
In table level
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
CONSTRAINT constraint_name PRIMARY KEY(column_name1, column_name2,...)
);
Lets create a dept_db table
CREATE TABLE dept_db
(deptid varchar2(5) NOT NULL,
deptname varchar2(10),
officenum varchar2(10),
officephone varchar2(10),
institute varchar2(20),
num_of_phd varchar2(5),
CONSTRAINT dept_pk PRIMARY KEY(deptid)
);
(or)
CREATE TABLE dept_db
(deptid varchar2(5) CONSTRAINT dept_pk PRIMARY KEY,
deptname varchar2(10),

officenum varchar2(10),
officephone varchar2(10),
institute varchar2(20),
num_of_phd varchar2(5)
);
Ok now lets try to create a primary key for student_db which we created earlier.
Oh no! Should i now drop the entire table and type the create table statement to add a primary key?
Not needed. You have the ALTER statement
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY(column_name)
Alter table student_db add constraint student_pk primary key(student_id);
3. FOREIGN KEY/REFERENTIAL INTEGRITY

It enforces relationship between tables. To establish parent-child relationship between 2


tables having a common column definition, we make use of this constraint. To implement
this, we should define the column in the parent table as primary key and same column in
the child table as foreign key referring to the corresponding parent entry.

ON DELETE CASCADE (when a referenced parent table row is removed all the child are
removed automatically)

The ON DELETE SET NULL When referenced data in the parent key is deleted, all rows in
the child table that depend on those parent key values have their foreign keys set to null.

ON DELETE NO ACTION (which is the default) prevents deleting a parent when there are
children
ON DELETE RESTRICT means you can't delete a given parent row if a child row exists that
references the value for that parent row
ON UPDATE RESTRICT -- if you try to update the value of a primary key, the update will
be rejected (error) if there exist any rows with a foreign key that references that value
ON UPDATE CASCADE-- if you try to update the value of a primary key, the update will be
accepted, and the updated value will automatically update(cascade) all foreign keys that
references that value

* Drop table and truncate table command will not work when the tables primary key is referenced by
another tables foreign key.
In column level
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),

column_name3 data_type(size) CONSTRAINT constraint_name REFERENCES


referencedtablename2(columnname2)
);
In table level
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
CONSTRAINT constraint_name FOREIGN KEY(column_name) REFERENCES
referencedtablename2(columnname2)
);

univem_db
empid(pk) lastname


roadaddress city


gender
state




salary


doj deptid(fk)

dob


dept_db

officephone institute


deptid(pk) deptname officenum
num_of_phd






Create table univem_db( empid varchar2(10) NOT NULL, lastname varchar2(10), gender char(1),
roadaddress varchar2(20), city varchar2(10), state varchar2(10), salary number(10), dob date, doj
date, deptid varchar2(5), primary key(empid), constraint univfk foreign key(deptid) references
dept_db(deptid) enable);
You can also use alter table command to add foreign key
4. CHECK constraint
Check constraint validates incoming data as they are inserted. You can define as many check
constraints on a single column.
ALTER TABLE tablename ADD CONSTRAINT constraint_name CHECK(condition)
Eg: ALTER TABLE univemp_db ADD CONSTRAINT salconst CHECK(salary>=0);
ALTER TABLE univemp_db ADD CONSTRAINT salconst2 CHECK(salary between 1000 and
10000);
5. UNIQUE constraint
It is the same as primary key ie it does not allow duplicate values. The differences are

There can be only one primary key per table whereas you can have multiple unique
keys per table

Primary key does not accept null values whereas unique key columns can be left
blank.

In column level
CREATE TABLE table_name
(
column_name1 data_type(size) CONSTRAINT constraint_name UNIQUE,
column_name2 data_type(size),
column_name3 data_type(size)
);
In table level
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
CONSTRAINT constraint_name UNIQUE(column_name)
);
ALTER TABLE tablename ADD CONSTRAINT constraint_name UNIQUE(column name);
Viewing the constraints
Select * from ALL_CONSTRAINTS where r_constraint_name in( select constraint_name from
all_constraints where table_name = tablename)
Select constraint_name,table_name,constraint_type from ALL_CONSTRAINTS where
r_constraint_name in( select constraint_name from all_constraints where table_name = student_db)

Here ALL_CONSTRAINTS is the name of table where all constraints are stored.
Removing constraints from a table
ALTER TABLE table_name DROP CONSTRAINT constraint_name;
Enable or Disable constraint
ALTER TABLE table_name ENABLE CONSTRAINT constraint_name;
ALTER TABLE table_name DISABLE CONSTRAINT constraint_name;
Exercise time:

Ex. No: 2
Aim: To study the various DML commands and implement them on the database for
performing Insertion, Deletion, Modifying, Altering, Updating and preserving the integrity constraints
DML commands
a.
b.
c.
d.

Insert
Update
Delete
Select

INSERT INTO

Inserts data into the specified table


Also extracts data from one table and insert it into another

2 ways

Single row insertion


INSERT INTO table_name(col_name1, col_name2,col_name3,)
VALUES(value1,value2,value3);
Rules:
1. Ensure that the datatype of the column and value you are giving is the same
2. Size of data value must be within the columns size.
3. Location in the column list and values list must match
4. All integrity constraints must be followed
a. NOT NULL, UNIQUE,CHECK constraint,Primary Key(unique as well as not
null), referential integrity Eg. When adding a foreign key deptid in
univemp_db, there must be a matching primary key dept_id in the dept_db.
5. Column list is optional. If you are not entering the column list then the values list
must match in order and number.

SQL> alter table student_db rename column address to roadaddress;


Table altered.
SQL> alter table student_db add city varchar2(10);
Table altered.
SQL> alter table student_db rename column year to year_of_join;
Table altered.
SQL> INSERT INTO student_db(student_id, firstname, lastname, roadaddress, city,
state, gender, year_of_join, dob, degree) values('m1001','shobbit','sharma','a51
1','Noida','up','M','2007','01-jan-1991','btech');

Should I remember
the column names!!!


INSERT INTO table_name VALUES (value1,value2,value3,...);
Insert into student_db values('m1002','saaddu','khana','21 lane street','Tamil
Nadu','M','2007','15-mar-1991','btech','chennai');
Insert into student_db values('m1003','James','raj','m21','Tamil Nadu','M','2007','15-mar1991','btech','chennai');
Insert atleast 10 rows into the database

Multiple row insertion


INSERT INTO table_name(col_name1, col_name2,col_nameN)
SELECT col1,col2,col3 from table_name(where condition);

We already have a stud_db table. Now let us perform the above statement to select values
from student_db and copy into stud_sb

INSERT into stud_db(student_id,name,degree)
Select student_id,firstname,degree from student_db;

Lets insert

1000 rows


JUST KIDDING.
But seriously, applications host lakhs of data. Now how do I insert so much of data.
There are GUIs which help in inserting a huge amount of data in seconds.
In SQL statement the below can be used
Inserting using substitution variable
INSERT INTO stud_db(student_id, name, degree) VALUES(&student_id, &name,
&degree);
Run this statement and observe what happens.

The previous statement executed can be run again using /.

INSERT INTO student_db(student_id, firstname,lastname,address,state,gender,year,dob,


degree)VALUES('&student_id', '&firstname', '&lastname', '&address', '&state', '&gender',
'&year', '&dob', '&degree');


Violation of integrity Constraints during insertions and how SQL maintains the data integrity
1. Preserving primary key constraint
2. Preserving referential integrity constraint
3. Preserving the check constraint
1. Insert into student_db values('m1001', 'rajeev','khanna','c001','Tamil Nadu','M','2009','02may-1990','btech');
Output: unique constraint violated.
Reason: the student id is defined as primary for the table. Already m1001 exists. When the above
statement executes it checks for an already existing m1001 and throws the error
2. Univem_db(deptid) is foreign key referencing dept_db(deptid)
Insert into dept_db values(01,cse,101,12344567,kit,12);
Insert into dept_db values(02,me,B102,52234568,kit,13);
Insert into dept_db values(03,EE,C104,86541167,kit,34);
Insert into dept_db values(04,ec,103,54344567,kit,14);
Insert into dept_db values(07,mba,108,12345234,kit,33);
Insert into univem_db values('e10', 'PRAKASH','M','A-12 tank road','delhi,delhi,50000,'11May-1970,12-jun-2000',01);

Now insert the below row and observe what happens.

Insert into univem_db values('e11','mahim','M','b31','delhi,delhi,50000,'11-May-1970,12jun-2000',27);
Output: integrity constraint violated parent key not found.
Reason: because the parent table dept_db does not have the deptid 27. So the child table
univem_db cannot have a deptid 27 which the parent does not have. So insertion will not
happen.
Now change 27 into 01 and insert the row
3. Now add a check constraint on the salary column on univem_db table such that the salary is
always greater than or equal to zero.
ALTER TABLE univem_db
ADD CONSTRAINT salconst CHECK(salary>=0)
Now try to insert a negative value in salary
Insert into univem_db values('e11','mahim','K','b31','delhi,delhi,-50000,'11-May-1970,12jun-2000',01);

Output: check constraint violated


Reason: you tried to insert a row of salary less than zero.
UPDATE statement
This statement is used to modify existing data values of the table rows.
UPDATE table_name
SET col1=value1,col2=value2...
WHERE some_column=some_value
The where clause specifies the selected rows and records that should be updated.
Insert the below 3 row into univem_db table
SQL> Insert into univem_db values('e13','anand','M','24, sans street','delhi','d
elhi',46000,'11-May-1970','12-jun-1990',02);
SQL> Insert into univem_db values('e01,'Rakesh','M','13 radha nagar','delhi','delhi',45000,'11-Jan1970','12-jun-1990',01);
SQL> Insert into univem_db values('e02','Sangna','F','211,'delhi','delhi',47000,'11-Jun-1970','22-Feb1997',02);
Exercise: increase the salary of employees in dept 01 by 2000.
UPDATE univem_db SET salary=salary+2000 where deptid=01;
Exercise: change the roadaddress as 12 rajnagar, city as ghaziabad and state as UP of employee whose
lastname=mahim
UPDATE univem_db SET roadaddress=12 raj nagar, city=ghaziabad,state=up where
lastname=mahim;
Exercise: execute the below statement
UPDATE univem_db SET roadaddress=12 raj nagar, city=ghaziabad,state=up;
Observe what happens. Oops! By mistake we changed everyones address in the table.
If you omit the where clause all the records will be updated.
To revert back use the rollback command
SQL>rollback;
EMPID
LASTNAME G ROADADDRESS
CITY
STATE
---------- ---------- - -------------------- ---------- ---------- ---------DOB
DOJ
DEPTI
--------- --------- ----e10
PRAKASH M A-12 tank road
delhi
delhi
52000
11-MAY-70 12-JUN-00 1

SALARY

e11
mahim
M 12 raj nagar
11-MAY-70 12-JUN-00 1
e13

ghaziabad up

anand

M 24, sans street


delhi
elhi
11-MAY-70 12-JUN-90 2

52000
46000

EMPID
LASTNAME G ROADADDRESS
CITY
STATE
---------- ---------- - -------------------- ---------- ---------- ---------DOB
DOJ
DEPTI
--------- --------- -----

SALARY

e01
Rakesh M 13 radha nagar
delhi
delhi
47000
11-JAN-70 12-JUN-90 1
e02
Sangna F 211
delhi
delhi
47000
11-JUN-70 22-FEB-97 2
Using subqueries in update statement
Exercise: change the salary of employee id e10 equal to the average salary of all the univ employees.
UPDATE univem_db SET salary=(SELECT AVG(salary) from univem_db) where empid=e01;
SALARY
------52000
52000
46000
SALARY
------48800
47000
Exercise: add 4 to the grade of students whose id starts with B
UPDATE grade_db SET grade=grade+4 where studentid in(SELECT studentid FROM grade_db
where studentid like B%);
Using functions in SET clause
Exercise: change the lastname in univem_db table to lowercase
UPDATE univem_db SET lastname=lower(lastname);
DELETE statement
This statement allows you to remove one or more records from the database. You are not allowed to
delete selected fields of a row. Use this statement with caution.
DELETE FROM table_name WHERE condition; - deletes specific rows which satisfy condition
DELETE FROM table_name; - deletes all the rows of the table, but keeps the schema intact

DELETE * FROM table_name; - deletes all the rows of the table, but keeps the schema intact
Example: Delete from stud_db where student_id=m1001;
Preserving referential data integrity while deleting parent table rows.
delete from dept_db where deptid=01;
output: integrity constraint violated - child record found
reason: a child row with deptid 01 is referencing the parent row with deptid 01. If the parent row
deletes the child row will loose its reference. So error is thrown.

Exercise time

Ex. No: 3
Aim: To practice and implement various Select commands

The select statement
Its purpose is to retrieve information from one or more tables.
It deals with what data to retrieve, what order to arrange data, what calculations to be performed on
retrieved data.

SELECT[DISTINCT] column_list FROM table-name


[WHERE search_condition]
[ORDER BY column_list]
[GROUP BY column list]
[HAVING condition];

SELECT clause is mandatory

table-name is the name of the table from which the information is retrieved.

column_list includes one or more columns from which data is retrieved.

WHERE clause includes a comparison predicate (search condition), ehic restricts the
rows/tuples returned by the query.

GROUP BY clause is used to project rows having common values into a smaller set pf
rows and it is frequently used with SQL aggregation function.

WHERE clause is applied before the GROUP BY clause

HAVING clause includes a predicate to filter rows resulting from the GROUP BY clause.
Because it acts on results of the GROUP BY clause, aggregation functions can be used in
the HAVING clause predicate.

ORDER BY clause which columns are used to sort the resulting data and in which order
to they should be sorted

DISTINCT clause is used to eliminate duplicate rows from the result.

Simple select
Exercise:retrieve the student id, firstname and lastname
SELECT student_id,firstname,lastname from student_db;
Changing order of the retrieved columns
Exercise: retrieve the studentid,lastname,firstname from student_db;
SELECT student_id,lastname,firstname from student_dbl
Get all the columns/attributes of the table
SELECT * from student_db;
Give aliases to the column names
Exercise:Display the studentid and firstname as ROLLNO and NAME
SELECT studentid as ROLLNO,firstname as NAME from student_db;

Derived column(computer) in select statement


Exercise: calculate the age of the student;
SELECT student_id,firstname,(SYSDATE-dob)/365 from student_db;
SELECT student_id,firstname,(SYSDATE-dob)/365 age from student_db;
Handling duplicates: using the DISTINCT clause
Exercise: which are the different states from where the students have come
SELECT DISTINCT state from student_db;
DISTINCT (vs) ALL
SELECT ALL state from student_db;
Where clause
Exercise: retrieve the record of all those students who belong to UP
SELECT * from student_db where state=up;
Exercise: retrieve the record of all those students who are doing btech
SELECT * from student_db where degree=btech;
OPERATORS
Relational/conditional operators(=,<,>,<=,>=,<>)
Exercise: find the doj of employee rakesh
SELECT lastname,doj from univem_db where lastname=rakesh;
Exercise: find all employee with salary less than 60000
SELECT lastname,salary from univem_db where salary<60000;
Exercise: find the names of employees whose name is greater than N
SELECT lastname from univem_db where lastname>N;
Logical operators(AND,OR,NOT)
Exercise: list all the employees having firstname greater than N and salary less than 60000
SELECT lastname,salary from univem_db where lastname>N AND salary<60000;
Exercise: list all the employees having firstname greater than N or salary less than 60000
SELECT lastname,salary from univem_db where lastname>N OR salary<60000;
Concatenation operator(concatenate two or more strings - ||)

Add a column firstname to the univem_db and update the firstname for each employee;
alter table univem_db add firstname varchar2(20);
update table univem_db set firstname='dev' where empid='e02';
select (firstname||' '||lastname) as name from univem_db;
BETWEEN operator and Select statement
BETWEEN is a range test operator. It returns those rows which fall within a specified range. It
requires both BETWEEN and AND keyword.
Exercise: retrieve all employees who have salary between 50000 and 60000.
Select firstname,salary from univem_db where salary between 50000 and 60000;
Convert the above query using relational operators
Select firstname,salary from univem_db where salary>=50000 and salary<=60000;
IN operator
This operator allows us to check values in a given set.
Exercise: List all employees who belong to states UP and Delhi
Select firstname,state from univem_db where state IN (UP,delhi);
Convert the above query using logical operator
Select firstname,state from univem_db where state =UP OR state=delhi;
LIKE operator
Pattern matching is important in searching. LIKE operator allows to match string patterns in given
columns.
Characters used along with LIKE operator
% - to define wildcards(missing letters in the pattern) both before and after the pattern.
_ - the _ matches a single character in pattern.
You can mix and match combination of _ and % in a pattern.
$ $ is used as escape sequence. To find a pattern er% then use er$%
Exercise: select all those students having firstname starting from character A
SELECT firstname,lastname from univem_db where firstname LIKE A%;
Pattern is case sensitive.
Exercise: find all those students whose firstname ends with character V

SELECT firstname,lastname from univem_db where firstname LIKE %V;


Exercise: find all students who have their firstname starting in character A and ending in character
D
SELECT firstname,lastname from univem_db where firstname LIKE A%D;
Exercise: find all those students whose 2nd,3rd and 5th characters are A , K and S respectively
Select firstname,lastname from univem_db where lastname LIKE '_ak_s%';
IS NULL and IS NOT NULL operators
Exercise: display all records whose state value is not updated
Select firstname,lastname from univem_db where state IS NULL;
NOT logical operator is used to reverse the meaning of IS NULL;
Exercise: display all records who have values in state column
Select firstname,lastname from univem_db where state IS NOT NULL;

Ex.No 4 a
Aim: To perform Select using inbuilt functions.
DATE FUNCTION
1. Add_month

This function returns a date after adding a specified date with specified number of
months. Syntax: Add_months(d,n); where d-date n-number of months
Example: Select add_months(sysdate,2) from dual;
ADD_MONTH
--------15-SEP-15
2. last_day
It displays the last date of that
month. Syntax: last_day (d);
where d-date

Example: SQL> select last_day(to_date('12-jul-2015','dd-mm-yyyy')) from dual;


LAST_DAY(
--------31-JUL-15
3. Months_between
It gives the difference in number of months between d1
& d2. Syntax: month_between (d1,d2); where d1 & d2 dates
Example: SQL> SELECT MONTHS_BETWEEN
2 (TO_DATE('07-15-2015','MM-DD-YYYY'),
3 TO_DATE('01-01-2015','MM-DD-YYYY') ) "Months"
4 FROM DUAL;
Months
---------6.4516129
4. next_day
It returns a day followed the specified
date. Syntax: next_day (d,day);
Example: Select next_day (sysdate, wednesday ) from dual
NEXT_DAY(
--------29-JUL-15
5. round
This function returns the date, which is rounded to the unit specified by the format
model. Syntax : round (d,[fmt]);
where d- date, [fmt] optional. By default date will be rounded to the nearest day
The following example rounds a date to the first day of the year:
Example: SQL> select round(to_date('01-jun-2009','dd-mm-yy'),'year')
from dual;
ROUND(TO_--------01-JAN-09

NUMERICAL FUNCTIONS
Command
Query
Abs(n)
Select abs(-15) from dual;
Ceil(n)
Select ceil(55.67) from dual;
Exp(n)
Select exp(4) from dual;
Floor(n)
Select floor(100.2) from dual;
Power(m,n)
Select power(4,2) from dual;
Mod(m,n)
Select mod(10,3) from dual;
Round(m,n)
Select round(100.256,2) from dual;
Trunc(m,n)
Select trunc(100.256,2) from dual;
Sqrt(m,n)
Select sqrt(16) from dual;
CHARACTER FUNCTIONS
Command

Query

Output
15
56
54.59
100
16
1
100.26
100.25
4
Output

initcap(char);
select initcap(hello) from dual;
Hello
select lower (HELLO ) from dual;
lower (char);
hello
upper (char);
select upper (hello ) from dual;
HELLO
select ltrim (cseit , cse ) from dual;
ltrim (char,[set]);
it
rtrim (char,[set]);
Select rtrim (cseit , it ) from dual;
cse
select replace(jack and jue ,j ,bl ) from dual; black and
replace (char,search
string, replace string);
blue
select substr (information , 3, 4) from dual;
substr (char,m,n);
form
Miscellaneous Functions
1. uid This function returns the integer value (id) corresponding to the user
currently logged in.
Example: select uid from dual;
2. user This function returns the logins user name.
Example: select user from dual;
GROUP FUNCTIONS
A group function returns a result based on group of rows.
Student_name
mark1
mark2
Total
Krithika
56
77
133
Manasa
78
89
167
1. avg - Example: select avg (total) from student;
2. max - Example: select max (percentage) from student;
3. min - Example: select min (markl) from student;

4. sum - Example: select sum(mark1) from student;


COUNT FUNCTION
In order to count the number of rows, count function is used.
1. count(*) It counts all, inclusive of duplicates and nulls.
Example: select count(*) from student;
2. count(col_name) It avoids null value.
Example: select count(total) from student;
3. count(distinct col_name) It avoids the repeated and null values.

Percentage
66.5
83.5

Example: select count(distinct student_name) from


student;
Table name: emp
Emp_id
A123
B124
C125

Emp_name
karthik
gugan
sathya

Emp_desig
Analyst
Analyst
Tech Lead

Emp_salary
22000
30000
20000

Emp_doj
1-jun-2010
20-jul-1996
12-sep-2010

Q1: Display the details whose salary ranges from 15000 to 30000.
Q2: Calculate the total and average salary amount of the emp table.
Q3: Count the different designation records
in the emp table.
Q4: Determine the max and min salary
Q5: Display the months between doj and till date

Q6: Find how many employees are there


Q7: What is the difference between maximum and minimum salaries of employees in
the organization?
Q8: display the employee name with first letter as capital
Ex.No: 4 b

Aim:To study the various data language commands (DCL, TCL) and implement
them on the database.
S no
1

Details
DCL Command: The DCL language is used for controlling the access to the table and

The privilege commands are namely, Grant and Revoke.


The various privileges that can be granted or revoked are,
Select Insert Delete Update
References ExecuteAll

hence securing the database. DCL is used to provide certain privileges to a particular user.
Privileges are rights to be allocated

GRANT COMMAND: It is used to create users and grant access to the database. It
requires database administrator (DBA) privilege, except that a user can change their
password. A user can grant access to their database objects to other users.
REVOKE COMMAND: Using this command , the DBA can revoke the granted
database privileges from the user.

TCL COMMAND

COMMIT: command is used to save the Records.


ROLL BACK: command is used to undo the Records.
SAVE POINT command is used to undo the Records in a particular transaction
SQL Commands DCL Commands GRANT COMMAND
GRANT [privilege name,[priv..]|ALL] ON object_name TO
{user_name|PUBLIC|role_name}[WITH GRANT OPTION]

REVOKE COMMAND
REVOKE [privilege name,[priv..]|ALL] ON object_name FROM
{user_name|PUBLIC|role_name}[CASCADE CONSTRAINTS]

<privilege_name> -- Specifies the system level priveleges to be granted to the users or


roles. This includes create / alter / delete any object of the system. Or it can also Specify
the actions such as alter / delete / insert / references / execute / select / update for tables.
<all> -- Indicates all the priveleges.
[ With Grant Option ] Allows the recipient user to give further grants on the objects.
TCL COMMANDS:
Syntax:

SAVEPOINT: SAVEPOINT <SAVE POINT NAME>;


ROLLBACK: ROLL BACK <SAVE POINT NAME>;
COMMIT:
Commit;
d)
Queries:
Tables
Used:

Consider the following tables namely DEPARTMENTS


Their schemas are as follows ,
Departments ( dept _no , dept_ name , dept_location );
Q1: Develop a query to grant all privileges of departments table
Ans:
SQL> grant all on department to test with grant option;
Grant succeeded.
Q2: Develop a query to grant some privileges of departments table
Ans:
SQL> grant select on department to test;
Grant succeeded.
Q3: Develop a query to revoke all privileges from departments table
Ans:
SQL> revoke all on department from test;
Revoke succeeded.
Q4: Write a query to implement the save point

Ans:
SQL> SAVEPOINT S1;
Savepoint created.
SQL> select * from student;
NAME
MARK1 MARK2 TOTAL PERCENTAGE
-------------------- ---------- ---------- ---------- ---------krithika
56
77
133
66.5
manasa
78
89
167
83.5
SQL> INSERT INTO STUDENT VALUES ('Akalya',72,72,144,72.0);
1 row created.
SQL> select * from student;
NAME
MARK1 MARK2 TOTAL PERCENTAGE
-------------------- ---------- ---------- ---------- ---------krithika
56
77
133
66.5
manasa
78
89
167
83.5
Akalya
72
72
144
72
Now write a query to implement rollback
SQL> roll back s1;
SQL> select * from student;
NAME
MARK1 MARK2 TOTAL PERCENTAGE
-------------------- ---------- ---------- ---------- ---------krithika
56
77
133
66.5
manasa
78
89
167
83.5

Write a query to implement the commit


Ans:
SQL> COMMIT;
Commit complete.









Ex.no: 5. a
Aim:To perform nested Queries and joining Queries using DML command.
Step
no.
1

Details of the step


Nested Queries: Nesting of queries one within another is known as a nested
queries.
Sub queries The query within another is known as a sub query. A statement
containing sub query is called parent statement. The rows returned by sub query
used by are the parent statement.
Types
1. Sub queries that return several values
Sub queries can also return more than one value. Such results should be
made use along with the operators in and any. IN->Equal to Any One in the
List.ANY->Compares Value to Each Value Returned by the Sub Query.
Example: select ename from employee where salary < any(select salary
from employee where deptno=10)
2. Multiple queries
Here more than one sub query is used. These multiple sub queries are
combined by means of and & or keywords
3. Correlated sub query
A sub query is evaluated once for the entire parent statement whereas a
correlated Sub query is evaluated once per row processed by the parent
statement. Example: select * from emp x where x.salary > (select avg(salary)
from emp where deptno =x.deptno);
Relating Data through Join Concept
The purpose of a join concept is to combine data spread across tables. A join is
actually performed by tr he where clause which combines specified rows of
tables.
Syntax: select columns from table1, table2 where logical expression;
Types of Joins 1. Simple Join 2. Self Join 3. Outer Join 4. Inner Join
1. Simple Join
a) Equi-join: A join, which is based on equalities, is called equi-join.
b) Non Equi-join: It specifies the relationship between columns belonging to
different tables by making use of relational operators other than =
Table Aliases
Table aliases are used to make multiple table queries shorted and more
readable. We give an alias name to the table in the from clause and use it
instead of the name throughout the query.
Self join: Joining of a table to itself is known as self-join. It joins one row in a
table to another. It can compare each row of the table to itself and also with other
rows of the same table.
Outer Join: It extends the result of a simple join. An outer join returns all the
rows returned by simple join as well as those rows from one table that do not
match any row from the table. The symbol (+) represents outer join.

Inner join: Inner join returns the matching rows from the tables that are
being joined

c) SQL Commands:
Simple Join
a) Equi-join
Example: select * from item, cust where
item.id=cust.id;
b) Non Equi-join
Example: select * from item, cust where item.id<cust.id;
Self join
Example: select * from emp x ,emp y where x.salary >= (select avg(salary) from x.emp
where x. deptno =y.deptno);
Outer Join
Example: select ename, job, dname from emp, dept where emp.deptno (+) = dept.deptno;
d) Queries:
SQL> select * from emp;
EMPNO ENAME
JOB
DEPTNO
---------- -------------------- ---------- ---------- ---------1 Mathi
AP
1 10000
2 Arjun
ASP
2 12000
3 Gugan
ASP
2 20000
4 Karthik
AP
1 15000

SAL

SQL> select * from dept;


DEPTNO DNAME
LOC
---------- -------------- ------------1 ACCOUNTING
NEW YORK
2 RESEARCH
DALLAS
30 SALES
CHICAGO
40 OPERATIONS
BOSTON
Q1: Display all employee names and salary whose salary is greater than minimum
salary of the company and job title starts with A.
Solution:
1. Use select from clause.
2. Use like operator to match job and in select clause to get the result.
Ans:
SQL> select ename,sal from emp where sal>(select min(sal) from emp where job like
'A%');
ENAME
SAL
-------------------- ---------Arjun
12000
Gugan
20000
Karthik
15000
Q2: Issue a query to find all the employees who work in the same job as Arjun.
Ans:

SQL> select ename from emp where job=(select job from emp where
ename='Arjun');
ENAME
-------------Arjun
Gugan
Q3: Issue a query to display information about employees who earn more than
any employee in dept 1.
Ans:
SQL> select * from emp where sal>(select max(sal) from emp where empno=1);
EMPNO ENAME
JOB
DEPTNO
---------- -------------------- ---------- ---------- ---------2 Arjun
ASP
2 12000
3 Gugan
ASP
2
20000
4 Karthik
AP
1 15000

SAL

JOINS
EQUI-JOIN
Q4: Display the employee details, departments that the departments are same in both
the emp and dept.
Solution:
1. Use select from clause. 2. Use equi join in select clause to get the result.
Ans:
SQL> select * from emp,dept where emp.deptno=dept.deptno;
EMPNO ENAME
JOB
DEPTNO
SAL DEPTNO DNAME
LOC
---------- ------------------ ---------- ---------- ---------- ---------- -------------- ------------1 Mathi
AP
1
10000
1 ACCOUNTING
NEW YORK
2 Arjun
ASP
2
12000
2 RESEARCH
DALLAS
20000
3 Gugan
ASP
2
2 RESEARCH
DALLAS
4 Karthik
AP
1
15000
1 ACCOUNTING NEW YORK
NON-EQUIJOIN
Q5: Display the employee details, departments that the departments are not same in
both the emp and dept.
Solution:
1.Use select from clause. 2. Use non equi join in select clause to get the result.
Ans:
SQL> select * from emp,dept where emp.deptno!=dept.deptno;
EMPNO ENAME JOB
DEPTNO
SAL DEPTNO DNAME
LOC
---------- -------------------- ---------- ---------- ---------- ------------------------ ------------2 Arjun
ASP
2
12000
1 ACCOUNTING NEW YORK
3 Gugan
ASP
2
20000
1 ACCOUNTING NEW YORK

1 Mathi

AP

10000

RESEARCH

DALLAS

EMPNO ENAME
JOB
DEPTNO
SAL DEPTNO DNAME
---------- -------------------- ---------- ---------- ---------- ---------- -------------- ------------4 Karthik
AP
1 15000
2 RESEARCH
DALLAS
1 Mathi
AP
1
10000
30 SALES
CHICAGO
2 Arjun
ASP
2
12000
30 SALES
CHICAGO
EMPNO ENAME
JOB
DEPTNO
SAL DEPTNO DNAME
---------- -------------------- ---------- ---------- ---------- ---------- -------------- ------------3 Gugan
ASP
2
20000
30 SALES
CHICAGO
4 Karthik
AP
1 15000
30 SALES
CHICAGO
1 Mathi
AP
1 10000
40 OPERATIONS BOSTON
EMPNO ENAME
JOB
DEPTNO
SAL DEPTNO DNAME
---------- -------------------- ---------- ---------- ---------- ---------- -------------- ------------2 Arjun
ASP
2
12000
40 OPERATIONS BOSTON
3 Gugan
ASP
2
20000
40 OPERATIONS BOSTON
4 Karthik
AP
1 15000
40 OPERATIONS BOSTON
12 rows selected.
LEFTOUT-JOIN
SQL> select * from stud1;
REGNO NAME
MARK2 MARK3 RESU
---------- ---------- ---------- ---------- ---102 raja
70
80 pass
103 sharin
70
90 pass
104 sam
90
95 pass
101 john
89
80 pass
105 raj
89
80 pass
106 smith
30
28 fail
SQL> select * from stud2;
NAME
G
---------- john
s
raja
s
sam
a
sharin a
prem
a
Q6: Display the Student name and grade by implementing a left outer join.
SQL> select stud1.name,grade from stud1 left outer join stud2 on stud1.name=stud
2.name;
NAME
G
---------- john
s
raja
s
sam
a
sharin a

LOC

LOC

LOC

raj
smith
6 rows selected.
RIGHTOUTER-JOIN
Q7: Display the Student name, register no, and result by implementing a right outer
join.
SQL> select stud1.name, regno, result from stud1 right outer join stud2 on stud1
.name = stud2.name;
NAME
REGNO RESU
---------- ---------- ---raja
102 pass
sharin
103 pass
sam
104 pass
john
101 pass
FULLOUTER-JOIN
Q8: Display the Student name register no by implementing a full outer
join.
SQL> select stud1.name, regno,Grade from stud1 full outer join stud2 on
(stud1.n
ame= stud2.name);
NAME
REGNO G
---------- ---------- ---------raja
102
s
sharin
103
a
sam
104
a
john
101
s
raj
105
smith
106
a
7 rows selected.
SELFJOIN
Q9: Write a query to display their employee
names Ans:
SQL> select distinct ename from emp x, dept y where
x.deptno=y.deptno;
ENAME
-------------------Arjun
Gugan
Karthik
Mathi
Q10: Display the details of those who draw the salary greater than the average
salary. Ans:
SQL> select distinct * from emp x where x.sal >= (select avg(sal) from emp);
EMPNO ENAME
JOB
DEPTNO SAL
---------- -------------------- ---------- ---------- ---------3 Gugan
ASP
2 20000

4 Karthik
11 kavitha

AP
designer

1
12

15000
17000

Result:
Thus the nested Queries and join Queries was performed successfully and executed.

Ex.no 5.b
AIM: To perform set operations using DML Commands.
b) Procedure for doing the experiment:
Step
no.

Details of the step

Set Operators:
1

c)

The Set operator combines the result of 2 queries into a single result. The following
are the operators:
Union
Union all
Intersect
Minus
The rules to which the set operators are strictly adhere to :
The queries which are related by the set operators should have a same number of
column and column definition.
Such query should not contain a type of long.
Labels under which the result is displayed are those from the first select statement.

SQL commands:

Union: Returns all distinct rows selected by both the queries


Syntax:
Query1 Union Query2;
Union all: Returns all rows selected by either query including the duplicates.
Syntax:
Query1 Union all Query2;
Intersect: Returns rows selected that are common to both queries.
Syntax:
Query1 Intersect Query2;
Minus: Returns all distinct rows selected by the first query and are not by the second
Syntax:
Query1 minus Query2;
GROUP BY CLAUSE
This allows us to use simultaneous column name and group functions.
Example: Select max(percentage), deptname from student group by
deptname;
HAVING CLAUSE
This is used to specify conditions on rows retrieved by using group by clause.
Example: Select max(percentage), deptname from student group by deptname
having count(*)>=50;
d) Queries:
Q1: Display all the dept numbers available with the dept and emp tables

avoiding duplicates.
Solution:
1. Use select from clause. 2. Use union select clause to get the result.
Ans:
SQL> select deptno from emp union select deptno from dept;
DEPTNO
---------1
2
12
30
40
Q2: Display all the dept numbers available with the dept and emp tables.
Solution:
1. Use select from clause. 2. Use union all in select clause to get the
result. Ans:
SQL> select deptno from emp union all select deptno from dept;
DEPTNO
---------1
2
2
1
12
1
2
30
40
9 rows selected.
Q3: Display all the dept numbers available in emp and not in dept tables and vice versa.
Solution:
1. Use select from clause.
2. Use minus in select clause to get the
result. Ans:
SQL> select deptno from emp minus select deptno from dept;
DEPTNO
---------12
SQL> select deptno from dept minus select deptno from
emp; DEPTNO
---------30
40
Result:
Thus the set operations using DML Commands was successfully performed and executed.


Exp . No: 6
Aim: To study PL/SQL blocks and to implement various control structures
PL/SQL stands for Procedural Language extension of SQL.PL/SQL is a combination of SQL along with
the procedural features of programming languages.It was developed by Oracle Corporation in the
early 90s to enhance the capabilities of SQL.
A Simple PL/SQL Block:
Each PL/SQL program consists of SQL and PL/SQL statements which form a PL/SQL block.
PL/SQL Block consists of three sections:

The Declaration section (optional).


The Execution section (mandatory).
The Exception Handling (or Error) section (optional).

Declaration Section:

The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is
optional and is used to declare any placeholders like variables, constants, records and cursors, which
are used to manipulate data in the execution section. Placeholders may be any of Variables,
Constants and Records, which stores data temporarily. Cursors are also declared in this section.
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END.
This is a mandatory section and is the section where the program logic is written to perform any
task. The programmatic constructs like loops, conditional statement and SQL statements form the
part of execution section.
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is
optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks
terminates gracefully. If the PL/SQLBlock contains exceptions that cannot be handled, the Block
terminates abruptly with errors.

Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be
nested within other PL/SQL blocks. Comments can be used to document code.
How a Sample PL/SQL Block Looks
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;


PL/SQL Placeholders

Placeholders are temporary storage area. PL/SQL Placeholders can be any of Variables, Constants and
Records. Oracle defines placeholders to store data temporarily, which are used to manipulate data during
the execution of a PL SQL block.
Define PL/SQL Placeholders

Depending on the kind of data you want to store, you can define placeholders with a name and a datatype.
Few of the datatypes used to define placeholders are as given below. Number (n,m) , Char (n) , Varchar2
(n) , Date , Long , Long raw, Raw, Blob, Clob, Nclob, Bfile
PL/SQL Variables
These are placeholders that store the values that can change through the PL/SQL Block.
General Syntax to declare a variable is
variable_namedatatype [NOT NULL := value ];
variable_name is the name of the variable.
datatype is a valid PL/SQL datatype.
NOT NULL is an optional specification on the variable.
value or DEFAULT valueis also an optional specification, where you can initialize a variable.
Each variable declaration is a separate statement and must be terminated by a semicolon.
For example, if you want to store the current salary of an employee, you can use a variable.
DECLARE
salary number (6);
* salary is a variable of datatype number and of length 6.
When a variable is specified as NOT NULL, you must initialize the variable when it is declared.
For example: The below example declares two variables, one of which is a not null.
DECLARE
salary number(4);
dept varchar2(10) NOT NULL := HR Dept;

The value of a variable can change in the execution or exception section of the PL/SQL Block. We can
assign values to variables in the two ways given below.
1) We can directly assign values to variables.
The General Syntax is:
variable_namedatatype:=

value;

lets execute some pl/sql programs


Set serveroutput on types this command in case you dont see the output of the program

3 ways to executing pl/sql


1. Type manually line by line in sql plus
2. Type in a notepad and copy paste in sql plus
3. Create a .sql file in mydocuments, type the plsql program in it and save the file.
Lets say your sample file is test.sql
In sql plus, in the sql prompt type SQL>@ C:\Users\ramya\Documents\test and press enter

Q1: Now lets find the sum of two numbers


declare
a number(2)=10;
b number(2)=20;
c number(2);

begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line(a|| ' + '||b||' = '||c);
end;
/
Output:30
PL/SQL procedure successfully completed.

Q2: now let us try to get the numbers from the user
declare
a number(2);
b number(2);
c number(2);
begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line(a|| ' + '||b||' = '||c);
end;
/

2) We can assign values to variables directly from the database columns by using a SELECT..INTO
statement. The General Syntax is:
SELECT column_name
INTO variable_name
FROM table_name
[WHERE condition];

Q3: The below program will get the salary of an employee with no 1 and display it on
the screen.
DECLARE
var_salary number(6);
var_emp_id number(6) = 1;
BEGIN
SELECT sal
INTO var_salary
FROM emp
WHERE empno = var_emp_id;
dbms_output.put_line(var_salary);
dbms_output.put_line('The employee '
|| var_emp_id || ' has salary
END;
/

' || var_salary);

OUTPUT:10000
The employee 1has

salary

10000

PL/SQL procedure successfully completed.

NOTE: The backward slash '/' in the above program indicates to execute the above PL/SQL Block.
PL/SQL Constants
As the name implies a constant is a value used in a PL/SQL Block that remains unchanged throughout the
program. A constant is a user-defined literal value. You can declare a constant and use it instead of actual
value.
For example: If you want to write a program which will increase the salary of the employees by 25%, you
can declare a constant and use it throughout the program. Next time when you want to increase the salary
again you can change the value of the constant which will be easier than changing the actual value
throughout the program.
General Syntax to declare a constant is:
constant_name CONSTANT datatype := VALUE;

constant_name is the name of the constant i.e. similar to a variable name.


The word CONSTANT is a reserved word and ensures that the value does not change.
VALUE - It is a value which must be assigned to a constant when it is declared. You cannot assign a value
later.
For example, to declare salary_increase, you can write code as follows:
DECLARE
salary_increase CONSTANT number (3) := 10;

You must assign a value to a constant at the time you declare it. Or else you will get an error.

PL/SQL Records

What are records?

Records are another type of datatypes which oracle allows to be defined as a placeholder. Records are
composite datatypes, which means it is a combination of different scalar datatypes like char, varchar,
number etc. Each scalar data types in the record holds a value. A record can be visualized as a row of data.
It can contain all the contents of a row.
Declaring a record:
To declare a record, you must first define a composite datatype; then declare a record for that type.
The General Syntax to define a composite datatype is:

TYPE record_type_name IS RECORD


(first_col_namecolumn_datatype,
second_col_namecolumn_datatype, ...);

record_type_name it is the name of the composite type you want to define.

first_col_name, second_col_name, etc.,- it is the names the fields/columns within the record.

column_datatype defines the scalar datatype of the fields.


There are different ways you can declare the datatype of the fields.
1) You can declare the field in the same way as you declare the fieds while creating the table.
2) If a field is based on a column from database table, you can define the field_type as follows:
col_nametable_name.column_name%type;

By declaring the field datatype in the above method, the datatype of the column is dynamically
applied to the field. This method is useful when you are altering the column specification of the
table, because you do not need to change the code again.
NOTE: You can use also %type to declare variables and constants.

The General Syntax to declare a record of a user-defined datatype is:
record_namerecord_type_name;

The following code shows how to declare a record called employee_rec based on a user-defined
type.
DECLARE
TYPE employee_type IS RECORD
(employee_id number(5),
employee_first_name varchar2(25),
employee_last_nameemployee.last_name%type,
employee_deptemployee.dept%type);
employee_salaryemployee.salary%type;
employee_recemployee_type;

If all the fields of a record are based on the columns of a table, we can declare the record as follows:
record_nametable_name%ROWTYPE;

For example, the above declaration of employee_rec can as follows:


DECLARE
employee_recemployee%ROWTYPE;

The advantages of declaring the record as a ROWTYPE are:


1) You do not need to explicitly declare variables for all the columns in a table.
2) If you alter the column specification in the database table, you do not need to update the code.
The disadvantage of declaring the record as a ROWTYPE is:
1) When u create a record as a ROWTYPE, fields will be created for all the columns in the table and
memory will be used to create the datatype for all thefields. So use ROWTYPE only when you are
using all the columns of the table in the program.
NOTE: When you are creating a record, you are just creating a datatype, similar to creating a
variable. You need to assign values to the record to use them.

The following table consolidates the different ways in which you can define and declare a pl/sql
record.

Syntax

Usage

TYPE record_type_name IS RECORD

Define a composite datatype, where each field

(column_name1 datatype, column_name2

is scalar.

datatype, ...);
col_nametable_name.column_name%type;

Dynamically define the datatype of a column


based on a database column.

record_namerecord_type_name;
record_nametable_name%ROWTYPE;

Declare a record based on a user-defined type.


Dynamically declare a record based on an
entire row of a table. Each column in the table
corresponds to a field in the record.

Passing Values To and From a Record


When you assign values to a record, you actually assign values to the fields within it.
The General Syntax to assign a value to a column within a record direclty is:
record_name.col_name := value;

If you used %ROWTYPE to declare a record, you can assign values as shown:
record_name.column_name := value;

We can assign values to records using SELECT Statements as shown:


SELECT col1, col2
INTO record_name.col_name1, record_name.col_name2
FROM table_name
[WHERE clause];

If %ROWTYPE is used to declare a record then you can directly assign values to the whole record
instead of each columns separately. In this case, you must SELECT all the columns from the table into
the record as shown:

SELECT * INTO record_name


FROM table_name
[WHERE clause];
Lets see how we can get values from a record.
The General Syntax to retrieve a value from a specific field into another variable is:
var_name := record_name.col_name;

The following table consolidates the different ways you can assign values to and from a record:
Syntax

Usage

record_name.col_name := value;

To directly assign a value to a specific


column of a record.

record_name.column_name := value;

To directly assign a value to a specific


column of a record, if the record is
declared using %ROWTYPE.

SELECT col1, col2 INTO record_name.col_name1,

To assign values to each field of a record

record_name.col_name2 FROM table_name [WHERE

from the database table.

clause];
SELECT * INTO record_name FROM table_name [WHERE To assign a value to all fields in the record
clause];

from a database table.

variable_name := record_name.col_name;

To get a value from a record column and


assigning it to a variable.

Conditional Statements in PL/SQL


As the name implies, PL/SQL supports programming language features like conditional statements,
iterative statements.
The programming constructs are similar to how you use in programming languages like Java and C++.

IF THEN ELSE STATEMENT


1)
IF condition
THEN
statement 1;
ELSE
statement 2;
END IF;
2)
IF condition 1
THEN
statement 1;
statement 2;
ELSIF condtion2 THEN
statement 3;
ELSE
statement 4;
END IF
3)
IF condition1 THEN
ELSE
IF condition2 THEN
statement1;
END IF;
ELSIF condition3 THEN
statement2;
END IF;


Iterative Statements in PL/SQL
Iterative control Statements are used when we want to repeat the execution of one or more statements
for specified number of times.
There are three types of loops in PL/SQL:
Simple Loop
While Loop
For Loop
1) Simple Loop
A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates.

An EXIT condition must be specified in the loop, otherwise the loop will get into an infinite number of
iterations. When the EXIT condition is satisfied the process exits from the loop.
General Syntax to write a Simple Loop is

:
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
These are the important steps to be followed while using Simple Loop.
1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without WHEN
condition, the statements in the loop is executed only once.

Q4 : print the values 1 to 20 using simple loop


2) While Loop
A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true.
The condition is evaluated at the beginning of each iteration. The iteration continues until the
condition becomes false.
The General Syntax to write a WHILE LOOP is:
WHILE <condition>
LOOP statements;
END LOOP;
Important steps to follow when executing a while loop:
1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not done oftenly.

Q5: print the values 1 to 20 using while loop


3) FOR Loop
A FOR LOOP is used to execute a set of statements for a predetermined number of times. Iteration
occurs between the start and end integer values given. The counter is always incremented by 1. The
loop exits when the counter reaches the value of the end integer.
The General Syntax to write a FOR LOOP is:
FOR counter IN val1..val2
LOOP statements;
END LOOP;
val1 - Start integer value.
val2 - End integer value.
Important steps to follow when executing a while loop:

1) The counter variable is implicitly declared in the declaration section, so it's not necessary to
declare it explicity.

2) The counter variable is incremented by 1 and does not need to be incremented explicitly.
3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's not done oftenly.

Q6: Print the values 1 to 20 using for loop


Q7: write a pl/sql program to swap two numbers c)
Procedure for doing the experiment:
Step
no.
1
2
3

Details of the step


Declare three variables and read variables through a and b
Swap the values of a and b using temporary variables
Display the swapped results

d) Program:
SQL>
declare
a number(10);
b number(10);
begin

c number(10);

dbms_output.put_line('THE PREV VALUES OF A AND B


WERE');
dbms_output.put_line(a);
dbms_output.put_line(b);
a:=&a;
b:=&b;
c:=a;
a:=b;
b:=c;
dbms_output.put_line('THE VALUES OF A AND B
ARE'); dbms_output.put_line(a);
dbms_output.put_line(
b); end;

e)output:
SQL> @
swapping.sql 19 /
Enter value for
a: 5 old 6:
a:=&a;
new 6: a:=5;
Enter value for
b: 3 old 7:
b:=&b;
new 7: b:=3;
THE PREV VALUES OF A AND B
WERE 53
THE VALUES OF A AND B
ARE 35

PL/SQL procedure successfully completed.

Q8: Write a pl/sql program to find the largest of three


numbers c) Procedure for doing the experiment:
Step
no.
1
2
3

Details of the step


Read three numbers through a, b & c
Find the biggest among three using nested if statement
Display the biggest no as result

Q9: write a pl/sql program to find the total and average of 6 subjects and display the
grade c) Procedure for doing the experiment:
Step
Details of the step
no.
1
Read six numbers and calculate total and average
2
Find whether the student is pass or fail using if statement
3
Find the grade using nested elseif statement
4
Display the Grade, Percentage and Total of the student
d)Program:
Q10: Write a pl/sql program to find the sum of digits in a given
number c) Procedure for doing the experiment:
Step
no.
1
2
3
d)Program:

Details of the step


Read a number. Separate the digits using modular function
Sum the digits separated by mod function
Display the sum of digits

Q11: write a pl/sql program to display the number in reverse


order c)Procedure for doing the experiment:
Step
Details of the step
no.
1
Read a number. Separate the digits using modular function
2
Reverse the digits separated by taking remainder from mod function
3
Display the reverse of the digits
d)Program:
SQL>edit
reverse.sql
declare
a number;
rev number;
d number; begin

a:=&a;
rev:=0;
while a>0 loop

d:=mod(a,10);
rev:=(rev*10)+d;
a:=trunc(a/10);
end loop;

dbms_output.put_line('no is'|| rev);


end;
e)output:
SQL> @
reverse.sql 16 /
Enter value for a:
536 old 6:
a:=&a; new
6: a:=536;

no is 635
PL/SQL procedure successfully completed.
Q12: Write a PL / SQL program to check whether the given number is prime
or not c) Procedure for doing the experiment:
Step
Details of the step
no.
1
Read the number
2
Using mod function find the given number is prime or not
3
Display the result
d)Program:
Q13: Write a PL/SQL program to find the factorial of a given
number c) Procedure for doing the experiment:
Step
no.
1
2
3

Details of the step


Read a number for calculating factorial value.
Calculate the factorial of a given number using for loop
Display the factorial value of a given number.

d)Program:
SQL>edit
fact.sql
declare
n number;
f number:=1;
begin
n:=&n;
for i in 1..n loop
f:=f*i;
end loop;
dbms_output.put_line('the factorial is'|| f);
end;

e)output:
SQL> @
fact.sql 12 /
Enter value for
n: 5 old 5:
n:=&n;
new 5: a:=5;
the factorial is 120
Q14: Write a PL/SQL program to find the largest of 2 nos

Q15: Write a PL/SQL program to calculate the area and circumference of a


circle
Q16: write a pl/sql code block to calculate the area of a circle for a value of radius
varying from 3 to 7. Store the radius and the corresponding values of calculated area in
an empty table named areas, consisting of two columns radius & area
c) Procedure for doing the experiment:
Step
no.
1
2
3

Details of the step


Create a table named areas with radius and area
Initialize values to pi, radius and area
Calculate the area using while loop. Display the result.

d)Program:
SQL> create table areas(radius number(10),area number(6,2));
Table created.
PROGRAM
declare

pi constant number(4,2):=3.14;
radius number(5):=3;
area number(6,2);
begin
while radius<7
loop
area:=pi*power(radius,2);
insert into areas values(radius,area);
radius:=radius+1;
end loop;
end;

e)output:
SQL> @
AREAOFCIRCLE.SQL 13 /
PL/SQL procedure successfully
completed. SQL> SELECT * FROM
AREAS; RADIUS AREA
---------- ----------

3 28.26
4 50.24
5 78.5
6 113.04
Q17: write a PL/SQL code block that will accept an account number from the user,
check if the users balance is less than minimum balance, only then deduct rs.100/- from
the balance. This process is fired on the acct table.
c) Procedure for doing the experiment:
Step
no.
1
2

Details of the step


Develop a query to Create the table acct and insert values into them
Develop a PL/SQL program to read the account number.

Check the balance for the account no. check if the users balance is less than minimum
balance, only then deduct rs.100/- from the balance

Update the balance changes into the acct table.

d)Program:
SQL> create table acct(name varchar2(10),cur_bal number(10),acctno
number(6,2)); SQL> insert into stud values('&sname',&rollno,&marks);
SQL> select * from acct;
ACCTNO NAME CUR_BAL

---------- ---------- ---------777 sirius 10000


765 john 1000
855 sam 500
353 peter 800
declare
mano number(5);
mcb number(6,2);
minibal constant number(7,2):=1000.00;
fine number(6,2):=100.00;
beginmano:=&ma
no;

selectcur_bal into mcb from acct where acctno=mano;


ifmcb<minibal then
update acct set cur_bal=cur_bal-fine where acctno=mano;
end if;
end;
e)output:
SQL> @
BANKACC.sql 13 /
Enter value for mano:
855 old 7:
mano:=&mano; new
7: mano:=855;
PL/SQL procedure successfully completed.

Ex. No 7:
Aim : To create PL/SQL programs to handle all types of exceptions
What is Exception Handling?
PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as
exception Handling. Using Exception Handling we can test the code and avoid it from exiting
abruptly.When an exception occurs a messages which explains its cause is recieved.
PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) A message

By Handling the exceptions we can ensure a PL/SQL block does not exit abruptly.
2) Structure of Exception Handling: General Syntax for coding the exception section
DECLARE
Declaration section
BEGIN
Exception section
EXCEPTION
WHEN ex_name1 THEN
-Error handling statements
WHEN ex_name2 THEN
-Error handling statements
WHEN Others THEN
-Error handling statements
END;

General PL/SQL statments can be used in the Exception Block.


When an exception is raised, Oracle searches for an appropriate exception handler in the
exception section. For example in the above example, if the error raised is 'ex_name1 ', then
the error is handled according to the statements under it. Since, it is not possible to determine
all the possible runtime errors during testing fo the code, the 'WHEN Others' exception is
used to manage the exceptions that are not explicitly handled. Only one exception can be
raised in a Block and the control does not return to the Execution Section after the error is
handled.
If there are nested PL/SQL blocks like this.
DELCARE
Declaration section
BEGIN
DECLARE
Declaration section
BEGIN

Execution section
EXCEPTION
Exception section
END;
EXCEPTION
Exception section
END;
In the above case, if the exception is raised in the inner block it should be handled in the
exception block of the inner PL/SQL block else the control moves to the Exception block of
the next upper PL/SQL Block. If none of the blocks handle the exception the program ends
abruptly with an error.

3) TYPES OF EXCEPTION.
There are 3 types of Exceptions.
a) Named System Exceptions/predefined Exceptions
b) Unnamed System Exceptions
c) User-defined Exceptions

A) NAMED SYSTEM EXCEPTIONS


System exceptions are automatically raised by Oracle, when a program violates a RDBMS
rule. There are some system exceptions which are raised frequently, so they are pre-defined
and given a name in Oracle which are known as Named System Exceptions.
For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System
exceptions.
Named system exceptions are:
1) Not Declared explicitly,
2) Raised implicitly when a predefined Oracle error occurs,
3) caught by referencing the standard name within an exception-handling routine.
Exception Name
Reason
Error
Number
CURSOR_ALREADY_OPEN When you open a cursor that is already open.

ORA06511

INVALID_CURSOR

ORA01001

NO_DATA_FOUND
TOO_MANY_ROWS

When you perform an invalid operation on a


cursor like closing a cursor, fetch data from a
cursor that is not opened.
When a SELECT...INTO clause does not return
any row from a table.
When you SELECT or fetch more than one row
into a record or variable.

ORA01403
ORA01422

ZERO_DIVIDE

When you attempt to divide a number by zero.

ORA01476

For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a


code to handle the exception as given below.

Pgm 1:
declare
name emp.ename%type;
begin
select ename into name from emp where deptno=2;
Exception
when others then
dbms_output.put_line('error code'||SQLCODE||SQLERRM);
end;
output:
error code-1422ORA-01422: exact fetch returns more than requested number of rows
PL/SQL procedure successfully completed.

pgm2:
SQL> declare
2 name emp.ename%type;
3 begin
4 select ename into name from emp where deptno=2;
5 Exception
6 when TOO_MANY_ROWS then
7 dbms_output.put_line('select statement retrieves many rows. it is advisable
that you provide a correct where clause');
8 end;
9 /
Output:
select statement retrieves many rows. it is advisable that you provide a correct

where clause

PL/SQL procedure successfully completed.
B) UNNAMED SYSTEM EXCEPTIONS
Those system exception for which oracle does not provide a name is known as unamed system
exception. These exception do not occur frequently. These Exceptions have a code and an associated
message.
There are two ways to handle unnamed sysyem exceptions:
1. By using the WHEN OTHERS exception handler, or
2. By associating the exception code to a name and using it as a named exception.

We can assign a name to unnamed system exceptions using


a Pragma called EXCEPTION_INIT.
EXCEPTION_INIT will associate a predefined Oracle error number to a
programmer_defined exception name.
Steps to be followed to use unnamed system exceptions are
They are raised implicitly.
If they are not handled in WHEN Others they must be handled explicity.
To handle the exception explicity, they must be declared using Pragma EXCEPTION_INIT as given
above and handled referecing the user-defined exception name in the exception section.

The general syntax to declare unnamed system exception using EXCEPTION_INIT is:
DECLARE
exception_name EXCEPTION;
PRAGMA
EXCEPTION_INIT (exception_name, Err_code);
BEGIN
Execution section
EXCEPTION
WHEN exception_name THEN
handle the exception
END;

For Example: Lets consider the product table and order_items table from sql joins.
Here product_id is a primary key in product table and a foreign key in order_items table.
If we try to delete a product_id from the product table when it has child records in order_id table an
exception will be thrown with oracle code number -2292.
We can provide a name to this exception and handle it in the exception section as given below.
DECLARE
Child_rec_exception EXCEPTION;
PRAGMA
EXCEPTION_INIT (Child_rec_exception, -2292);
BEGIN
Delete FROM product where product_id= 104;
EXCEPTION
WHEN Child_rec_exception
THEN Dbms_output.put_line('Child records are present for this product_id.');
END;
C) USER-DEFINED EXCEPTIONS

Apart from sytem exceptions we can explicity define exceptions based on business rules. These are
known as user-defined exceptions.

Steps to be followed to use user-defined exceptions:


They should be explicitly declared in the declaration section.

Syntax: Exception_Name EXCEPTION;


They should be explicitly raised in the Execution Section.
Syntax: RAISE Exception_Name;
They should be handled by referencing the user-defined exception name in the exception
section.
Example on the below table perform the pl sql program where an exception is raised when
the updated salary of the employee is more than the maximum salary in the database
Pgm 3:
declare
salmax emp.salary%type;
sal emp.salary%type;
name emp.ename%type;
salary_exception EXCEPTION;
begin
select max(salary) into salmax from emp;
name:='&name';
select salary into sal from emp where ename=name;
sal:=sal+20000;
if sal>salmax then
raise salary_exception;
else
update emp set salary=sal where ename=name;
end if;
EXCEPTION
when salary_exception then
dbms_output.put_line('the salary for employee cannot be updated');
end;
/

RAISE_APPLICATION_ERROR ( )
RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display the user-

defined error messages along with the error number whose range is in between -20000 and -20999.
Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous transactions
which are not committed within the PL/SQL Block are rolled back automatically (i.e. change due to
INSERT, UPDATE, or DELETE statements).

RAISE_APPLICATION_ERROR raises an exception but does not handle it.


RAISE_APPLICATION_ERROR is used for the following reasons,
a) to create a unique id for an user-defined exception.
b) to make the user-defined exception look like an Oracle error.
The General Syntax to use this procedure is:

RAISE_APPLICATION_ERROR (error_number, error_message);


The Error number must be between -20000 and -20999
The Error_message is the message you want to display when the error occurs.
Steps to be folowed to use RAISE_APPLICATION_ERROR procedure:
1. Declare a user-defined exception in the declaration section.
2. Raise the user-defined exception based on a specific business rule in the execution section.
3. Finally, catch the exception and link the exception to a user-defined error number in
RAISE_APPLICATION_ERROR.
Using the above example we can display a error message using
RAISE_APPLICATION_ERROR.
Pgm 4:
The above program can now be converted to look like a system defined exception
declare
salmax emp.salary%type;
sal emp.salary%type;
name emp.ename%type;
salary_exception EXCEPTION;
begin
select max(salary) into salmax from emp;
name:='&name';
select salary into sal from emp where ename=name;
sal:=sal+20000;
if sal>salmax then
raise salary_exception;
else
update emp set salary=sal where ename=name;
end if;
EXCEPTION
when salary_exception then
raise_application_error(-20120,'the salary for employee cannot be updated');
dbms_output.put_line('error'||SQLCODE||SQLERRM);
end;
/

Output:
ORA-20100: the salary for employee cannot be updated
ORA-06512: at line 18

Result:
Thus the PL/SQL program to handle all types of exceptions was successfully
executed.

Exp no: 8
Aim: To create procedures and functions and manipulate the data from the table
PL/SQL syntax:
A procedure is a block that can take parameters (sometimes referred to as
arguments) and be invoked.
Procedures promote reusability and maintainability. Once validated, they can be
used in number of applications. If the definition changes, only the procedure are affected,
this greatly simplifies maintenance.
Modularized program development:
Group logically related statements within blocks.
Nest sub-blocks inside larger blocks to build powerful programs.
Break down a complex problem into a set of manageable well defined logical
modules and implement the modules with blocks.
KEYWORDS AND THEIR PURPOSES
REPLACE: It recreates the procedure if it already exists.
PROCEDURE: It is the name of the procedure to be created.

ARGUMENT: It is the name of the argument to the procedure. Parenthesis can be


omitted if no arguments are present.
1) IN type parameter: These types of parameters are used to send values to stored
procedures.
2) OUT type parameter: These types of parameters are used to get values from stored
procedures.
This
is
similar
to
a
return
type
in
functions.
3) IN OUT parameter: These types of parameters are used to send values and get
values from stored procedures.
RETURN: It is the data type of the function s return value because every function must
return a value, this clause is required.
PROCEDURES
Syntax :
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS

[local declaration_section]

BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];

FUNCTIONS
Syntax:
CREATE [OR REPLACE] FUNCTION function_name [ (parameter [,parameter]) ]
RETURN return_type
AS
[local declaration_list]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Pgm1: to calculate area given length and width
create or replace procedure calArea(len in number,wid in number, area out number)
as
begin
area:=len*wid;
end;
/
Procedure created
SQL>variable area1 number;
SQL>execute(10,5,:area1);
PL/SQL procedure successfully completed.
SQL>print area1;
AREA1
---------50
Pgm2: to remove a particular student from student table
create or replace procedure removestu(stuname varchar)
as
totstu number;
begin
delete from student where name=stuname;
totstu:=totstu-1;
end;
/
Procedure created
SQL>execute removestu('aaa');
PL/SQL procedure successfully completed.

PROGRAM FOR FUNCTION AND ITS EXECUTION


Pgm 3: to create a function to get the total of a particular student
SQL> create or replace function asktotal(stuname varchar)
2 return number
3 is
4 tot number;
5 begin
6 select total into tot from student where name=stuname;
7 return tot;
8 end;
9 /
Function created.
SQL> select asktotal('KKK') from dual;
ASKTOTAL('KKK')
--------------23
FACTORIAL OF A NUMBER USING FUNCTION PROGRAM AND
EXECUTION
SQL> create function itfact (a number) return number is
2 fact number:=1;
3 b number;
4 begin
5 b:=a;
6 while b>0
7 loop
8 fact:=fact*b;
9 b:=b-1;
10 end loop;
11 return(fact);
12 end;
13 /
Function created.
SQL> declare
2 a number:=7;
3 f number(10);
4 begin
5 f:=itfact(a);
6 dbms_output.put_line(The factorial of the given number is ||f);
7 end;
8 /
The factorial of the given number is 5040

Q1: Write a procedure to calculate total for the all the students and pass regno,
mark1, & mark2 as arguments.
c)Procedure for doing the experiment:
Step
no.
1
2
3

Details of the step


Develop a query to create a table named itstudent2 and insert values into them
Develop a procedure p1 with regno, mark1, & mark2 as arguments.
Calculate the total and update the total value into the itstudent2 table

d)Program:
SQL> create table itstudent2(regno number(3),name varchar(9),mark1
number(3),mark2 number(3));
Table created.
SQL> insert into itstudent2
2 values(&a,'&b',&c,&d);
Enter value for a: 110
Enter value for b: arun
Enter value for c: 99
Enter value for d: 100
old 2: values(&a,'&b',&c,&d)
new 2: values(110,'arun',99,100)
1 row created.
SQL> /
Enter value for a: 112
Enter value for b: siva
Enter value for c: 99 Enter value
for d: 90
old 2: values(&a,'&b',&c,&d)
new 2: values(112,'siva',99,90)
1 row created.
SQL> select * from itstudent2;
REGNO NAME
MARK1 MARK2
110 arun
99
100
112 siva
99
90
SQL> alter table itstudent2 add(total number(5));
Table altered.
SQL> select * from itstudent2;
REGNO NAME
MARK1 MARK2TOTAL
110 arun
99
100
112 siva
99
90
SQL> create or replace procedure p1(sno number,mark1 number,mark2 number) is
2 tot number(5);
3 begin
4 tot:=mark1+mark2;
5 update itstudent2 set total=tot where regno=sno;
6 end;
7 /
Procedure created.

SQL> declare
2 cursor c1 is select * from itstudent2;
3 rec itstudent2 % rowtype;
4 begin
5 open c1;
6 loop
7 fetch c1 into rec;
8 exit when c1%notfound;
9 p1(rec.regno,rec.mark1,rec.mark2);
10 end loop;

11 close c1;
12 end;
13 /
PL/SQL procedure successfully completed.
e)Output:
SQL> select * from itstudent2;
REGNO NAME
MARK1
MARK2TOTAL
--------- --------- ---------- ---------- ---------110 arun
99
100
199
112 va
99
90
189
Q2: Write a PL/SQL procedure called MULTI_TABLE that takes two numbers as parameter
and displays the multiplication of the first parameter till the second parameter.
Ans.
//p2.sql
create or replace procedure multi_table (a number, b
number) as mul number;
begin
for i in 1. .b
loop
mul : = a * i;
dbms_output.put_line (a || * || i || = || mul);
end loop;
end;
//pq2.sql
declare
a number; b number;
begin
a:=&a;
b:=&b;
multi_table(a,b);
end;

e)Output:
SQL> @p2.sql;
Procedure created.
SQL> @pq2.sql;
Enter value for a: 4
old 5: a:=&a;
Enter value for b: 3

new 5: a:=4;

old 6: b:=&b;
new 6: b:=3;
4*1=4
4*2=8
4*3=12
Q3: Consider the EMPLOYEE (EMPNO, SALARY, ENAME) Table.
Write a procedure raise_sal which increases the salary of an employee. It accepts an employee
number and salary increase amount. It uses the employee number to find the current salary
from the EMPLOYEE table and update the salary.
Ans:
//p3.sql

create or replace procedure raise_sal( mempno employee . empno % type,


msal_percent number ) as
begin
update employee set salary = salary + salary*msal_percent /100 where empno =
mempno; end;
/
//pq3.sql

declare
cursor c1 is select * from emp;
rec emp % rowtype;
begin
open c1;
loop
fetch c1 into rec;
exit when
c1%notfound;
raisal(rec.empno,10);
end loop;
close c1;
end;
/
e)Output:
SQL> @p3.sql;
Procedure created.
SQL> select * from emp;
EMPNO ENAME JOB
DEPTNO
SAL
---------- -------------------- ------------- ---------- ---------1 Mathi
AP
1 10000
2 Arjun
ASP
2 15000
3 Gugan
ASP
1 15000
4 Karthik
Prof
2 30000
5 Akalya
AP
1 10000
SQL> @pq3.sql;
PL/SQL procedure successfully completed.
SQL> select * from emp;
EMPNO ENAME JOB
DEPTNO
SAL
---------- -------------------- ------------- ---------- ---------1 Mathi
AP
1 11000
2 Arjun
ASP
2 16500
3 Gugan
ASP
1 16500
4 Karthik
Prof
2 33000
5 Akalya
AP
1 11000

Q4: Write a PL/SQL function CheckDiv that takes two numbers as arguments and returns the
values 1 if the first argument passed to it is divisible by the second argument, else will return the
value 0;
Ans:
//p4.sql

create or replace function checkdiv (n1 number, n2 number) return number as


res number;
begin
if mod (n1, n2) = 0
then res := 1;
else
res:= 0;
end if;
return res;
end;
/
//pq4.sql
declare
a number;
b number;
begin
a:=&a; b:=&b;
dbms_output.put_line(result= ||checkdiv(a,b));
end;
/

e)Output:
SQL> @p4.sql;
Function created.
SQL> @pq4.sql;
Enter value for a: 4
old 5: a:=&a;
Enter value for b: 2
old 6: b:=&b;
result=1

new 5: a:=4;
new 6: b:=2;

Q5: Write a PL/SQL function called POW that takes two numbers as argument and return
the value of the first number raised to the power of the second .
Ans:
//p5.sql

create or replace function pow (n1 number, n2 number) return


number as res number;
begin
select power ( n1, n2) into res from dual; return res; end;
or
create or replace function pow (n1 number, n2 number) return
number as res number : =1;
begin
for res in 1..n2
loop
res : = n1 * res;
end loop;

return res;
end;
//pq5.sql
declare
a number;
b number;
begin
a:=&a; b:=&b;
dbms_output.put_line('power(n1,n2)='||pow(a,b));
end;

e)Output:
SQL> @p5.sql;
Function
created.
SQL> @ pq5.sql;
Enter value for
a: 2 old 5:
a:=&a; new 5:
a:=2; Enter
value for b: 3
old 6: b:=&b;
new 6: b:=3;
power(n1,n2)=
8
Q6: Write a PL/SQL function ODDEVEN to return value TRUE if the number passed to
it is EVEN else will return FALSE.
Ans:
//p6.sql

create or replace function oddeven (n number) return boolean as


begin
if mod (n, 2) = 0 then
return true;
else
return false;
end if;
end;
/
//pq6.sql
declare
a number;
b boolean;
begin
a:=&a;
b:=oddeven(a);
if b then
dbms_output.put_line('The given number is Even');
else
dbms_output.put_line('The given number is Odd');
end if;
end;
/
e)Output:

SQL> @p6.sql;
Function created.
SQL> @pq6.sql;
Enter value for a: 5
old 5: a:=&a;
The given number is Odd

new 5: a:=5;

Q8. Write a function to retrieve the address and salary of a particular employee.

Result:
Thus the procedures and function for various operations was developed and
executed successfully.

Exp.No: 9
Aim: To create triggers for various events such as insertion, updation etc
PL/SQL Syntax: TRIGGER
A Trigger is a stored procedure that defines an action that the database automatically
take when some database-related event such as Insert, Update or Delete occur.
TRIGGER VS. PROCEDURE VS CURSOR
TRIGGER
These are named
PL/SQL blocks.
These are invoked
automatically.
These cant take
parameters.
These are stored in
database.

PROCEDURES
These are named
PL/SQL blocks.
User as per need invokes
these.
These can take
parameters.
These are stored in
database.

CURSORS
These are named PL/SQL
blocks.
These can be created both
explicitly and implicitly.
These can take parameters.
These are not stored in
database.

TYPES OF TRIGGERS
The various types of triggers are as follows,
Before: It fires the trigger before executing the trigger
statement. After: It fires the trigger after executing the trigger
statement.
For each row: It specifies that the trigger fires once per row.

For each statement: This is the default trigger that is invoked. It specifies that the
trigger fires once per statement.
VARIABLES USED IN TRIGGERS
:new
:old
These two variables retain the new and old values of the column updated in the
database. The values in these variables can be used in the database triggers for data
manipulation
Row Level Trigger vs. Statement Level Trigger:
Row Level Trigger
Statement Level Trigger
These are fired for each row affected by These are fired once for the statement
the DML statement.
instead of the no of rows modified by it.
These are used for generating/checking These are used for generated the
the values begin inserted or updated.
summary information.

Before trigger vs. after trigger


Before Triggers
Before triggers are fired before the

After Triggers
After triggers are fired after the

DML statement is actually executed.

DML statement has finished


execution.

Syntax:
Create or replace trigger <trg_name>
[Before /After]
[Insert/Update/Delete]
[of column_name, column_name.] on <table_name>
[for each row] [when condition]
begin
--statement
end;
Q1: Create a trigger that insert current user into a username column of an existing
table c) Procedure for doing the experiment:
Step
no.
1

Details of the step

Create a table itstudent4 with name and username as arguments

Create a trigger for each row that insert the current user as user name into a table

Execute the trigger by inserting value into the table

d)Program:

SQL> create table itstudent4(name varchar2(15),username


varchar2(15)); Table created.
SQL> create or replace trigger itstudent4 before insert on itstudent4 for each row
2 declare
3 name varchar2(20);
4 begin
5 select user into name from dual;
6 :new.username:=name;
7 end;
8 /
Trigger created.
e)Output:

SQL> insert into itstudent4


values('&name','&username'); Enter value for name:
akbar
Enter value for username: ranjani
old 1: insert into itstudent4 values('&name','&username')
new 1: insert into itstudent4 values('akbar','ranjani')
1 row
created.
SQL> /

Enter value for name: suji


Enter value for username:
priya
old 1: insert into itstudent4 values('&name','&username')
new 1: insert into itstudent4 values('suji','priya')
1 row created.
SQL> select * from itstudent4;
NAME
USERNAME
--------------- --------------akbar
SCOTT
suji
SCOTT

Q2: Create a Simple Trigger that does not allow Insert Update and Delete Operations
on the Table
d)Program: Table
used:

SQL> select * from emp;


ENAME SALARY DEPTNO
---------- --------- --------Abc
10000 2
Cde
10500 2
Xyz
15500 3
Trigger:
SQL> create trigger trig1 before insert or update or delete on emp for each row
begin
raise_application_error(-20010,'you cannot do manipulation');
end;
/
Trigger created.
Perform the below queries and note down the error messages
SQL> insert into emp values('abc',10000,3);
insert into emp values('abc',10000,3)
*
ERROR at line 1:
ORA-20010: you cannot do manipulation
ORA-06512: at "TESTUSER.TRIG1", line 2
ORA-04088: error during execution of trigger 'TESTUSER.TRIG1'
SQL> delete from emp where ename=xyz;
delete from itempls where ename=xyz
*

ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG",
line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'
SQL> update itempls set deptno=15 where ename=cde;
update itempls set deptno=15 where ename=cde
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG",
line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'
`Q3: Create a Trigger that raises an User Defined Error Message and does not allow
updating and Insertion on the Employee table with fields ename, eid and salary
d)Program: Table
used:

SQL> select * from itempls;


ENAME EID SALARY
---------- --------- --------xxx 11 10000
yyy 12 10500
zzz
13 15500
Trigger:
SQL> create trigger ittriggs before insert or update of salary on itempls for each row
2 declare
3 triggsal itempls.salary%type;
4 begin
5 select salary into triggsal from itempls where eid=12;
6 if(:new.salary>triggsal or :new.salary<triggsal) then
7 raise_application_error(-20100,'Salary has not been changed');
8 end if;
9 end;
10 /
Trigger created.
e)Output:
SQL> insert into itempls values
('bbb',16,45000); insert into itempls values
('bbb',16,45000)
*
ERROR at line 1:
ORA-04098: trigger 'STUDENT.ITTRIGGS' is invalid and failed revalidation SQL> update itempls set eid=18 where ename='zzz';
update itempls set eid=18 where ename='zzz'
*
ERROR at line 1:

ORA-04298: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation


Q4: develop a query to Drop the Created Trigger
Ans:
SQL> drop trigger ittrigg;
Trigger dropped.
Exercises
1. emp_details (emp_no, emp_name, DOB, address, doj, mobile_no, dept_no, salary).
Creating Trigger On Table Employ For Not Allowing Insert/Update/Delete Operations
On Friday.
2. Product(product_id, product_name, supplier_name, unit_price)
Product_price_history(product_id, product_name, supplier_name, unit_price)
Create a trigger price_history_trigger such that whenever unit_price is to be updated
in the product table, the previous values must be entered into the
product_price_history table)
CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES
(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END;
/

3. Phone_book(ph_no,name,door_no,street,place).
Create a Trigger To Insert Values To Another Table

Result:
Thus the creation of triggers for various events such as insertion, updation, etc., was
performed and executed successfully.

Exp. No 10
Aim: To create Views, Synonyms, sequences and indexes on database tables
VIEW

A view is a virtual table that contains no data of its own. A view provides a window to the
database user through which data from tables can be examined or changed.
Using a view common queries can be executed.
SQL Commands
Creating and dropping view:
Syntax:
Create [or replace] view <view name> [column alias names] as <query> [with
<options> conditions];
Drop view <view name>;
Example:
Create or replace view empview as select * from emp;
Drop view empview;
d) Queries: Tables used:

SQL> select * from emp;


EMPNO ENAME
JOB
DEPTNO
SAL
---------- -------------------- ---------- ---------- ---------1 Mathi
AP
1
10000
2 Arjun
ASP
2
12000
3 Gugan
ASP
2
20000
4 Karthik
AP
1
15000
Q1: The organization wants to display only the details of the employees those who are
ASP. (Horizontal portioning)
Solution:
1. Create a view on emp table named managers
2. Use select from clause to do horizontal partioning
Ans:
SQL> create view empview as select * from emp where job='ASP';
View created.
SQL> select * from empview;
EMPNO ENAME JOB
DEPTNO SAL
---------- -------------------- ---------- ---------- ---------2 Arjun
ASP
2 12000
3 Gugan
ASP
2 20000
Q2: The organization wants to display only the details like empno, empname,
deptno, deptname of the employees. (Vertical portioning)
Solution:
1. Create a view on emp table named general 2. Use select from clause to do vertical
partioning

Ans:
SQL> create view empview1 as select ename,sal from emp;
View created.
Q3: Display all the views generated.
Ans:
SQL> select * from tab;
TNAME
TABTYPE CLUSTERID
------------------------------ ------- ---------DEPT
TABLE
EMP
TABLE
EMPVIEW
VIEW
EMPVIEW1
VIEW
Q4: Execute the DML commands on the view created.
Ans:
SQL> select * from empview;
EMPNO ENAME
JOB
DEPTNO
SAL
---------- -------------------- ---------- ---------- ---------2 Arjun
ASP
2 12000
3 Gugan
ASP
2
20000
Q5: Drop a view.
Ans: SQL> drop view empview1;
View dropped.
SYNONYM

A synonym is an alias for any table, view, sequence, procedure, function, package, type,
Java class schema object. Since a synonym is simply an alias, it requires no storage other
than its definition in the data dictionary.
Syntax for Synonyms
CREATE [OR REPLACE] [PUBLIC] SYNONYM synonym_name
FOR [schema .] object_name [@ dblink];

Where
OR REPLACE allows you to recreate the synonym (if it already exists) without
having to issue a DROP synonym command.
PUBLIC means that the synonym is a public synonym and is accessible to all users.
Remember though that the user must first have the appropriate privileges to the object
to use the synonym.
schema is the appropriate schema. If this phrase is omitted, Oracle assumes that you
are referring to your own schema.
object_name is the name of the object for which you are creating the synonym
Example:
SQL> create public synonym empsynonym for emp_db;
Synonym created.
Perform select * from empsynonym;

SEQUENCES

If your table does not contain a candidate for primary key, you can use auto generated
sequence.
Syntax for Sequence
CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;

Example:
SQL> create sequence stud_seq
minvalue 1
maxvalue 20
start with 2
increment by 1
cache 10;
Sequence created.
Note: This would create a sequence object called stud_seq. The first sequence number that it
would use is 1 and each subsequent number would increment by 1 (ie: 2,3,4,...}. It will cache
up to 10 values for performance. If you omit the MAXVALUE option, your sequence will
automatically goto default value
stud_seq.nextval this will retrieve the next value from stud_seq.
you can use sequences as below
SQL>insert into student_db(studentid,firstname) values (stud_seq.nextval,Sammy);
INDEXES

Indexes are database objects for speeding up the querying of a table. An index can be created
on a single column or a combination of columns. Oracle automatically creates an index for
each UNIQUE or PRIMARY KEY declaration
Syntax for creating INDEX
CREATE[UNIQUE] INDEX INDEX_NAME ON TABLE_NAME(COLUMN_NAME)

Example
CREATE INDEX stu_idx_state

on student_db(state);

Or
CREATE INDEX stu_idx_state

on student_db(state,studentid);

index created
Drop Index
DROP INDEX stu_idx_state;

Result:
Thus the creation and manipulate various database objects of the Table using views
was successfully executed.

Exp 11:Visual Basic Designing and Application Development using VB as front end and
Oracle as backend
Aim: to design forms using VB and create an application with VB as front end and Oracle as
backend
Simple Calculator

PublicClass Form1
PrivateSub Button1_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button1.Click
If TextBox1.Text = "ramya"And TextBox2.Text = "ramya"Then
Form2.Visible = True
Else
MsgBox("please enter a valid username or password")
EndIf
EndSub
EndClass
On entering a invalid username or password



On entering a valid username and password

On clicking submit


Enter the operands and click ADD



FORM2

PublicClass Form2
PrivateSub Button5_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button5.Click
Me.Close()
Form1.Visible = True
EndSub
PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
TextBox3.Text = Val(TextBox1.Text) + Val(TextBox2.Text)
TextBox1.Clear()
TextBox2.Clear()
EndSub
PrivateSub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
TextBox3.Text = TextBox1.Text - TextBox2.Text
TextBox1.Clear()
TextBox2.Clear()
EndSub
PrivateSub Button3_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click
TextBox3.Text = TextBox1.Text * TextBox2.Text
TextBox1.Clear()
TextBox2.Clear()
EndSub
PrivateSub Button4_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button4.Click
TextBox3.Text = TextBox1.Text / TextBox2.Text
TextBox1.Clear()
TextBox2.Clear()
EndSub

EndClass


Working with Graphics

PublicClass Form1

PrivateSub Button1_Click(ByVal sender AsObject, ByVal e As


System.EventArgs) Handles Button1.Click
Dim myGraphics As Graphics = Me.CreateGraphics
Dim myPen As Pen
myPen = New Pen(Brushes.DarkMagenta, 10)
myGraphics.DrawLine(myPen, 10, 10, 100, 10)
EndSub
PrivateSub Button2_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button2.Click
Dim myGraphics As Graphics = Me.CreateGraphics
Dim myPen As Pen
myPen = New Pen(Brushes.DarkMagenta, 10)
myGraphics.DrawRectangle(myPen, 0, 0, 100, 50)
EndSub
PrivateSub Button3_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button3.Click
Dim myGraphics As Graphics = Me.CreateGraphics
Dim myPen As Pen
myPen = New Pen(Drawing.Color.Red, 5)

myPen.DashStyle = Drawing.Drawing2D.DashStyle.Dot
myGraphics.DrawRectangle(myPen, 10, 10, 100, 50)
EndSub
PrivateSub Button4_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button4.Click
Dim myGraphics As Graphics = Me.CreateGraphics
myGraphics.Clear(Me.BackColor)
EndSub
EndClass
On clicking Draw Line Button

On Clicking Draw Rectangle Button

On Clicking Draw Dashed Rect Button

Mini Project Sample


Employee Payroll System
SQL>descemployeetable;
Name Null? Type
----------------------------------------- -------- ---------------

ENAME VARCHAR2(20)
EID NUMBER
EDESIG VARCHAR2(20)
EPROJECT VARCHAR2(20)
EEMAIL VARCHAR2(20)
EPHONE NUMBER
SALARY NUMBER

SQL>descesalary;
Name Null? Type
----------------------------------------- -------- ----------

EID NUMBER
BASIC NUMBER
HRA NUMBER
PF NUMBER
DA NUMBER
BONUS NUMBER
SALARY NUMBER
FORM1
PublicClass Form1

PrivateSub Button1_Click(ByVal sender AsObject, ByVal e As


System.EventArgs) Handles Button1.Click
Form2.Show()
Me.Visible = False
EndSub
PrivateSub Button2_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button2.Click
Form3.Show()
Me.Visible = False
EndSub
PrivateSub Button3_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button3.Click
Form4.Show()
Me.Visible = False
EndSub
PrivateSub Button4_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button4.Click
Me.Close()
EndSub
PrivateSub Button5_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button5.Click
Form5.Show()
Me.Visible = False
EndSub
EndClass
FORM2
Imports System.Data
Imports Oracle.DataAccess.Client 'ODP.NET Oracle managed provider
Imports Oracle.DataAccess.Types
PublicClass Form2
PrivateSub Button1_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button1.Click
Dim oradb AsString = "Data Source=<name of DS>;User Id=<your
username>;Password=<your password>;"
Dim conn AsNew OracleConnection(oradb)
Dim rowsupdated AsInteger
conn.Open()
Dim cmd AsNew OracleCommand
cmd.Connection = conn
cmd.CommandText = "Insert into employeetable values('"&
TextBox1.Text &"',"& Val(TextBox2.Text) &",'"&
ListBox1.SelectedItem.ToString() &"','"& ListBox2.SelectedItem.ToString()
&"','"& TextBox3.Text &"',"& Val(TextBox4.Text) &",0000)"
rowsupdated = cmd.ExecuteNonQuery()
If (rowsupdated = 0) Then
MessageBox.Show("Record not inserted")
Else
MessageBox.Show("Success!")
EndIf

cmd.CommandText = "Insert into esalary values('"&


Val(TextBox2.Text) &"',0000,0000,0000,0000,0000,0000)"
rowsupdated = cmd.ExecuteNonQuery()
If (rowsupdated = 0) Then
MessageBox.Show("Record not inserted")
Else
MessageBox.Show("Success!")
EndIf
conn.Dispose()
EndSub
PrivateSub Button2_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button2.Click
Form1.Show()
Me.Close()
EndSub
EndClass
FORM3
Imports System.Data
Imports Oracle.DataAccess.Client 'ODP.NET Oracle managed provider
Imports Oracle.DataAccess.Types
PublicClass Form3
PrivateSub Button1_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button1.Click
Dim oradb AsString = "Data Source=<name of DS>;User Id=<your
username>;Password=<your password>;"
Dim conn AsNew OracleConnection(oradb)
Dim rowsupdated AsInteger
conn.Open()
Dim cmd AsNew OracleCommand
Dim cmd1 AsNew OracleCommand
cmd.Connection = conn
cmd.CommandText = "Delete from employeetable where eid="&
TextBox1.Text
rowsupdated = cmd.ExecuteNonQuery()
If (rowsupdated <> 0) Then
MessageBox.Show("Record deleted ")
Else
MessageBox.Show("not deleted")
EndIf
cmd1.Connection = conn
cmd1.CommandText = "Delete from esalary where eid='"& TextBox1.Text
&"'"
rowsupdated = cmd1.ExecuteNonQuery()
If (rowsupdated <> 0) Then
MessageBox.Show("Record deleted ")
Else
MessageBox.Show("not deleted")
EndIf
conn.Dispose()
EndSub

PrivateSub Button2_Click(ByVal sender AsObject, ByVal e As


System.EventArgs) Handles Button2.Click
Me.Close()
Form1.Visible = True
EndSub
EndClass
FORM4
Imports System.Data
Imports Oracle.DataAccess.Client 'ODP.NET Oracle managed provider
Imports Oracle.DataAccess.Types
PublicClass Form4
PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Basic AsDouble
Dim HRA AsDouble
Dim PF AsDouble
Dim DA AsDouble
Dim BONUS AsDouble
Dim GROSS AsDouble
Basic = Val(TextBox2.Text)
HRA = (40 / 100) * Basic
PF = (12 / 100) * Basic
DA = (30 / 100) * Basic
BONUS = (4 / 100) * Basic
GROSS = Basic + HRA + PF + DA + BONUS
TextBox3.Text
TextBox4.Text
TextBox5.Text
TextBox6.Text
TextBox7.Text

=
=
=
=
=

HRA
PF
DA
BONUS
GROSS

EndSub
PrivateSub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim oradb AsString = "Data Source=<name of DS>;User
Id=<yourusername>;Password=<your password>;"
Dim conn AsNew OracleConnection(oradb)
Dim rowsupdated AsInteger
conn.Open()
Dim cmd AsNew OracleCommand
cmd.Connection = conn
Dim myCMD AsNew OracleCommand()
myCMD.Connection = conn
myCMD.CommandText = "procempsal"
myCMD.CommandType = CommandType.StoredProcedure
myCMD.Parameters.Add("peid", OracleDbType.Varchar2).Value =
Val(TextBox1.Text)
myCMD.Parameters.Add("pgrosssalary", OracleDbType.Int32).Value =
Val(TextBox7.Text)
myCMD.ExecuteNonQuery()
cmd.CommandText = "update esalary set basic="& Val(TextBox2.Text)
&",hra="& Val(TextBox3.Text) &",pf="& Val(TextBox4.Text) &",da="&

Val(TextBox5.Text) &",bonus="& Val(TextBox6.Text) &",salary="&


Val(TextBox7.Text) &" where eid="& TextBox1.Text
rowsupdated = cmd.ExecuteNonQuery()
MsgBox("done")
If (rowsupdated = 0) Then
MessageBox.Show("Record not inserted")
Else
MessageBox.Show("Success!")
EndIf
conn.Dispose()
EndSub
PrivateSub Button3_Click(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles Button3.Click
Me.Close()
Form1.Visible = True
EndSub
EndClass
STORED PROCEDURE
SQL> create or replace procedure procempsal(peid number, pgrosssalary number)
2 as
3 begin
4 updateemployeetable set salary=pgrosssalary where eid=peid;
5 end;
6 /
FORM5
PublicClass Form5
PrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Form1.Visible = True
Me.Close()
EndSub
EndClass


On clicking ADD EMPLOYEE button

Input the values and click ADD button to upload the data to database

SQL> select * from employeetable;



ENAME EID EDESIG EPROJECT
-------------------- ---------- -------------------- -------------
EEMAIL EPHONE SALARY
-------------------- ---------- ----------
Prema 12 Developer Banking
prema@gmail.com 123456789 0


on clicking UPDATE SALARY button in the home page


Input only employee id and basic pay and click CALCULATE SALARY STRUCTURE button


Click UPLOAD button

SQL> select * from employeetable;

ENAME EID EDESIG EPROJECT
-------------------- ---------- -------------------- ---------------
EEMAIL EPHONE SALARY
-------------------- ---------- ----------
Prema 12 Developer Banking
prema@gmail.com 123456789 11160

SQL> select * from esalary;


EID BASIC HRA PF DA BONUS SALARY
---------- ---------- ---------- ---------- ---------- ---------- ----------
12 6000 2400 720 1800 240 11160

On clicking VIEW EMPLOYEE button


On clicking REMOVE EMPLOYEE button


SQL> select * from employeetable;
no rows selected
SQL> delete from esalary;
0 rows deleted.

You might also like