Sei sulla pagina 1di 34

ORACLE

ORACLE
ORACLE is an RDBMS (Relational Data Base Management System). An
RDBMS is a computer program, which provides the users facility to store an retrieve
data in a manner consistent with a defined Model, called the Relational Model.
The Relational Model has three components. They are:
1. Structural Component to build the model.
Relation (table)
Attributes (columns)
Tuples (Rows)
2. Integrity Component, which, defines the operational rules of the data, model.
3. Manipulation component, which is the component to manipulation the structure.

Data Structure:
The fundamental rule of the Relational model is that is seen as tables. A table
is formally referred to as a relation has the same structure i.e., the same number of
columns and rows. Each column which represents a attributes of the Relation must be
unique.
Oracle being an RDBMS stores the data in tables. Many tables can be created
and related to each other. All the tables from the data base.

Example: Table with 4 columns.


Roll. No.
1
2
3
4

Name
Sachin
Kapil Dev
Ronaldo
Ronaldinho

Course
CCC01
CCC02
CCC03
CCC04

Join_date
01_AUG_96
20_JUL_84
30_JAN_86
8_AUG_88

Data Integrity:
The Relational Model also provides data integrity which means that the data is
accepted based on certain rules and therefore, data is valid example, Oracle will
ensure that roll numbers of the students in the file is unique. Data Integrity is
maintained using a set of rules referred to as Integrity constraints.

Data Manipulation:
In order to create tables and manipulation the data with in tables Oracle
provides the data base access language called SQL stands for Structured Query
Language.

SQL
[Structured Query Language]
Structural Query Language is an English like language which is used to store
and retrieve data from a data base so, it is a data base language to help users to extract
information from a data base easily. This language is non-procedural SQL was
introduced by IBM, SQL was standardized by ANSI and ISO in 1986.

SCT COMPUTER EDUCATION, CHITTOOR

Page 1

ORACLE
Oracle supports distributed data base, which means that many physically
separate data base, can appear to the user as a single data base. The physical distance
becomes transparent to the user. This is also referred to as client server architecture
clients are nodes connected to the data base server. Oracle also has E-mail Interface,
which allows communicate between users and applications.
Oracle is the current version of Oracle the first version was introduced in the
year 1982 and was called Oracle2. To develop applications, Oracle offers the
following tools and features.

TOOLS:
SQL *PLUS
SQL *Report Writer
SQL *Forms
Export / Import utility.

SQL * PLUS:
SQL *PLUS is Oracles implementation of SQL. It is an extension to the
standard SQL. SQL *PLUS comprises of PL / SQL which is procedural. Procedural
means that PL / SQL has all the programming structures of a procedural language like
selection, alteration and decision making.
SQL *PLUS comprises of SQL, SQL *PLUS and PL / SQL.

SQL *FORMS:
SQL *FORMS is a tool for creating forms based applications. It has provision
to create default data entry forms can be used to query a database UPDATE, DELETE
or ADD to a data base.

SQL * REPORT WRITER:


SQL *REPORT WRITER is a menu-driven formatting tool to create simple to
sophisticated reports.

EXPORT / IMPORT UTILITY:


Files may be imported into a data base or exported using this utility.

Features:

DELCARATIVE
TIGGERS
ALERTS
DATA BASE INTEGRITY
PROCEDURES
SECURITY

SCT COMPUTER EDUCATION, CHITTOOR

Page 2

ORACLE
DELCARATIVE:
Declarative, database integrity guarantees that the data in the data base is with
in a predefined set of rules the data can.

TIGGERS:
Tiggers are blocks of PL / SQL code written by users for a specific table. This
code is tiggered when any INSERT, DELETE or UPDATE operation is performed on
that table.

PROCEDURES:
Porcedures are SQL and PL / SQL code compiled and stored in the data base.

ALERTS:
Alerts are information messages that an application specific and generated by
certain transactions.

SECURITY:
Oracle performs record looking when two users are updating the same data.
The row locking is an automatic feature.
The use of the data base is secured by privileges that are granted to the user by
the Data Base Administrator (DBA).

SQL *PLUS:
SQL *PLUS commands are basically divided into three.
1. DDL (Data Definition Language):
It is used to create and remove data base objects.
Ex:- Create, Alter, Drop.
2. DML (Data Manipulation Language):
Ex:-

It is used to manipulate the data in the data base.


Insert, Delete, Update, Select.

3. DCL (Data Control Language):


It is used to control the king of data access to the data bases and also for
transaction control.
Ex:- Revoke, Grant are used for data access control.
ROLLBACK and COMMIT are transaction control commands.
SQL commands are terminated by a semicolon.
SCT COMPUTER EDUCATION, CHITTOOR

Page 3

ORACLE
SQL *PLUS command is used by data base administration to create users
specifying the rights and principles to the users and also monitoring the data base.
SQL *PLUS is used by the application developers.

Creating a table:
In order to create a table the DDL create is used on the columns of the table
along with the data types and the width is to be specified. The names given to the
table and its column must follow certain rules. When a table is created ORACLE put
the table definition into the data dictionary (Meta data).

Rules for creating tables and columns names:


1.
2.
3.
4.
5.
6.
7.
8.

Names can be up to 30 characters.


Names must begin with alphabet.
Names cannot contain quotes.
Names are not case sensitive.
Names can contain characters a to z, 0 to 9, underscore, dollar prompts and #.
Data base names can be up to 8 characters.
Names cannot be reserve words.
The above rules can be bypassed by using double quotes.

Create table syntax: CREATE TABLE <TABLE NAME>


(
FIELDNAME1 FIELDTYPE (WIDTH),

.
.
.
);

DATA TYPES:
DATA TYPE
Number
Number(w)
Number(wad)
Char(w)
Varchar2(w)
Date
Long

CONTENTS
Numbers, a decimal point and a minus sign. Allows 40 digits and a
decimal point.
Number of column of specified size.
Number of column of specified width out of which two is reserved
for decimal points.
Fixed length character data type maximum size is 255 default
1(i.e., minimum).
Variable length character string of width w maximum width is
2000 bytes.
Accepts date, 01-jan-06
Any printable character alphabets, digits, special symbols, blank
spaces. The length can vary from 0 to 2 GB. Only one long column
may be defined for table. It cannot be used in functions,
expressions or in the where clauses.

SCT COMPUTER EDUCATION, CHITTOOR

Page 4

ORACLE
Row(w)
Long
RowId

Binary data in what ever form the coast computer course maximum
size is 255 bytes.
Row binary data in other ways if like the long data.
A value that uniquely identifies a row in ORACLE database it is.
Written by the Pseudo column rowId. Table columns may not be
assigned this type.

