Documente Academic
Documente Profesional
Documente Cultură
No
Write a PL/SQL block to satisfy some conditions by accepting input from the
user.
Creation of Procedures
10
INTRODUCTION TO DBMS
OVERVIEW OF RDBMS:
RDBMS
is
the
acronym
for
Relational
Data
Base
Management System. The concept of relational database is known since 1980s but
the idea of Data Base Management System is definitely old. The most famous
RDBMS packages are Oracle, Sybase, and Informix.
What is DBMS?
DBMS is the program that organizes and maintains the information whereas the
Database Application is the program that lets us view, retrieve and update
information stored in the DBMS.
DBMS has to protect against unintentional changes that could be caused by
users and applications. In case of multi user system, it must be capable of notifying
any database change to the other user.
DBMS offers following services:
Data
Definition
Data
maintena
nce Data
Manipulat
ion Data
display
Data Integrity
Page 1
INTRODUCTION TO
ORACLE
The tools provided by Oracle are so user friendly that a person with
minimum skillls in the field of computer can access them with ease. The main tools are
SQL * Plus
Page 2
PL/SQL
Fo
rm
s
Re
po
rts
S
Q
L
*
Pl
us
:
SQL * Plus is a Structered Query Language supported by Oracle.
Through SQl* Plus we can store, retrieve, edit, enter and run SQL commands and
PL/SQL blocks. Using SQl * Plus we can perform calculations, list column
definitions for any table and can format query results in the form of a report.
PL/SQL:
Forms:
Page 3
Ability to break the most frequently used object, the table into smaller
units thereby reducing the risk to loss of data.
Page 4
INTRODUCTION TO
SQL
SQL was invented and developed by IBM in early 1970s. SQL stands
for Structured Query Language. IBM was able to demonstrate how to control
relational
database
using
SQL.
The
SQL
implemented
by
ORACLE
CORPORATION is 100% compliant with the ANSI/ ISO standard SQL data
language. Oracles database language is SQL, which is used for storing and
retrieving information in Oracle. A table is a Primary database object of SQL that is
used to store data. A table that holds data in the form of rows and columns.
In order to communicate with the database, SQL supports the following
categories of commands: Data Definition Language
- grant and
revoke commands.
Data Definition Language:
and
PL/SQL
blocks
and
executes
them.
SQL
*Plus
enables
enter, edit, store, retrieve and run SQL commands and PL/SQL blocks.
format, perform calculations, store and print query results in the form of reports.
Page 6
Ex.No:1.
AI
M:
To create a database and write SQL queries to retrieve information from the database.
DESCRIPTION:
Data Definition Language:
DDL (Data Definition Language) statements are used to create, change the
objects of a database. Typically a database administrator is responsible for using
DDL statements or production databases in a large database system.
The commands used are:
Create - It is used to create a table.
Alter - This command is used to add a new column, modify the
existing column definition and to include or drop integrity constraint.
Drop - It will delete the table structure provided the table should be empty.
Truncate - If there is no further use of records stored in a table and the
structure has to be retained, and then the records alone can be deleted.
Desc - This is used to view the structure of the table.
SYNTAX:
CREATE TABLE:
ALTER TABLE:
DESCRIBING TABLE:
Page 7
TRUNCATE:
The truncate table statement
removes all rows from a table
Release the storage space used by that table
DROP TABLE:
1. All data and structure in the table is deleted
2. Any pending transactions are committed.
3. All indexes are dropped.
Page 8
Table created.
SQL> desc tbl03; Name
Null?
Type
VARCHAR2 (10)
AGE
NUMBER (2)
MARKS
NUMBER (2)
Name
Null?
Type
NUMBER (2)
REGNO
NUMBER (12)
NAME
VARCHAR2 (10)
AGE
NUMBER (2)
MARKS
NUMBER (2)
TOTAL
NUMBER (3)
SQL> insert into tbl03 values (&sno, ®no,'&name', &age, &marks, &total);
Page 9
Abishek
Enter value for marks:
99 Enter value for total: 599
old 1: insert into tbl03 values (&sno, ®no,'&name', &age, &marks, &total) new 1: insert into tbl03 values (02, 003,'Abishe
1 row created.
1 row created.
SNO
REGNO
NAME
AGE
MARKS
TOTAL
SNO REGNO
---------- -------------
NAME
AGE
MARKS
TOTAL
003
Abishek
18
99
599
22
023
Iasi
18
98
598
003
Abishek
18
99
599
Page 10
AGE
NAME
MARKS
TOTAL
003name='Isai';Abishek
SQL> update 2tbl03 set total=95 where
18
99
599
22
1 row updated.
20
98
598
023
Isai
SNO
REGNO
NAME
AGE
MARKS
TOTAL
18
99
599
ERRO
R at
line 1:
Page 11
*
ERROR:
ORA-04043: object tbl03z does not exist
ORA-00942: table or view does not
exist SQL> desc tbl03z;
RESULT:
Page 12
Ex.No.2.
Select command with where clause: To select specific rows from a table we include
where clause in the select command. It can appear only after the from clause.
Syntax: Select column_name1, ..,column_namen from table name where condition;
Select command with order by clause:
Syntax: Select column_name1, ..,column_namen from table name where
condition order by colmnname;
Select command to create a table:
Syntax: create table tablename as select * from existing_tablename;
Select command to insert records:
Syntax: insert into tablename ( select columns from existing_tablename);
UPDATE - It is used to alter the column values in a table. A single column may be
updated or more than one column could be updated.
update <table name> set (fieldname-1 = value, fieldname-2 = value,
,fieldname-n = value) [WHERE <condition/expression>];
DELETE - After inserting row in a table we can also delete them if required. The
delete command consists of a from clause followed by an optional where clause.
delete from <table name> [where <condition/expression>];
ALTER TABLE
alter table <table name> modify (fieldname-1 data type (new size));
alter table drop column
column name; Table altered.
Page 14
SAMPLE OUTPUT:
INSERT, SELECT, UPDATE AND DELETE COMMANDS
SQL> create table person(pid int, lastname varchar2(10),firstname
varchar(10), address varchar2(20),age number);
Table created.
INSERTING A SINGLE ROW INTO A TABLE
SQL> insert into person
values(1,'Prettina','Anne','Bangalore',14); 1 row created.
SQL> insert into person
values(2,'Benitto','Anish','Trichy',24); 1 row
created.
SQL> select * from person;
Page 15
Page 16
1 row updated.
UPDATE VALUES USING &
SQL> update person set address ='&address',age=&age where
pid=&pid; Enter value for address: Assam
Enter value for
age: 40 Enter
value for pid: 6
old 1: update person set address ='&address',age=&age where
pid=&pid new 1: update person set address ='Assam',age=40
where pid=6
1 row
updated.
SQL> /
Enter value for address:
Britain Enter value for
age: 55
Enter value for pid: 5
old 1: update person set address ='&address',age=&age where
pid=&pid new 1: update person set address ='Britain',age=55
where pid=5
1 row updated.
SELECT COMMAND TO RETRIEVE THE ENTIRE INFORMATION FROM THE TABLE
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
---------- ---------- ---------- -------------------- ---------1 Prettina Anne Bangalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
6 rows selected.
SELECT COMMAND USING 'WHERE' CLAUSE
SQL>select * from person where lastname= 'Kumar' and
address='Coimbatore'; PID LASTNAME FIRSTNAME ADDRESS
AGE
---------- ---------- ---------- -------------------- ---------4 Kumar Ashok Coimbatore 30
Page 17
t
t
o
H
i
n
n
K
u
m
a
r
P
r
a
k
a
s
h
P
r
e
t
t
i
n
a
R
a
j
6 rows selected.
SELECT COMMAND WITH ORDER BY CLAUSE
SQL> select pid, firstname,age from person order by age;
Page 18
7
SQL> select count(distinct lastname) as pid from
person; PID
6
SQL> select max(age) from person;
MAX(AGE)
5
5
Page 19
RESULT:
Thus the Insertion, Deletion, Modifying, Altering, Updating and Viewing records based
on conditions in RDBMS were executed and verified.
Page 21
Ex.No.3
POINT
AI
M:
DESCRI
PTION:
VIEWS
In SQL, a view is a virtual table based on the result-set of an SQL
statement. A view contains rows and columns, just like a real table. The fields in a
view are fields from one or more real tables in the database.
A view is an object that gives the user the logical view of data from the
underlying table. Any relation that is not part of the logical model but is made
visible to the user as a virtual relation is called a view. They are generally used to
avoid duplication of data.
Views are created for the following reasons,
Data simplicity
Structural simplicity (because view contains only limited number of rows and
columns)
TYPES OF VIEWS
Page 22
INDEXES
Indexes are special lookup tables that the database search engine can use to
speed up data retrieval. An index is a pointer to data in a table. An index in a
database is very similar to an index in the back of a book. An index helps speed up
SELECT queries and WHERE clauses, but it slows down data input, with UPDATE
and INSERT statements. Indexes can be created or dropped with no effect on the
data. Index in sql is created on existing tables to retrieve the rows quickly. When
there are thousands of records in a table, retrieving information will take a long time.
Therefore indexes are created on columns which are accessed frequently, so that
the information can be retrieved quickly. Indexes can be created on a single column
or a group of columns. When an index is created, it first sorts the data and then it
assigns a ROWID for each row.
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries
table_name is the name of the table to which the indexed column belongs.
SEQUENCE
A sequence is a user-defined schema bound object that generates a sequence
of numeric values according to the specification with which the sequence was
created. The sequence of numeric values is generated in an ascending or descending
order at a defined interval and can be configured to restart (cycle) when exhausted.
Sequences, unlike identity columns, are not
Page 23
associated with specific tables. Applications refer to a sequence object to retrieve its
next value. The relationship between sequences and tables is controlled by the
application. User applications can reference a sequence object and coordinate the
values across multiple rows and tables.
SYNTAX
CREATE SEQUENCE
sequence_name MINVALUE value
MAXVALUE
value START
WITH value
INCREMENT
BY value
CACHE value;
Drop Sequence: Syntax: DROP SEQUENCE sequence_name
Transactional control commands are only used with the DML commands INSERT,
UPDATE and DELETE only. They cannot be used while creating tables or dropping
them because these operations are automatically committed in the database.
The COMMIT Command
The COMMIT command is the transactional command used to save changes invoked
by a transaction to the database. The COMMIT command saves all transactions to the
database since the last COMMIT or ROLLBACK command.
Syntax: COMMIT;
Page 24
ROLLBACK TO SAVEPOINT_NAME;
Following is an example where you plan to delete the three different records
from the CUSTOMERS table. You want to create a SAVEPOINT before each
delete, so that you can ROLLBACK to any SAVEPOINT at any time to return the
appropriate data to its original state: The RELEASE SAVEPOINT Command
The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have
created.
Syntax: RELEASE SAVEPOINT SAVEPOINT_NAME;
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK
command to undo transactions performed since the SAVEPOINT.
undo transactions performed since the SAVEPOINT.
SYNONYMS
Synonym is an alternative name for a table, view, sequence, operator,
procedure, stored function, package, materialized view, Java class schema object,
user-defined object type, or another synonym. A synonym places a dependency on its
target object and becomes invalid if the target object is changed or dropped.
CREATE SYNONYM offices
FOR
hr.locati
ons;
Page 25
SAMPLE
OUTPUT:
VIEWS
SQL>create table kavi1(name varchar(20),rno number(5),marks number(5),primary key
(rno));
Table created. SQL> desc kavi1; NAME
NULL?
TYPE
-------------------------------------------------------------------------------------------------
NAME
RNO
VARCHAR (20)
NUMBER (5)
NUMBER (5)
MARKS
-----------------------------------------------------------------------------------------prami
kavi indhu
1001
1002
1003
350
298
375
number (5), primary key (roll no));
NAME
NULL?
TYPE
----------------------------------------------------------------------------------ROLLNO
NOTNULL
NUMBER (5)
ATTENDENCE
NUMBER (5)
Page 26
1 row created.
SQL> insert into kavi2 values
(1002, 75); 1 row created.
SQL> insert into kavi2 values (1003, 85);
1 row created.
SQL> select * from kavi2;
ROLLNO
ATTENDENCE
----------------------------------------------------------------------------------------1001
90
1002
75
1003
85
SQL> create view rollno=rno;
kaviview as select name, rno, marks, attendance from kavi1, kavi2
view created.
where
RNO
MARKS
ATTENDENCE
---------------------------------------------------------------------------------------------------------------------
RNO
MARKS
ATTENDENCE
---------------------------------------------------------------------------------------------------------------------
prami
1001
350
90
kavi
1002
298
75
indhu
SQL> update kaviview 1 row
1003
set
375
85
updated.
prami
1001
352
90
priya
1002
298
75
indhu
1003
375
85
Page 27
SEQUENCE
SQL> create table supplier2 (supplierid number (10), supplier name varchar (20)); Table created.
SQL>insert into supplier2 values (10,ganesh); 1 row created.
SQL> select * from supplier2;
SUPPLIER ID
SUPPLIERNAME
-------------------------------------------------------------------------------10
ganesh
MINVALUE 1
STARTWITH 1
INCREMENT BY 1
CACHE 20
Sequence created.
SQL> insert into supplier2 (supplier id, supplier name) values
(supplier2_seq.NEXTVAL,Kra
ftfoods); 1 row created.
Page 28
10
1
ganesh
Kraftfoods
SYNONYMS
create public synonym suppliers for app.suppliers; Synonym created.
TCL COMMANDS
SQL> create table tb43 (rno number(2),name varchar(10)); Table created;
SQL>insert into tb43 values(2,kavi); 1 row created.
SQL>insert into tb43 values(3,prami);
1 row created.
created.
Page 29
NAME
--------------------------------------------------2
kavi
prami
geetha
SQL>
commit;
Commit
complete.
SQL>insert into tb43
values(5,indhu); 1 row
created.
SQL> select * from tb43;
RNO
NAME
----------------------------------------------------------2
kavi
prami
geetha
indhu
SQL>rollbac
k; Rollback
complete;
SQL> select * from tb43;
RNO
NAME
----------------------------------------------------2
kavi
prami
geetha
SQL>save
point s1;
Save point
created;
SQL> delete * from tb43
where rno=3; 1 row deleted.
SQL> select * from tb43;
Page 30
prami
NAME
RNO
NAME
------------------------------------------------------------------------------------------------------------kavi
prami balu
2
kavi
2
3
7
SQL> rollback to s1; Rollback complete;
SQL> select * from tb43;
RNO
NAME
-----------------------------------------------------2
3
kavi
prami
RESULT:
Thus the Views, Sequence, Indexes, Save point and Synonyms are implemented
in SQL.
Page 31
DESCRIPTION:
SQL CONSTRAINTS
Constraints are the rules enforced on data columns on table. These are used to limit the type of data that can go into a tab
Constraints could be column level or table level. Column level constraints are applied only to one column, whereas table
Ex. No.
AN EMPLOYEE DATABASE TO SET VARIOUS
Following are commonly
used4.constraintsCREATING
available in SQL.
NOT NULL Constraint: Ensures that a column cannot CONSTRAINTS
have NULL value.
UNIQUE Constraint: Ensures that all values in a column are different.
AIM identified each rows/records in a database table.
PRIMARY Key: Uniquely
FOREIGN Key: Uniquely identified a rows/records in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain conditions.
Page 32
SAMPLE
OUTPUT: NOT
NULL
SQL>
CREATE
TABLE
EMPLOYEE
(EMP_NO
NUMBER(6)NOT
Null?
Type
NOT NULL
NUMBER(6)
NAME
VARCHAR2(10)
BRANCH
VARCHAR2(6)
1 row created.
SQL> SELECT * FROM
EMPLOYEE; EMP_NO
NAME
BRANCH
--------------
-------------- -------------
501
ABHILASH CHENNAI
502
ABI
CHENNAI
Page 33
UNIQUE
SQL>
CREATE
TABLE
EMPLOYEE
(EMP_NO
NUMBER(6)
UNIQUE
Page 34
PRIMARY KEY
SQL> CREATE TABLE EMPLOYEE (EMP_NO NUMBER(6) PRIMARY KEY
,NAME VARCHAR2(10),BRANCH VARCHAR2(6));
Table created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for
emp_no: 501 Enter
value for name:
abhilash Enter value
for branch: chennai
old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')
new 1: INSERT INTO EMPLOYEE VALUES(501,'abhilash',
chennai) 1 row created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for
emp_no: 502 Enter
value for name: ABI
Enter value for branch: CHENNAI
old 1: INSERT INTO EMPLOYEE
VALUES(&EMP_NO,'&NAME','&BRANCH') new 1: INSERT INTO
EMPLOYEE VALUES(502,'ABI','CHENNAI')
1 row created.
SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');
Enter value for
emp_no: 502 Enter
value for name:
BHAVYA
Enter value for branch: CHENNAI
old 1: INSERT INTO EMPLOYEE
VALUES(&EMP_NO,'&NAME','&BRANCH') new 1: INSERT INTO
EMPLOYEE VALUES(502,'BHAVYA', 'CHENNAI')
Page 35
NAME
BRANCH
----------
----------
-----------
501
ABHILASH
CHENNAI
502
ABI
CHENNAI
CHECK
SQL>
Page 36
Page 37
1 row created.
SQL> insert into adm values(&emp_id,'&ename',&per); Enter value for emp_id: 4
Enter value for ename: naveen Enter value for per: 70
old 1: insert into adm values(&emp_id,'&ename',&per) new 1: insert into adm values(4,'naveen',70)
1 row created.
SQL> select * from adm;
Enter value for per: 99
old 1: insert into adm
values(&emp_id,'&ename',&per) new 1: insert
into adm values(3,'sachin',99)
EMP_ID
---------- 1
2
3
4
ENAME
PER
--------------- ---------abi
80
rohit 89
sachin 99
naveen 70
emp_id: 5 Enter
value for branch:
cse
Page 38
department
values(5,'cse','b')
insert into department
values(5,'cse','b')
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SID_FK) violated - parent key not found SQL> delete from adm where emp_id=1;
*
ERROR at line 1:
ORA-02292: integrity constraint (SCOTT.SID_FK) violated - child record found SQL> delete from department where emp_id=
1 row deleted.
SQL> delete from adm where emp_id=1; 1 row deleted.
SQL>select * from adm; EMP_ID ENAME PER
----- --------------- - ----------
RESULT :
Thus an Employee database with various constraints was created and the output was verified.
rohit
89
sachin
99
naveen
70
Page 39
Ex.No.5
AI
M:
commands.
DESCRIPTION:
PRIMARY KEY
Most tables should have a primary key, and each table can have
only ONE primary key.
SYNTAX:
create table<table name>(fieldname1 datatatype (size) primary key);
FOREIGNKEY
The table containing the foreign key is called the referencing or child
table and the table containing the candidate key is called the
referenced or parent table
If a table has a primary key defined on any fields, then you cannot
have two records having the same value of those fields.
SYNTAX:
create table<table name>(fieldname1 data type(size) constraint first table primary key);
Page 40
SAMPLE OUTPUT:
Table name: Branch
SQL>Create table branch(branch_name varchar2(30) primary key, branch_city
varchar2(20), assets number);
Table created.
SQL>desc
branch;
Name
Null?
Type
-------------------------------------------------------------------- BRANCH_NAME
NOT
NUMBER
===================================================================
==
Table name: Customer
SQL>create table customer(customer_id varchar2(10) primary key, customer_name
varchar2(20), customer_Street varchar2(15), customer_City varchar2(15));
Table
created.
SQL>desc
customer;
Name
Null?
Type
VARCHAR2(15)
CUSTOMER_CITY
VARCHAR2(15)
===================================================================
==
Page 41
Name
Null?
Type
VARCHAR2(30)
NUMBER
Name
Null?
Type
--------------------------------------------------------------------
====================================================================
Table name: borrower
SQL>create table borrower (customer_id varchar2(11) references customer(customer_id),loan_no varchar2(4) referenc
SQL> desc borrower;
LOAN_NO
NOT NULL VARCHAR2(4)
Name
Null?
Type
BRANCH_NAME
VARCHAR2(20)
----------------------------------------- -------- ---------------------------AMOUNT
NUMBER
CUSTOMER_ID
VARCHAR2(11)
LOAN_NO
VARCHAR2(4)
Page 42
Null?
Type
VARCHAR2(11)
===============================================================
====== INSERTING RECORDS IN ALL THE SIX CREATED TABLES:
SQL> insert into branch values ('tambaram','chennai-45', 50000)
SQL>insert into customer values ('cus_109','mohammed','southeast_masi','chennai-32')
SQL>insert into account values ('735_105','chrompet', 5000)
AMOUNT
ln_101
900
cus_101
ln_106
2000
cus_103
ln_107
500
cus_105
ln_105
1000
cus_103
ln_104
1300
cus_105
ln_102
1500
6 rows selected.
Page 43
2. For all customers who have loan at tambaram branch find their
IDs,loan ID,loan amount.(Join)
SQL> select borrower.CUSTOMER_ID,loan.LOAN_NO,loan.AMOUNT from loan, borrower
LOAN_NO
AMOUNT
ln_104
1300
BRANCH_NAME
NO_OF_DEPOSITOR
------------------------------ -----------------------------------------------
adayar
chrompet
guindy
saidapet
tnagar
RESULT:
Page 44
Ex.No .6
STUDY OF
DESCRI
PTION:
PL/SQL
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 from the part of execution section.
Page 45
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/SQL Block 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.
A Sample PL/SQL Block
Looks like: DECLARE
Variable
declaration
BEGIN
Program
Execution
EXCEPTION
Exception
handling
END;
PL/SQL Block Structure:
DECLARE
v_variable
VARCHAR2(5); BEGIN
SELECT
column_name
INTO
v_variable
FROM
table_name;
EXCEPTION
Procedure
PROCEDURE name IS
BEGIN
--statements [EXCEPTION] END;
PROCEDURE name
Function FUNCTION name RETURN datatype IS
BEGIN
--statements RETURN value; [EXCEPTION]
END;
RESULT:
Page 47
To write a PL/SQL block to satisfy some conditions by accepting input from the user
using oracle.
DESCRIPTION:
PL/SQL Control Structure provides conditional tests, loops, flow control and branches that let to produce well-structured progra
Ex.No.7
WRITE A PL/SQL BLOCK TO SATISFY SOME
CONDITIONS BY ACCEPTING INPUT FROM THE
USER.
SYNTAX:
DECLARE
AIM:
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
PL/ SQL GENERAL SYNTAX
SQL> declare
<variable declaration>; begin
<executable statement >; end;
PL/ SQL GENERAL SYNTAX FOR IF CONDITION
SQL> declare
<variable declaration>; begin
if(condition) then
<executable
statement >;
end;
Page 48
Page 49
3 c number;
4 begin
5 a: =&a;
6 b: =&b;
7 c: =a+b;
8 dbms_output.put_line ('sum of'||a||'and'||b||'is'||c);
Page 50
7 if(C>B) THEN
8 dbms_output.put_line('C is maximum');
Page 51
OUTPUT
C is maximum
PL/SQL procedure successfully completed.
12 /
Page 52
INPUT
Enter value for
number: 2 old 5:
n:=&number;
new 5: n:=2;
OUTPUT
entered number is less than 5
PL/SQL procedure successfully completed.
PL/ SQL PROGRAM FOR IF ELSE IF CONDITION
( Write a PL/SQL Program to find the greatest of three numbers using if else if )
PROCEDURE
STEP 1: Start
STEP 2: Initialize the necessary
variables. STEP 3: invoke the if
else if condition.
STEP 4: Execute the
statements. STEP 5:
Stop.
PROGRAM
SQL>set server
output on SQL>
declare
2 a number;
3 b number;
4 c number;
5
b
e
gi
n
6
a:
=
&
a;
7
b:
=
&
b;
8
c:
=
&
c;
9 if(a>b)and(a>c) then
10 dbms_output.put_line('A is
maximum'); 11 else
if(b>a)and(b>c)then
12 dbms_output.put_line('B is maximum');
13 else
14 dbms_output.put_line('C is maximum');
Page 53
INPUT
Enter value for a: 21 old 7: a:=&a;
new 7: a:=21;
Enter value for b: 12 old 8: b:=&b;
new 8: b:=12;
Enter value for b: 45 old 9: c:=&b;
new 9: c:=45;
OUTPUT 15 end if;
C is maximum
16 end;
PL/SQL procedure successfully completed.
17 /
3 sum1 number
default 0; 4 end
value number;
Page 54
for n in 1..endvalue
loop
if mod(n,2)=1
then
sum1:=sum1+n;
end if;
end loop;
5 begin ='||sum1);
dbms_output.put_line('sum
end;
6 end
17 /
value:=&end
INPUT
Enter value for end value:
6: end value:=&end value; new 6: end value:=4; OUTPUT
value; 47 old
n:=1;
sum =4
PL/SQL procedure successfully completed.
Page 55
SQL>1 declare
n number;
i number;
p number:=1;
begin
6 n:=&n;
7 for i in 1..n loop 8 p:=p*i;
end loop;
dbms_output.put_line(n ||' ! = '||p); 11* end;
PROGRAM
Enter value for n: 5 old 6: n:=&n;
new 6: n:=5;SQL>set server output on
5 ! = 120
PL/SQL procedure successfully completed.
RESULT:
Thus a PL/SQL block to satisfy some conditions by accepting input from the
user was created using oracle.
Page 56
Ex.No.8
AI
M:
To implement and execute PL/SQL Block that handles all types of exceptions in
Oracle
DESCRI
PTION:
EXCEPT
IONS
In PL/SQL, the user can catch certain runtime errors. Exceptions can be
internally defined by Oracle or the user. Exceptions are used to handle errors that
occur in your PL/SQL code. A PL/SQL block contains an EXCEPTION block to
handle exception.
There are three types of exceptions:
1. Predefined Oracle errors
2. Undefined Oracle errors
3. User-defined errors
The different parts of the exception.
1. Declare the exception.
2. Raise an exception.
3. Handle the
exception. An
exception has four
attributes:
1. Name provides a short description of the problem.
2. Type identifies the area of the error.
3. Exception Code gives a numeric representation of the exception.
Page 57
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 messages which explains
its cause is received. PL/SQL Exception message consists of three parts.
Type of
Exception
An Error
Code
A message
STRUCTURE OF EXCEPTION HANDLING
GENERAL SYNTAX FOR CODING THE EXCEPTION SECTION
DECLARE
Declaration
section
BEGIN
Exception
section
EXCEPTI
ON
WHEN ex_name1 THEN
-Error handling
statements WHEN
ex_name2 THEN
-Error handling
statements WHEN
Others THEN
-Error handling
statements END;
Types of Exception
There are 2 types of Exceptions.
a) System Exceptions
b) User-defined Exceptions
a) 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.
Page 58
EPTI
ON
WHEN
exception_name THEN
statement;
END;
Page 59
INVALID_CURSOR
VALUE_ERROR
INVALID_NUMBER
ZERO_DIVIDE
DUP_VAL_ON_INDEX
CURSOR_ALREADY_OPEN
NOT_LOGGED_ON
TRANSACTION_BACKED_OUT
LOGIN_DENIED
PROGRAM_ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
OTHERS
PROGRAM
ZERO_DIVIDE EXCEPTION
SQL> BEGIN
2
3
E
N
D;
4
DBMS_OUTPUT.PUT_LINE(1 / 0);
/
O
U
T
P
U
T
begin
*
ERROR at line 1:
Page 60
ORA-01476: divisor is
equal to zero ORA06512: at line 2
BEGIN
2 DBMS_OUTPUT.PUT_LINE(1 / 0);
3 EXCEPTION
4 WHEN ZERO_DIVIDE THEN
5 DBMS_OUTPUT.PUT_LINE('Division by zero');
6
E
N
D
;
7
/
Division by zero:
PL/SQL procedure successfully completed.
INVALID_NUMBER EXCEPTION
1 BEGIN
2 INSERT INTO employees(DEPARTMENT_ID)VALUES('101x');
3 EXCEPTION
4 WHEN INVALID_NUMBER THEN
5 DBMS_OUTPUT.PUT_LINE('Conversion of string to number
failed'); 6* end;
SQL> /
Conversion of string to number
failed PL/SQL procedure
successfully completed. OTHERS
EXCEPTION
1
BEGIN
DBMS_OUTPUT.PUT_LINE(1 / 0);
EXCEPTION
DBMS_OUTPUT.PUT_LINE('An exception
occurred'); 6* END;
7 /
An exception occurred
Page 61
EXCEPTION;
ABOVE_SALARY_RANGE
EXCEPTION;
-- salary variables
n_salary employees.salary%TYPE;
n_min_salary employees.salary
%TYPE; n_max_salary
employees.salary%TYPE;
-- input employee id
Page 62
n_emp_id employees.employee_id%TYPE :=
&emp_id; BEGIN
SELECT salary, min_salary max_salary INTO n_salary, n_min_salary,
n_max_salary FROM employees
INNER JOIN jobs ON jobs.job_id =
employees.job_id WHERE employee_id =
n_emp_id;
IF n_salary < n_min_salary
THEN RAISE
BELOW_SALARY_RANGE
;
ELSIF n_salary >
n_max_salary THEN
RAISE
ABOVE_SALARY_RANG
E;
END IF;
dbms_output.put_line('Employee ' || n_emp_id ||
' has salary $' || n_salary );
EXCEPTION
WHEN BELOW_SALARY_RANGE THEN
dbms_output.put_line('Employee ' ||
n_emp_id || ' has salary below
the salary range');
WHEN ABOVE_SALARY_RANGE THEN
dbms_output.put_line('Employee ' ||
n_emp_id || ' has salary above
the salary range');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee ' || n_emp_id || ' not
found'); END;
/
RESULT:
Thus a PL/SQL block that handles all type of exceptions was written,
executed and verified successfully.
Page 63
Ex.No.9
CREATION OF
PROCEDURES AIM:
To implement and execute Procedures in Oracle Database using Procedural Language
concepts.
DESCRIPTION:
PROCEDURES
Procedure is a sub program used to perform an action.
Replace-recreates the procedure if it already exists.
3 MODES
IN Means you must specify a value for the argument at the time execution of the procedure.
OUT-passes back a value to its calling program.
INOUT When calling the procedure, yu must specify the value and that procedures passes value back to the calling procedure
SYNTAX
Create or replace procedure <procedure_name> (argument {in, out, in out} data type) {is, as} Variable declaration
Begin
Pl/SQL Subprogram body. Exception
Exception PL/SQL Block.
End;
Page 64
begin
dbms_output.put_line('hello from procedure...'); 4 end;
5/
OUTPUT
Procedure created. SQL> EXECUTE proc1
Hello from procedure...
PL/SQL procedure successfully completed.
I) PROCEDURE USING POSITIONAL PARAMETERS:
SQL> set serveroutput on
SQL> create or replace procedure proc1 as
Page 65
18 end
19
Procedure
created
Page 66
SQL>decl
are
2 n number;
3 begin
4 n:=&n;
5 rev(n);
6 end;
7/
OUTPUT
Enter value for n:876
The reversed number is 678
PL/SQL procedure successfully completed.
IV) PROCEDURE FOR GCD OF
NUMBERS SQL> create or replace
procedure pro is
a
numb
er(3);
b
numb
er(3);
c
numb
er(3);
d
numb
er(3);
begin
a:=&a;
b:=&
b;
if(a>
b)
then
c:=m
od(a,
b);
if(c=
0)
then
dbms_output.put_line('GCD is');
dbms_output.put_line(b);
else
dbms_output.put_line('GCD is');
dbms_output.put_line(c);
end if;
Page 67
else
d:=m
od(b,
a);
if(d=
0)
then
dbms_output.put_line('G
CD is');
dbms_output.put_line(a);
else
dbms_output.put_line('G
CD is');
dbms_output.put_line(d)
;
e
n
d
i
f
;
e
n
d
i
f
;
e
n
d
;
/
Enter value
for a: 8 old
8: a:=&a;
new 8: a:=8;
Enter value
for b: 16 old
9: b:=&b;
new 9:
b:=16;
Procedure
created.
SQL> set
serveroutput on;
SQL> execute
pro;
G
C
D
i
s
8
PL/SQL procedure successfully completed.
V) PROCEDURE FOR CURSOR IMPLEMENATION
create table st13(regno number(4),name varchar2(20),mark1 number(3),mark2
number(3),mark3
numbe r(3),mark4 number(3),mark5
number(3)); insert into st13
values(101,'raji',100,90,97,89,91);
Page 68
insert
into
REGNO
NAME MARK1
------ -------- -----------raji
100
kali
99
jaya 78
a13
MARK2
MARK3
MARK4 MARK5
---------- 90
---------- ---------------77
97
89
91
88
69
81
99
77
60
89
values(102,'kali');
insert
into
a13
SQL>set server output on
values(103,'jaya');
declare
ave number(5,2); totselect
number(3);
* from st13;
cursor c_mark is select * from st13 where mark1>=40 and mark2>=40 and mark3>=40 and mark4>=40 and mark5>=40;
begin
dbms_output.put_line('regno name mark1 mark2 mark3 mark4 mark5 total average'); dbms_output.put_line('-----------------------for student in c_mark loop
tot:=st13.mark1+st13.mark2+st13.mark3+st13.mark4+st13.mark5; ave:=tot/5;
dbms_output.put_line(st13.regno||rpad(st13.name,15)||rpad(st13.mark1,6)||rpad(st13.mark2,6)||rp ad(st13.mark3,6)||rpad(st13.m
end loop; end;
/
Page 69
100 90 97
89
91 467
93.4
102kali
99
77
69
81 99
425
85
103jaya
78 88
77
60 89
392
78.4
MGR
HIREDATE
Page 70
u
t
:
Enter value for empno: 7844
old 6: WHERE EMPNO =
&EMPNO; new 6: WHERE
EMPNO = 7844;
PL/SQL procedure successfully completed.
EXPLICIT CURSORS
SQL> DECLARE
2 ena EMP.ENAME%TYPE;
3 esa EMP.SAL%TYPE;
4 CURSOR c1 IS SELECT ename,sal FROM EMP;
5 BEGIN
Page 71
RESULT:
Thus, Procedures in Oracle Database using Procedural Language concepts were implemented
Page 72
Ex. No 10
FUNCTIONS AIM:
To create database triggers and functions.
DESCRI
PTION:
TRIGGE
R
A trigger is a statement that is executed automatically by the system as a side effect
of a modification to the database. The parts of a trigger are,
Trigger statement: Specifies the DML statements and fires the trigger
body. It also specifies the table to which the trigger is associated.
TYPES OF TRIGGERS
The various types of triggers are as follows,
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
:new
:old
Page 73
RNO
NAME
--------------------------------01
02
kala
priya
SQL>create or replace trigger pool before insert on poo for each row
2 declare
3 rno poo.rno%type
Page 74
5 begin
6 open c;
7 loop;
FUNCTIONS:
Functions are routines that accept parameters, perform an action such as a complex calculation and return the result of that actio
PROCEDURE
STEP 1: Start
Page 75
STEP 4: Frame the searching procedure for both positive and negative
searching. STEP 5: Execute the Function for both positive and negative
result .
STEP 6: Stop
PROGRAM
SQL>create function fnfact(n
number) return number is
b
nu
m
be
r;
be
gi
n
b:
=1
;
for
i in
1..
n
loo
p
b:=
b*i
;
end
loo
p;
ret
urn
b;
end
;
/
SQL>
Decla
re
n
number
:=&n;
y
number
; begin
y:=fnfa
ct(n);
dbms_output.put_
line(y); end;
/
Function created.
INPUT
Enter value for n: 5
old 2: n
number:=&n;
new 2: n
number:=5;
Page 76
OUTPUT
120
PL/SQL procedure successfully completed.
ALGORITHM
Step 1: Start the program
Step 2: Declare the
variables f and i Step 3:
Initialize f to 1
Step 4: Start the for loop
i in 1..a Step 5: Compute
f=f*i
Step 6: End the loop
Step 7: Return the
factorial value Step 8:
Stop the program
PROGRAM
SQL> create or replace function fact(a number)return
number as 2 i number;
3 f number;
4 begin
5 f:=1;
6 for
i in
1..a
7
loop
8 f:=f*i;
9 end loop;
10 return f;
11 end fact;
12 /
Function created.
OUTPUT
SQL> set
serveroutput on
SQL> begin
2 dbms_output.put_line('the factorial ='||fact(&a));
Page 77
3 end;
4/
Enter value for a:4
old 2: dbms_output.put_line('the factorial ='||
fact(&a)); new 2: dbms_output.put_line('the
factorial ='||fact(4)); the factorial=24
PL/SQL procedure successfully completed.
ALGORITHM
Step 1: Start the program
Step 2: Declare the variables i and f
Step 3: Initialize the values for f and
i as 1 Step 4: Start the while loop 1
<= a
Step
5:
Compute
f=f*i Step 6:
Compute
i=i+1
Step
7: Exit the
loop
Step 8: Return the factorial
value Step 9: Stop the
program
PROGRAM
SQL> create or replace function fact(a number)return
number as 2 i number;
3 f number;
4 begin
5 f:=1;
6 i:=1;
7 while(i<=a)
8 loop
9 f:=f*i;
10 i:=i+1;
11 end loop;
12 return f;
13 end fact;
Page 78
14 /
Function created.
OUTPUT
SQL> set
serveroutput on
SQL> begin
2 dbms_output.put_line('the factorial ='||
fact(&a)); 3 end;
4/
Enter value for a:5
old 2: dbms_output.put_line('the factorial ='||
fact(&a)); new 2: dbms_output.put_line('the
factorial ='||fact(5)); the factorial=120
PL/SQL procedure successfully completed.
PROGRAM
SQL> create table phonebook (phone_no number (6) primary
key,username varchar2(30),doorno varchar2(10),
street varchar2(30),place varchar2(30),pincode
char(6)); Table created.
SQL> insert into phonebook values(20312,'vijay','120/5D','bharathi street','NGO
colony','629002');
1 row created.
SQL> insert into phonebook values(29467,'vasanth','39D4','RK bhavan','sarakkal
vilai','629002'); 1 row created.
SQL> select * from phonebook;
PHONE_NO USERNAME DOORNO STREET PLACE PINCODE
------------------------------- ------------- ---------------- -------------------20312 vijay 120/5D bharathi street NGO colony
629002 29467 vasanth 39D4 RK bhavan sarakkal
vilai 629002
Page 79
Page 80