DBMS Lab Manual PDF
DBMS Lab Manual PDF
DBMS Lab Manual PDF
TECHNOLOGY
Loyola College campus, Nungambakkam, Chennai 34
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
Version: 1.1
Date of Revision:
Verified By:
Authorized By
Dr. R. Deepa
HoD IT
IT6312
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:
What is SQL?
Structured Query Language. It is a language designed specifically for communicating with databases.
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
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
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)
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
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),
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
2 ways
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
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,
°ree);
Run this statement and observe what happens.
The previous statement executed can be run again using /.
SALARY
e11
mahim
M 12 raj nagar
11-MAY-70 12-JUN-00 1
e13
ghaziabad up
anand
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.
table-name is the name of the table from which the information 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.
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
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;
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
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
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;
Percentage
66.5
83.5
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
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
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
REVOKE COMMAND
REVOKE [privilege name,[priv..]|ALL] ON object_name FROM
{user_name|PUBLIC|role_name}[CASCADE CONSTRAINTS]
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
Ex.no: 5. a
Aim:To perform nested Queries and joining Queries using DML command.
Step
no.
1
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 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.
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:
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:
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;
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
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;
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:
first_col_name, second_col_name, etc.,- it is the names the fields/columns within the record.
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;
Syntax
Usage
is scalar.
datatype, ...);
col_nametable_name.column_name%type;
record_namerecord_type_name;
record_nametable_name%ROWTYPE;
If you used %ROWTYPE to declare a record, you can assign values as shown:
record_name.column_name := value;
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:
The following table consolidates the different ways you can assign values to and from a record:
Syntax
Usage
record_name.col_name := value;
record_name.column_name := value;
clause];
SELECT * INTO record_name FROM table_name [WHERE To assign a value to all fields in the record
clause];
variable_name := record_name.col_name;
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.
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.
d) Program:
SQL>
declare
a number(10);
b number(10);
begin
c number(10);
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
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:
a:=&a;
rev:=0;
while a>0 loop
d:=mod(a,10);
rev:=(rev*10)+d;
a:=trunc(a/10);
end loop;
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
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
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
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
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
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;
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
ORA06511
INVALID_CURSOR
ORA01001
NO_DATA_FOUND
TOO_MANY_ROWS
ORA01403
ORA01422
ZERO_DIVIDE
ORA01476
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.
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.
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).
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.
[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.
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
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
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
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
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
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.
After Triggers
After triggers are fired after the
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
Create a trigger for each row that insert the current user as user name into a table
d)Program:
Q2: Create a Simple Trigger that does not allow Insert Update and Delete Operations
on the Table
d)Program: Table
used:
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:
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:
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
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
=
=
=
=
=
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="&
On clicking ADD EMPLOYEE button
Input the values and click ADD button to upload the data to database
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.