To add data to the table:


Syntax:
Insert into <tablename> values (v1,v2,v3,..);
As the fields of name certain constraints can be specified. Constraints are the
rules to control the data in a column. The common constraints include primary key,
not null and check constraints.
Syntax:
Create table <table name> (field_name1 field type(w) primary key,
field_name2 field type(w) not null,
field_name3 field type(w),
check(field_name in (a,b,c))
);

Primary Key:
This is a constraint for the column of a table the primary key constraint
ensures that the column cannot be null and that the values in the column will be
unique.

Not null:
The Not Null constraint ensures that the user always type the data for that
column.

Check:
The Check constraint ensure that when data is entered the data in the column
is limited to specify values like a, b, or c.

To add fields interactively:


Insert into <table name> values ( &name, &rollno, &course,&place);

Note: That the names need not match the column names, the type and order is
important.

SCT COMPUTER EDUCATION, CHITTOOR

Page 5

ORACLE
To add only secific fields:
If only certain data items are to be input then the order and name of the fields
must be typed before the value clauses.
Syntax:
Insert into <table name> (Columns to insert) values (values to insert);
Ex:Insert into <table name> (name, rollno, course) values(RAMA,420,B.Sc);
Interactive Method is:
Insert into <table name> (name, rollno, course) values(&name, &rollno,
&course);

To view the rows in the table:


Viewing the rows in the table is equivalent to querying the table. The
SELECT statement is the most popular statement to query table.
Syntax:
Select * from <table name>;
To view the selected rows,
Select <column name> from <table name>;
Select <column name> from <table name> where <condition>;

To delete rows from a table:


Syntax:
Delete from <table name>;
It will delete all rows in the table.
Delete from <table name> where <condition>;

To update rows in the table:


Syntax:
Update <table name> set <field> = value;
Will update the field with value for all rows unless a condition is specified.
Syntax:
Update <table name> set <field> = value where (field) = value;

Multiple fields update:


Update <table name> set (field1)=value, <field2>=value where (field) = value;
Multiple columns can be updated by specifying all the fields and values
separated by commas.

ROLL BACK, COMMIT AND SAVE POINT:


Roll back, Commit and Save point are considered as transaction control
commands.
SCT COMPUTER EDUCATION, CHITTOOR

Page 6

ORACLE
A transaction is a sequence of SQL statements that ORACLE treats as a single
unit. A set of changes made to a tablusing update, delete or insert are temporary. To
make the changes permanent commit must be issued.
A transaction begins with the execution of the first SQL statement in the
transaction and ends with either roll back statement or the commit statement.
Ex:- Save point a1;
Delete from <table name> where place = TPT;
Save point a2;
Delete from <table name> where place = PLR;
ROLL BACK TO D2;
COMMIT;
Will undo the second delete operation commit will also release the exclusive
row lock.

Note:
The deleted data is stored in special files called Redo log files until COMMIT
statement is executed.

LOCK TABLE:
Lock tables in the following modes:
1. ROWSHARE
2. ROW EXCLUSIVE
3. SHARE UPDATE
4. SHARE
5. SHARE ROW
6. EXCLUSIVE
Only the table owner, DBA or user having ( Update, Delete, Insert, Select or
Alter). Privilege on the table can issue this command. A table can have multiple share
lock but only one exclusive lock. Lock determines how different users can commit or
roll back.
Syntax:
Lock table [user.] table name [, user.] table name] in lock mode MODE [NO
WAIT];
Lock Mode:
Lock mode can be one of the share, exclusive, row share, row exclusive, share
update, share row exclusive.
Nowait:
If table is already locked the call returns instead of querying for the table to be
unlock.

SCT COMPUTER EDUCATION, CHITTOOR

Page 7

ORACLE
Share:
Share allows concurrent queries but this allows update to a table.
Exclusive:
It allows queries on locked tables.
Row Share:
Prevents locking the entire table for exclusive access there by allowing
concurrent access.
Share Update:
Same as row share.
Ex:
Lock table <table name> in Exclusive mode;
Lock table <table name> in exclusive mode Nowait;
The use of first statement will make ORACLE wait if for some reason the
table is not available for locking, another user may lock the table. The second
statement will immediately return to the application if the table lock cannot be
executed.
Implicit commit:
Certain an action will automatically force a command.
Ex:
Execution of any DDL like create, drop, alter other commands like exit, grant,
revoke, connect, disconnect, audit and no audit.
Where:
When we want information about particular field from the data base we use
where clause. The general syntax of select by using where option or caluse is from
<table>.
Syntax:
Select <column names> from <table name> where <condition>;
Where with AND, OR , NOT:
AND:
When we want the information about more than one column from the data
base we can use AND clause in where option as follows:
Select <column name> from <table name> where <conition1> and
<coniditon2>;
OR:
When we want the information about more than one column and also at least
needs any one of the column.

SCT COMPUTER EDUCATION, CHITTOOR

Page 8

ORACLE
Select <column name> from <table name> where <condition1> or
<condition2>;
NOT:
Not is denoted by the symbol !
Select <column name> from <table name> where <condition>;
Ex:
Select <column name> from <table name> where rollno !=1024;

ORDER BY:
It would list customers sorted by descending order or ascending order. When
no order is specified in the statement, the ORACLE sorts in ascending order only.
Ex:
Select * from <table name> orderby <fieldname>;
Select * from <table name> orderby <fieldname> desc;

ALTER:
Alter command is used to add additional columns in to a table on a data base.
Syntax:
Alter <table> <table name> add (column name varchar2(20));
To delete a specific column we use the following syntax:
Alter <table> <table name> drop <column> <column name>;

Renaming Tables:
To rename the tables follow the following syntax.
Syntax:
Rename <old table name> to <new table name>;

Dropping a table:
To destroy the tables in ORACLE we should follow the following syntax:
Drop table <table name>;

DESCRIBE:
To find information about the columns defined in the table use the following
syntax.
Syntax:
Describe <table name>;
This command displays the column names, the data types and the special
attributes connected to the table.

SCT COMPUTER EDUCATION, CHITTOOR

Page 9

ORACLE
Note:
To find out the tables created by the user follow the syntax:
Select * from tab;

Referential Integrity:
It is a property that guaranteed that values from one column depend on values
in another column. This property can be enforced through the referential integrity
rule.
To understand this concept better let us take the example of creating tables to
store student data normally all the data related to students is not stored in a single
table. The data i.e., permanent like the data of birth, address, parents name is stored in
one table referred as the master table. The master table will contain only one record
for every student. The marks table on the other had is the transaction table. It can have
more than one record for every student i.e., every time the student appears for the
exam, records will be added to the marks table.
The marks table will show only data about the examination similarly the fee
details of the student will be stored in another table and since fees may be received
from the student more than one time. This table is also a transaction table. So the
student address file is the master file of students containing only one record for every
student.

Note:
1. The master table or parent table, which contains the linking column, must be
primary key.
2. The linking column in the transaction table or child table references the parent
table. This column in the child table which reference a primary key of parent table
is referred to as a foreign key.

Syntax:
Create table <table name> (R.No. number(5) primary key, field data type);
Create table <table name> (R.No. number(5) references <master table name>,
field data type,.);

On Delete Cascade:
This is referential integrity rule which allows the user to delete rows from the
master and at the same time it will delete the dependent rows in all the child tables
i.e., if row of ROLL_NO2 is deleted from student address file, automatically two
rows will be deleted from the student marks file.
In order to apply this rule, the following syntax is followed while creating the
child table.
Create table STD_MARKS(R_NO Number(4) references STD_ADD on
Delete Cascade, subject varchar2(10), exa,_date date, marks number(3));

SCT COMPUTER EDUCATION, CHITTOOR

Page 10

ORACLE
Table Alias:
Consider the query given below to retrieve data from two tables.
Ex:
Select player.rollno, name, match_date opponent from player, match where
player.rollno = match.rollno;
The query can be coded with an Alias for the table name, making the query
easy to code.
Ex:
Select p.rollno, name, match_date opponent from player p, match m where
p.rollno = m.rollno;
The table player referred by Alias P, the table match is referred by Alias M.

Note:
To clear the screen use cl scr command.

Column Alias:
The columns of the table can be displayed with user specified heading instead
of column names appearing as the heading.
Ex:
Select <column name1> heading1, <column name2> heading 2,.from
<table name>;
The above query will display columns from the table. The first column will
have the heading heading1 and the second column will be display heading2.

Column Format:
The column data can be formatted to suit the requirements of the user.
Ex:
Column <column name> format 99999.99;
Select * from <table name>;
OR
Select <column names> from <table name>;
The column name column will now display with the specified format. It
will allow commas also.
Syntax:
Column <column name> format 99,999.99;

Text:
Column <column name> format a10 trunc;
The column name column is formatted to display only ten characters if a
name is longer than 10 characters it will be truncated in the display.
SCT COMPUTER EDUCATION, CHITTOOR

Page 11

ORACLE
FUNCTIONS
Number Functions:
1. Abs(data): Returns the absolute value of data (i.e., positive value).
Ex: Select abs(-5000) from dual;
2. Ceil(data): Returns the smallest integer greater than or equal to data.
Ex: Select ceil(123.55) from dual;
3. Floor(data): Returns the largest integer less than or equal to data.
Ex: Select floor(123.55) from dual;
4. LN(data): Returns the natural logarithm of data.
5. Log(b,data): Returns the base b logarithm of data.
6. Mod(data,y): Returns the modulus of dividing data by y.
Ex: Select MOD(101,2) from dual;
7. Power(data, y): Returns the data raised to power of y.
Ex: Select POWER(2,4) from dual;
8. Round(data,n): Where n is the number of decimal places to which the data is
rounded.
Ex: Select ROUND(123.55,0),ROUND(123.55,1) from dual;
9. Sqrt(data): Returns the square root of data.

Ex: Select SQRT(64) from dual;


10. TRUNC(data,n): Where n is the number of decimal places for truncation.
Ex: Select TRUNC(123.55,0),TRUNC(123.55,1) from dual;

Other Functions:
1. COS(X): Returns the cosine of x.
2. COSh(X): Returns the hyperbolic cosine of x.
3. SIN(X):

Returns the sine of x.

4. SINh(X): Returns the hyperbolic sine of x.


5. TAN(X): Returns the tangent of x.
6. TANh(X): Returns the hyperbolic tangent of x.

SCT COMPUTER EDUCATION, CHITTOOR

Page 12

ORACLE
Character Functions:
1. Initcap(data):

Will convert the first letter of the string to uppercase.

Syntax: Select INITCAP(VINU) from dual;


2. Length(data):

Will return the length of the string.

Syntax: Select LENGTH(ANU) from dual;


3. SUBSTR(data,x,y): Will extract y characters starting from the xth character of
data.
Syntax: Select SUBSTR(ANUSHA VINODH,5,3,) from dual;
4. INSTR(data,x): Will find the location of string x in the string data.
Syntax: Select INSTR(ANUSHA VINODH, ANU) from dual;
5. INSTR(data,x,s,n): Will find the location of the nth occurrence string x in the
string data starting from position s.
Syntax: Select INSTR(MEENAKSHI VINODH, I, 1,3,) from dual;
6. GREATEST(exp1,exp2,exp3,.): Displays the greatest value from a group of
expressions.
Syntax: Select GREATEST(100,100.9,2000) from dual;
Syntax: Select GREATEST( to_date(20-jan-1995),to_date(20-dec-1997)
from dual;
7. LEAST(exp1,exp2,exp3,.): Displays the least value from a group of
expressions.
Syntax: Select LEAST(100,100.9,2000) from dual;

Aggregate Functions:
The aggregate functions, also known as Group Functions summarize data.
1. AVG( [DISTINCT / ALL ] X): Average value of X.
AVG function can be used on numeric data or character data that contains only
numerics.
Syntax: Select AVG(BASIC) from salary;
2. COUNT: Number of rows in the result.
Syntax: Select COUNT(Basic) from salary;

NOTE: It does not count the null values.


3. MAX([DISTINCT / ALL] X): Maximum value of x.
MAX and MIN functions can be used on any type of data.
Syntax: Select MAX(BASIC) from salary;
SCT COMPUTER EDUCATION, CHITTOOR

Page 13

ORACLE
4. MIN([DISTINCT] / ALL] X): Minimum value of x.
Syntax: Select MIN(BASIC) from salary;
5. SUM([DISTINCT] / ALL] X):

Sum of values of x.

SUM function can be used on numeric data.


Syntax: Select SUM(BASIC) from salary;
6. STDDEV([DISTINCT] / ALL] X): Standard deviation of x.
Syntax: Select STDDEV(BASIC) from salary;
7. VARIANCE([DISTINCT] / ALL] X): Variance of x.
Syntax: Select VARIANCE(BASIC) from salary;

The three different forms of COUNT function is as follows:


1. COUNT( * ): Counts the number of rows in the table or the number of rows in
the group INCLUDING NULL.
2. COUNT( column_name): Counts the number of non-null values in the column.
3. COUNT( DISTINCT column_name): Counts the number of different values in
the column.

Conversion Functions:
To_char :
The to_char function can be used to convert a date or number to a character
string. With this function a date item can be formatted in many ways which must be
enclosed in single quotations. Consider 6-oct-06 as the system date then,
SELECT TO_CHAR(SYS_DATE,MONTH) FROM DUAL;
It will return only the month OCTOBER.
SELECT TO_CHAR(SYS_DATE,DD/MM/YY) FROM DUAL;
It will return [date-month-year] as 06-10-06.
Ex: SELECT * FROM <TABLE NAME> WHERE
TO_CHAR(FIELDNAME,MM=03);
It will return the row, which is having month as MARCH.
To_date(String):
Converts a string into an Oracle date. It will also accept a number instead of a
string, with certain limit.
INSERT INTO SALARY VALUES(1005,4444,100,200,TO_DATE(01-JAN2006, DD-MON-YYYY));

SCT COMPUTER EDUCATION, CHITTOOR

Page 14

ORACLE

Some useful queries using ALTER :


1. To add a new column to an existing table follow the syntax:
ALTER TABLE <TABLE NAME> ADD(<COLUMN NAME> DATATYPE);
2. To change the width of an existing column follow the syntax:
ALTER TABLE <TABLE NAME> MODIFY(COLUMNNAME
DATATYPE(WIDTH);
3. To add more than one column to an existing table follow the syntax:
ALTER TABLE <TABLE NAME> ADD(COLUMNNAME1
DATATYPE(WIDTH), COLUMN NAME2 DATATYPE(WIDTH),.);
4. To add a primary key after the table has been created follow the syntax:
ALTER TABLE <TABLE NAME> ADD PRIMARYKEY(COLUMN NAME);
5. To remove primary key option from the table follow the syntax:
ALTER TABLE <TABLE NAME> DROP PRIMARY KEY;
6. To drop a primary key that has been dependent tables follow the syntax:
ALTER TABLE <TABLE NAME> DROP PRIMARY EY CASCADE;
7. To add a foreign key constraint to an existing column follow the syntax:
ALTER TABLE <TABLE NAME> ADD(FOREIGN KEY (COLUMN NAME)
REFERENCES <LINK TABLE NAME> ON DELETE CASCADE);
8. To drop a foreign key constraint follow the syntax:
ALTER TABLE <TABLE NAME> DROP CONSTRAINT <CONSTRAINT
NAME>;
9. To add a not null constraint follow the syntax:
ALTER TABLE <TABLE NAME> MODIFY COLUMN NAME NOT NULL;
10. To drop a not null constraint follow the syntax:
ALTER TABLE <TABLE NAME> MODIFY COLUMN NAME NULL;

SCT COMPUTER EDUCATION, CHITTOOR

Page 15

ORACLE
SUB-QUERY
A sub-query is a query with in a query i.e., a select statement is used as part of
another SQL statement. The outer statement is called the Parent and the nested query
passes a value to the outer query. The nested query executes first.

Note:
1. The nested query must return a single column.
2. The result can only contain columns from the tables referenced in the outer most
queries.
3. The nested query must return a single row when the standard operator such as =,
>, < is used.
4. The between operator cannot be used with in a sub-query.
5. Sub-queries can also be used in insert, update and delete statements.

Using a sub-query to select data:


In order to list the employees who earn less than the average salary in the
organization a group function AVG must be used to calculate the average salary
however, the group function cannot be used in the where class. In such a case, a subquery may be used.
SELECT *FROM <TABLE NAME> WHERE COLUMN NAME( SELECT
AVG(COLUMN NAME1) FROM <TABLE NAME1>);
Sub-queries are also used to retrieve data in a join operation with a negative
condition.
Ex:
In order to list names of employees who do not work in the marketing
department.
SELECT EMP_NO, EMP_NAME FROM EMPLOYEE WHERE EMP_NO
NOT IN ( SELECT EMP_NO FROM SALARY WHERE DEPT=MKT);

Using a sub-query to insert data:


1. Create table <table name1> as select * from <table name2>;
It is used to insert all the data from one table to another table. I.e., a new table
name <table name1> is created which will be a duplicate of the table name
<tablename2>.
2. Create table <table name1> as (select * from <table name2> where 1>2);
A new table name <table name1> is created which will have the structure of
the table name <table name2>.
3. Insert into <table name1> (select *from <table name2> where <condition>);
Rows from the table <table naem2> where condition is satisfied will be
inserted into the table <table name1>.

Using a sub-query to delete job:


Delete from <table name> where column name in (select <column name1>
from <table name> where query or condition);
SCT COMPUTER EDUCATION, CHITTOOR

Page 16

ORACLE
Using a sub-query to update data:
Update <table name1> set <field>=(select SUM(field name) from <table
name2> where condition;
When using sub-queries with UPDATE, be certain that the sub-query will
return no more than ONE RECORD for each of the Updated records.

PL / SQL
[ PROCEDURAL LANGUAGE / STRUCTURED QUERY LANGUAGE]
There are two version of PL / SQL. One is part of the data base engine. The
other is a separate engine embedded on a number of ORACLE tools. We call them
database PL / SQL and tool PL / SQL, they are very similar. Both use the same
programming constraint syntax and logic mechanisms.

Characters:
When programming in PL / SQL allows the following characters.
1. All upper case and lower case letters.
2. Digits 0 to 9.
3. Symbols opening and closing parenthesis, +, -, * ,/ <, >, !, = etc.,
Some serves as arithmetic operators ( Add, Subtracts, Multiply, Division) and
some serves as relational operators ( = ,!=, > ,<).

Operators:
There are two types of operators using PL / SQL.
1. Arithmetic operators.
2. Relational operators.

1. Arithmetic Operators:
The common Arithmetic Operators used in PL / SQL are :

OPERATOR
+

*
**
/

MEANINGS
Addition
Subtraction
Multiplication
Exponentiation
Division

2. Relational Operators:
The PL / SQL relational operators are as follows:
SCT COMPUTER EDUCATION, CHITTOOR

Page 17

ORACLE
OPERATORS
<>
^>
!=
>
<
=

MEANING
Not equal
Not equal
Not equal
Greater than
Less than
Equals to

Variables:
Variables are names used in PL / SQL to process items of data rules for using
variables are :
1. Variables must start with a letter ranging from A to Z and a to z.
2. One or more letters, numbers and the special characters can optionally follow
variables.
3. Variables must be no longer than 30 characters.
4. There can be no spaces embedded in the variable name.
Ex: Avg., Variable1, Nature_trial.

Data types:
A PL / SQL program is returned to manipulate and display many different
types of data. The data type in PL/SQL are
Varchar2( )
Number( )
Date( )
Boolean( )
Varchar2( ):
This is a variable length used for -numeric data type. It can have a length up
to 32,767 bytes.
Syntax:
Variable name varchar2(maximum length);
Ex: student_name varchar2(10);
The length in the parenthesis must be a positive integer. Using the syntax as follows
may initialize it:
Syntax: s_name varchar2(10):=VINU;
Number data type:
This type of data type can be used to represent all numeric data, the format of
declaration is :
Syntax: numberfield number(length);
Ex: S_number number(10);
Date data type:
This data type is used to store fixed length data values. The format of
declaration is:
Syntax: Datefield field;
Ex: field date 01-02-02;
SCT COMPUTER EDUCATION, CHITTOOR

Page 18

ORACLE
By default Oracle displays dates in the format DD-MM-YYYY;
DD for Date, MM for Month, YY for Year.
Boolean data type:
This data type is a switch that holds the status true or false. The number format
is = if status = true; than do something else do something.
Ex: if a=10; then a=a+10
Do something else exit;
Syntax: if status = true;
Then d statement;
Else statement1;
Ex: if a=10;
Then a=a+10;
Else
Exit;

PL / SQL Components:
1.
2.
3.
4.

The components in PL / SQL are


Exceptions.
Control Structures.
Do Nothing ( Null constraint )
Declare Section.

1. Exceptions:
This is the PL / SQL method of dealing with error conditions. The most common
exceptions in PL/SQL are :
No-data-found
If a select statements attends to retrieve data base on its
conditions, this exception is raised when no rows satisfy the select criteria.
Too many rows this exception detects the existence of more than one row.
Dup-value or Index:
This exception detects an attempt to create an entry in an index whose
key column values already exists.
Value-Error:
This exception indicates that there has been an assignment of operation
where the target field is not long enough.

2. Control Structures:
If-then:I
If the condition evaluates to truth one or more lines of code are
executed. If the condition evaluates to false program control is passed to the
next statement.
Ex: if variable1>10
Then variable2 := variable1+20;
End if;
If-then-else:
This is similar to IF except when the condition evaluate to false one
or more statement following else are executed.
Ex: if variable1>10
SCT COMPUTER EDUCATION, CHITTOOR

Page 19

ORACLE
Then variable2 :=variable1+20;
Else
Variable2:= variable1 * variable1;
End if;
If-then-else-if:
Ex:
If variable1>10
Then variable2 :=variable1+20;
Else
If variable1 between 7 and 8
Else
Variable2:= 2* variable1;
End if;
Looping:
Looping provides the ability to execute a process over and over again
until complete.
Loop-Exit-End loop:
Ex: c:=1
Initialized the loop counter before loop starts.
Loop
keyword starts the loop.
C:=c+1
Increment the loop counter.
If c>100
then testing c for exist condition.
Exit
End loop condition.
End if
to match previous if
End loop
this key word helps to end the loop.
Loop-Exit-When-End loop:
Ex: c:=1
Initialized the loop counter before loop starts.
Loop
keyword starts the loop.
c:=c+1
Incrementing the loop counter.
When c>100
Test for exit condition by examining c.
End loop
end loop key word to end the loop.
While-loop-end loop:
Ex:

c:=1
while c<=100 loop
c:=c+1;
end loop;
For-In-Loop-End Loop:
Ex: for c in 1..3 loop
Insert into <table name> values (still in loop,c);
End loop;

3. DO-NOTHING OR NULL CONSTRAINT:


Ex:
If c>=90 then
Null;
Else
Insert into <table name> values (still <90,c);
SCT COMPUTER EDUCATION, CHITTOOR

Page 20

ORACLE
End if;
The null keyword denotes performing no operations.
Cursors:
PL / SQL uses cursors for management of SQL select statement.
Cursors are memory allocated process these statements some time we
define the cursor manually and other time we led the PL / SQL define the cursor.
Explicit Cursors:
This technique defines a cursors as a part of declare section. The SQL
statement definition must contain only select statement that can be no INSERT,
UPDATE, DELETE keywords used. When using explicit cursors we always got both
components.
1. The cursor is defined in the declare section of PL / SQL block.
2. The cursor is open after the initial begin in the PL / SQL block.
3. The cursor is fetched into one or more variables they must be the fetch as these are
columns in the cursors select list.
4. The close cursor is using.
5. The following points about explicit cursor:
i.
A success or failure of the cursor is determined by testing either percent
found or percent not found. The cursor returns success if it retrieves a
row from the data base based on its selection criteria. This test must be
then report the cursor is closed.
ii.
If a cursor is repeatedly fetched in a loop construct, a running total of the
number of rows retrieved so far can be found in the percent row
counter system variable.
iii.
All cursors must be fetched into one or more variables depending on the
number of columns in the cursor select list.
iv.
The target variables of the cursor must match the columns in the table
being selected in data type.
If a PL / SQL block uses more then one cursor, each cursor must have a unique
name.
Implicit Cursors:
1. There must be an into with each implicit cursor.
2. With Implicit cursor, the variables that receive data with the into key word
must be the same data type as the column in the table.
3. Implicit cursors expect only one row to returned.

Drawbacks of SQL:
1. SQL does not have any procedural capabilities.
2. SQL statements are passed to the Oracle engine one at a time. Each time an SQL
statement is executed, a call is made to the engine resources. This adds to the
traffic on the network, and also causes the show data processing. Especially in a
multi user environment.
3. Which processing an SQL sentence if an error occurs the Oracle engine displays
its own error messages. SQL has no facility for programmed handling of errors
that arise during manipulation of data.
SCT COMPUTER EDUCATION, CHITTOOR

Page 21

ORACLE
PL / SQL:
PL / SQL is a super set of SQL, its acronyms stands for procedural language
for SQL. PL / SQL is a block structured language that enables develops to combine
the power of SQL with procedural statement.

Advantages:
1. PL /SQL is development tool that not only supports SQL data manipulation, but
also provides facilities of conditional checking, branching and looping.
2. PL / SQL sends an entire block of statements to the Oracle engine at one time.
3. The communication between the program block and the Oracle engine reduce the
network traffic and increases the speed of data processing.
4. PL / SQL also permits dealing with errors as required and facilities displaying user
friendly messages when errors encountered.

Structure or Skeleton of PL / SQL statement:


1.
2.
3.
4.

Every PL /SQL block consist or contains the three sections.


Declarative section.
Begin section.
End section.
The begin and end section also consist exception section.

Delcarative Section:
The PL / SQL code block start with a declarative section in which variables
and other Oracle objects can be declared ad if required SQL statements for Data
Manipulation.

Begin Section:
It consists of a set of SQL and PL / SQL statements which describe processes
that have to be applied to the data. Actual data manipulation retrieval, looping and
branching constructs are specified in this section.

End Section:
This marks the end of a PL / SQL block.

Exception Section:
This section deals with handling of errors that arise during execution of the
data manipulation statements which make up the PL /SQL code block errors can arise
due to syntax, logic and validation rule violation.
SCT COMPUTER EDUCATION, CHITTOOR

Page 22

ORACLE
Displaying user message on the screen:
Programming tools require a method through which messages can be
displayed to the user on the VDU screen. In PL / SQL we have DBMS_OUTPUT is
a package that includes a number of procedure and functions that accumulate
information in a buffer so that it can be retrieved later. These functions can also be
used to display messages to the user.

Put_line:
Put a piece of information in the package buffer followed by an end of line
marker.

Lab Work:
1. Write a PL / SQL code block that will accept an account number from the user
and debit an amount of Rs. 3000/- from the account where the account has
minimum balance of 1000/- after the amount is debited.
Create table accounts ( acc_id varchar2(10),
Name varchar2(10),
Balance number(5,2));
Declare accounts_balance number(10,2);
Account_number varchar2(10);
Debit_account number(9):=3000;
Min_bal const numbre(10,2):=1000;
Begin
Account_number := * &account_number;
Select bal * into acc_bal from accounts where acc_id = account_number;
acc_bal := acc_bal_debit_amt;
If acc_bal >= min_bal then
Update accounts set bal = bal_debit_amt where acc_id=acc_no;
End if;
End;
2. Write a PL / SQL block to calculate sum for two variables or two numbers.
Declare
X number(5) :=10;
Y number(5) :=20;
Z number(5);
Begin
X:=X+Y;
Dbms_output.putline(Z);
End;
SCT COMPUTER EDUCATION, CHITTOOR

Page 23

ORACLE
3. Write a PL /SQL program to calculate area of a circle using while loop.
Create table area ( radius, area)
Declare
Pi constant number(4,2) :=3.14;
Radius number(5);
Area number(5);
Begin
Radius :=14;
While radius <=10;
Loop
Area = pi* power( raidus,2);
Insert into area values (radius, area);
Radius := radius+1;
End loop;
End;
4. Write a PL / SQL program to find inverse of given number using for loop.
( for in loop_end_loop = formulae)
Declare
Gnum varchar2(7) := A5675;
Str_length number(2);
Inverse varchar(7);
Begin
Str_length := length(gnum);
For enter in reverse
1.. Str_length
loop
inverse := inverse // substr (gnum,enter,1);
end loop;
dbms_output.putline(The given number is // gnum);
dbms_output.putline(The reverse number is // inverse);
end;
5. Write a PL / SQL program that will accept a stud_number from the user and
update the stud_name column.
Declare
Stud_number number(10);
Begin
Stud_number := &stud_number;
Update stud_name where stud_id :=stud_number;
End;
6. Write a PL / SQL program to simulate the following.

SCT COMPUTER EDUCATION, CHITTOOR

Page 24

ORACLE
If the price of product is less than 5000 then change the price to 5000. The
price change is to recorded in the old price table along with product_no and the date
on which the price was last changed.
Create oldprice table with the following fields ( product_no, date, change,
oldprice)
Delcare
S_price number(10,2);
Begin
Select sellprice into s_price form product_master where p_no= P0001;
If s_price <5000 then
Goto add_old_price;
Else
Dbms_output.putline(current price of P0001 is // s_price);
End if;
<<add_old_price>>
update product_master set sell_price = 5000 where p_no = P0001;
insert into old_price values ( P0001, Sys date, s_price);
dbms_output.putline(the new price of P0001 is 5000);
end;
7. Write a program to perform simple arithmetic operations.
Declare
A number(5) :=100;
B number(5) :=100;
Add numbr(5);
Sub number(5);
D number(5);
M number(5);
Begn
A :=&A;
B := &B;
Add := A+B;
Sub := A-B;
D := A/B;
M := A*B;
Dbms_output.putline(Add);
Dbms_output.putline(Sub);
Dbms_output.putline(D);
Dbms_output.putline(M);
End;
8. Example for explicit cursor.
Create Emp table ( empname,social / security)
SCT COMPUTER EDUCATION, CHITTOOR

Page 25

ORACLE
Declare
F_name varchar2(10);
L_name varchar2(10);
S_secno varchar2(10);
Cursor mycur is
Select f_name, l_name, s_sno from person where pin = pin_in;
Begin
Open mycur;
Fetch mycur into fname, lname, ssecno;
While mycur % found loop
If ssec_no is null then
Insert into emp values(pin.in, Nossno);
Else
Insert into emp_tab values ( pin_in,sysdate);
End if;
Fetch mycur into fname, lname, ssecno;
End loop;
Close mycur;
End;
Example:
Exception
When lo_value then
Declare
Lo_value exceptin;
Qty_hand itemfile.qty_hand % type;
Begin
Select qty_hand into qtyhand from itemfilewhere item code= i201;
If qtyhand < 200 then
Raise lo_value;
End if;
Dbms_output.putline(quantity not enough _ recorder);
End;

Some important queries:


Write the queries using logical operators AND, OR , NOT.
SELECT * FROM STUDENT WHERE PLACE = CHITTOOR AND PLACE =
PLMR;
SELECT *FROM STUDENT WHERE (AGE =19 OR AGE =21) AND ( PLACE
= CTR);
Display the student details whose average is between 75 and 85.
SELECT *FROM STUDENT WHERE AVERAGE >=75 AND AVERAGE<=85;
SELECT *FROM STUDENT WHERE AVERAGE BETWEEN 74 AND 86;
SCT COMPUTER EDUCATION, CHITTOOR

Page 26

ORACLE
Using marks in the student table display total and average.
SELECT NAME, M1+M2+M3 TOTAL, M1+M2+M3/3 AVG FROM
STUDENT;
To display the student details whose average is not in the range 10 to 45.
SELECT *FROM STUDENT WHERE AVG NOT BETWEEN 10 AND 45;
Display the student details whose starting letter is A or V.
SELECT *FROM STUDENT WHERE NAME LIKE A% OR NAME LIKE V
%;
Display the student details whose street in mittoor, goolingspet.
SELECT *FROM STUDENT WHERE STREET IN(MITTOOR,
GOOLINGSPET);
Display the student details whose street are not mtr,ctr.
SELECT *FROM STUDENT WHERE STREET NOT IN(MTR, CTR);

Count(*):
It returns number of rows in the table including duplicates and null values.
SELECT COUNT(*) FROM STUDENT;

Count(exp):
It returns number of rows i.e., unique rows and not null columns.
SELECT COUNT(COURSE) FROM STUDENT;
Display the student details according to the course.
SELECT *FROM STUDENT GROUPBY COURSE;
Display the student details according to group wise where year is III or II.
SELECT *FROM STUDENT GROUPBY COURSE HAVING YEAR= II OR
YEAR= III;

To_char(date field format):


It is used to convert the date data type to character values in the format
specified.
TO_CHAR(DOB, DD/MM/YY);
TO_CHAR(DOB, MONTH DD, YYYY);
SELECT TO_CHAR(DOB, MONTH DD, YYYY), NAME FROM STU;

To_char(number, format):

TO_CHAR(FEES, $99999.99);
SELECT TO_CHAR(FEES, $9999.99),NAME FROM STUDENT;

To_number(character):
SCT COMPUTER EDUCATION, CHITTOOR

Page 27

ORACLE
Converts character value containing a number to a value of number data type.
TO_NUMBER(SUBSTR(EXNO, 3,4))+2;
Here 3 is the starting character and 4 is the total characters to be effected.
SELECT TO_NUMBER(SUBSTR(AP1001,3,4))+2, NAME FROM
STUDENT;
To display the student details according to the day of joining.
SELECT *FROM STUDENT ORDER BY TO_CHAR(DOJ, DD/MM/YY);
To delete the duplicate rows( repeated fields).
DELETE FROM <TN> WHERE ROW_ID NOT IN(SELECT
MAX(ROW_ID) FROM DATA GROUP BY SNO);

DECODE:
SELECT COURSE DECODE(COURSE, B.Sc, VA, GOOD) FROM
STUDENT;
To find out the last day of the month.
SELECT LAST_DAY(SYSDATE) FROM DUAL;
Find the names of sailors who have reserved boat number 103.
SELECT S.SID, S.NAME FROM SAILOR S, RESERVATION R WHERE
S.SID=R.SID AND B.NO=103;
Find the name of sailors who have reserved atleast one boat.
SELECT S.NAME, R.BID FROM SAILORS S, RESERVATION R WHERE
R.BID = S.BID;
Find the name of sailors who have reserved a red boat.
SELECT S.SID, S.NAME FROM SAILOR S, RESERVATION R WHERE
S.SID= R.SID AND BCOLOUR = RED;
Find the names of all Jrs. Who are enrolled in a class taught by IB.Sc
SELECT SNAME FROM STUDENT S ENROLLED E WHERE S.SNO=E.SNO
AND LEVEL =Jr AND CLASS.CNAME=IB.Sc;
To insert time
INSERT INTO <TN> VALUES (<FN1>,<FN2>,TO_DATE(&TIMED,
HH:MI));
SELECT TO_CHAR ( TIME, HH:MI AM) FROM <TN>;
Find the age of the oldest student who is either a history major or is enrolled in a
class taught by Iyear.
SELECT S.NAME FROM STUDENT S WHERE (S.MAJOR= HISTORY) OR
S.NUM IN( SELECT E.SNUM FROM CLASS C, ENROLLED E, FACULTY F
WHERE E.CNAME=C.NAME AND C.FID=F.FID AND F.FNAME= IYEAR);
SCT COMPUTER EDUCATION, CHITTOOR

Page 28

ORACLE

SOME IMPORTANT QUERIES USING SUB-QUERY:


NOTE: Sub-queries must be used in WHERE or HAVING clauses only.
To display the highest marks from the table.
SELECT NAME, MARKS FORM STU WHERE MARKS IN( SELECT
MAX(MARKS) FROM STU);

To select maximum ten salaries.


SELECT SAL FROM ( SELECT SAL FROM EMP ORDER BY SAL DESC)
WHERE ROWNUM<=10;
SELECT SAL FROM EMP WHERE ROWNUM<=10 ORDER BY SAL
DESC;
Select the sales representative whose target greater than sales vice president.
SELECT S.NAME, E.SALES_REP, FROM SALES E, SALES S WHERE
S.TARGET>E.TARGET;
SELECT NAME, SALES_REP, TARGET FROM (SELECT NAME,
SALES_REP, TARGET FROM SALES ORDER BY TARGET DESC) WHRE
SALES_REP.TARGET>VP.TARGET;
SELECT NAME,TARGET FROM SALES WHERE TARGET>(SELECT
TARGET FROM SALES WHERE REP= VPSALES);
Select all distributors name who served by the sales representative VINODH.
SELECT DIST_NAME FROM DIST WHERE SALES_NAME IN( SELECT
SALES_NAME FROM SALES WHERE SALES_NAME = VINODH);
List the employees who do not work in the office managed by ANUSHA
SELECT EMP_NAME FROM EMP WHERE MANAGER NOT IN( SELECT
MANAGER FROM EMP WHERE MANAGER= ANUSHA);
List the sales_rep whose target is greater than the average target.
SELECT SALES_REP FROM SALES WHERE TARGET>(SELECT
AVG(TARGET) FROM SALES);

Predetermined Internal PL/SQL Exceptions:


1. No_data_found:
Raised when select statements returns zero rows.

2. Program_error:
Raised when PL / SQL has an internal problem.

3. Login_denied:
SCT COMPUTER EDUCATION, CHITTOOR

Page 29

ORACLE
Raised when an invalid user or pass word was used to logon to Oracle.

4. Dup_Bal_On_Index:
Raised when an insert or update attempts to create two rows with duplicate
values in columns contained by a unique index.

5. Not_logged_on:
Raised when PL / SQL issues and Oracle call without being logged on to
Oracle.

6. Timeout_on_resource:
Raised when Oracle has been waiting to access a resource beyond the user
defined time out limits.

7. Two_Many_rows:
Raised when a select statements returns more than one row.

8. Value_error:
Raised when the data type or data size is invalid.

9. Others:
Stands for all other exceptions not explicitly mean in the exception handler.

SOME IMPORTANT NUMBER FUNCTIONS IN SQL:


FUNCTION NAME
ABS ( n)
CEIL
FLOOR
MOD ( m,n)
POWER (M,N)
ROUND (N,M)
TRUNC (n,m)
SIGN (n)
SQRT (n)

DESCRIPTION
Absolute value of n
Smallest integer greater
than or equal to n
Largest integer less than or
equal to n
Remainder of m divided
by n
M is raised to nth power
where n is integer
N rounded to m decimal
places
N truncated to m decimal
places
Returns 1 if n<0
1 if n>0
0 if n=0
Square root of n

EXAMPLE
ABS(-9) = 9
CEIL(9.5)=10
FLOOR (10.5) =10
Mod (17,5) = 5
POWER(3,3) = 27
ROUND( 10.586,2)=10.59
TURNC(10.586,2) = 10.58
Sign (-5) = -1
Sign (5) = 1
Sign (0) = 0
SQRT(9) = 3

These functions can be used with column having numeric type. For
example, MOD() function can be written as follows:
SELECT MOD(SALARY, 100) FROM EMP_COMPANY;

CHARACTER FUNCTIONS:
These function are mainly operated on character data. The functions are:
FUNCTION NAME
ASCII ( Char)

DESCRIPTION
ASCII value of first

SCT COMPUTER EDUCATION, CHITTOOR

EXAMPLE
ASCII (ABC) = 65
Page 30

ORACLE
CHR (n)
INITCAP ( char)
INSTR ( char1, char2, n,
m)

INSTR ( abcabdebd,
bd, 1, 1)=5

If m=2 is provided i.e.,


INSTR ( abcabdebd,
bd, 1,2)=8
LENGTH (char)
LOWER (char)
LPAD( char1, n,char2)

LTRIM (char, set)


RPAD (char1, n, char2)
RTRIM (char, set)

character
The character with ASCII
CHR (65) = A
value n
Fist letter of char is
INITCAP ( vinu)= Vinu
capitalized
It gives mth occurrence
of char2 in char1.
Returns a numeric
value
N indicates the place
from where searching
begins.
The first occurrence of
bd in abcabdebd is at
position 5, where
searching begins from 1st
letter.
Since second occurrence
of bd starts from 8
Length of string
Converts all character to
lower case
Char1 left padded to
length n with sequence of
characters in char2. Char2
may be replicated.
Trims the character up to
first character not in set
from left side.
Right pad the char1 to
length with sequence of
character in char2.
Trims the character from
the right side up to last
character not in set

SOUNDEX ( char)

A character value
representing the sound of
word in char

Example:
SUBSTR( char, m, n)

A substring of char
beginning of character m
and n character long.
Produce all letters in upper
case

UPPER ( char)

SCT COMPUTER EDUCATION, CHITTOOR

Length(abc) =3
LOWER( ABC) =abc
LPAD (Nagpur ,4, city)
= city Nagpur
LPAD (Nagpur , 8, city)
= city Nagpur
LTRIM (Nagpur, (n)) =
Nagpur.
RPAD (Nagpur , r, city)
= Nagpur city.
RTRIM (Nagpur, (u,v))=
Nagp. It is trimmed up to a
p since u and v are in the
set.
If you compare the string
son and sun it will
return false. But if you
compare soundex ( son)
= soundex ( sun) then it
will return true since both
are producing same sound.
SUBSTR ( 17-MAY-99,
4,3)= MAY
UPPER (abc) = ABC

Page 31

ORACLE
TRANSLATE ( char,
from_c, to_c)

It translates character set


in from_c to character set
n to_c.

Translate (Mumbai,
mu, ac)= Acmbai;

FUNCTION NAME
ADD_MONTHS (d,n)

DESCRIPTION
It adds n months in date.

LAST_DAY (d)

Date of last day of month


containing d
Number of months
between two dates d1 and
d2
Date of first day of week
named by char equal to or
later.
d with time of day
truncated

EXAMPLE
ADD_MONTHS ( 17MAY-99 ,2) =17-JUL-99
LAST_DAY (17-MAY99) = 31-MAY-99
MONTHS_BETWEEN
( 17-MAY-99, 19-JUL99) = 2
NEXT_DAY ( 20-DEC99 , WED)

DATE FUNCTIONS:

MONTHS_BETWEEN
(d1,d2)
NEXT_DAY (d, char)
TRUNC (d)

FUNCTION NAME
DECODE ( expr,
s1,r1,s2,r2,, default)

DESCRIPTION
If expression expr equals
to s1 it will return r1; if
expr equals to s2 it will
return r2 etc. ifno s1,s2 is
matched default is
returned.

GREATEST(e1,e2,)

It returns the greatest


among e1,e2, All
expressions are converted
to the type of first before
comparison is done.

SCT COMPUTER EDUCATION, CHITTOOR

EXAMPLE
DECODE ( X , A, 50 ,
B, 10 ,80)
If value of X is A, it will
return 50. If it is B it will
return 10, otherwise 80 is
returned. If default is not
written, null is returned.
The type of expr and s1,
s3 should be of same
type.
GREATEST ( 10,20,30)
returns 30

Page 32

ORACLE
LEAST( e1,e2,)

It returns the least of


smallest among e1,e2.
If F is null, it returns
expression E. f can be any
type. The type of E should
be same as left hand side.

NVL ( F,E)

LEAST ( 10,20,30) returns


10

The following chart summarizes the value of four cursor attributes, in


different conditions:
Before Open
After Open
Before first
fetch
After first
fetch
Before middle
fetch
After middle
fetch
Before last
fetch
After last
fetch
Before close
After close

%FOUND
E
N
N

%NOT FOUND
E
N
N

%ISOPEN
F
T
T

%ROWCOUNT
E
D
D

F
E

T
E

T
F

D
E

N : NULL
T : TRUE
F : FALSE
E : Exception INVALID CURSOR
D : Data Dependent 1,2,3 Depends on number of rows fetched.

CURSOR ATTRIBUTES:
ATTRIBUTE
% NOT FOUND

SCT COMPUTER EDUCATION, CHITTOOR

DESCRIPTION
To determine if a row was retrieved. Use
after FETCH.
NOTFOUND is TRUE if a row was not
retrieved.
NOTFOUND is FALSE if a row was
retrieved.
Page 33

ORACLE
%FOUND
%ROW COUND

%ISOPEN

SCT COMPUTER EDUCATION, CHITTOOR

To determine if a row was retrieved. Use


after FETCH.
ROWCOUNT is zero when the cursor is
opened.
ROWCOUNT returns the number of rows
retrieved.
To determine if a cursor is open.
ISOPEN is TRUE if a cursor is open.
ISOPEN is FALSE if a cursor is not open.

Page 34

Potrebbero piacerti anche