Sie sind auf Seite 1von 79

c 



p
| | 


A Relational database management system (RDBMS) is a database management


system (DBMS) that is based on the relational model as introduced by E. F. Codd.
Most popular commercial and open source databases currently in use are based on
the relational model.

A short definition of an RDBMS may be a DBMS in which data is stored in the


form of tables and the relationship among the data is also stored in the form of
tables.

Relational databases are powerful because they require few assumptions about how
data is related or how it will be extracted from the database. As a result, the same
database can be viewed in many different ways.

An important feature of relational systems is that a single database can be spread


across several tables. This differs from flat-file databases, in which each database
is self-contained in a single table.

Almost all full-scale database systems are RDBMS's. Small database systems,
however, use other designs that provide less flexibility in posing queries. RDBMS
data is structured in database tables, fields and records. Each RDBMS table
consists of database table rows.

Each database table row consists of one or more database table fields. RDBMS
store the data into collection of tables, which might be related by common fields
(database table columns).

RDBMS also provide relational operators to manipulate the data stored into the
database tables. Most RDBMS use SQL as database query language.
Edgar Codd introduced the relational database model.

Many modern DBMS do not conform to the Codd¶s definition of a RDBMS, but
nonetheless they are still considered to be RDBMS. The most popular RDBMS are
MS SQL Server, DB2, Oracle and MySQL.

    c


p
c  

p
| |   

The Oracle Database (commonly referred to as Oracle RDBMS or simply Oracle)


consists of a relational database management system (RDBMS) produced and
marketed by Oracle Corporation. As of 2008, Oracle had become a major presence
in database computing.

An Oracle  is a collection of data treated as a unit. The purpose of a


database is to store and retrieve related information. A database server is the key to
solving the problems of information management. In general, a server reliably
manages a large amount of data in a multiuser environment so that many users can
concurrently access the same data. All this is accomplished while delivering high
performance. A database server also prevents unauthorized access and provides
efficient solutions for failure recovery.

Oracle Database is the first database designed for enterprise grid computing, the
most flexible and cost effective way to manage information and applications.
Enterprise grid computing creates large pools of industry-standard, modular
storage and servers. With this architecture, each new system can be rapidly
provisioned from the pool of components. There is no need for peak workloads,
because capacity can be easily added or reallocated from the resource pools as
needed.



An Oracle database system ² identified by an alphanumeric system identifier or


SID comprises at least one instance of the application, along with data storage. An
instance ² identified persistently by an instantiation number comprises a set of
operating-system processes and memory-structures that interact with the storage.
Typical processes include PMON (the process monitor) and SMON (the system
monitor).

Users of Oracle databases refer to the server-side memory-structure as the SGA


(System Global Area). The SGA typically holds cache information such as data-
buffers, SQL commands and user information. In addition to storage, the database
consists of online redo logs (which hold transactional history). Processes can in
turn archive the online redo logs into archive logs (offline redo logs), which
provide the basis (if necessary) for data recovery and for some forms of data
replication.

    c


p
c  

p
The Oracle RDBMS stores data logically in the form of tablespaces and physically
in the form of data files. Tablespaces can contain various types of memory
segments; for example, Data Segments, Index Segments etc. Segments in turn
comprise one or more extents. Extents comprise groups of contiguous data blocks.
Data blocks form the basic units of data storage. At the physical level, data-files
comprise one or more data blocks, where the block size can vary between data-
files.

Oracle database management tracks its computer data storage with the help of
information stored in the SYSTEM table space. The SYSTEM tablespace contains
the data dictionary ² and often (by default) indexes and clusters. (A data
dictionary consists of a special collection of tables that contains information about
all user-objects in the database). Since version 8i, the Oracle RDBMS also
supports "locally managed" tablespaces which can store space management
information in bitmaps in their own headers rather than in the SYSTEM tablespace
(as happens with the default "dictionary-managed" tablespaces).

If the Oracle database administrator has instituted Oracle RAC (Real Application
Clusters), then multiple instances, usually on different servers, attach to a central
storage array. This scenario offers numerous advantages, most importantly
performance, scalability and redundancy. However, support becomes more
complex, and many sites do not use RAC. In version 10g, grid computing has
introduced shared resources where an instance can use (for example) CPU
resources from another node (computer) in the grid.

The Oracle DBMS can store and execute stored procedures and functions within
itself. PL/SQL (Oracle Corporation's proprietary procedural extension to SQL), or
the object-oriented language Java can invoke such code objects and/or provide the
programming structures for writing them.

    c


p
c  

p
 



! 
 

1 There is no relationship concept. It is use to establish relationship
concept between two database objects
i.e. tables.
2 It support single user. It support multiuser.
3 It reads data as files internally. It reads tables internally.
4 It requires low software and It requires high software and hardware
hardware requirements. requirements.
5 It is less secure. It is more secure.
6 It is possible to store and retrieve It is possible to store and retrieve large
fewer amounts of data in it. amount of data in it.
7 No keys are used. Keys are used.
8 Normalization concept is not Normalization is present.
present.
9 Used for smaller organizations Large organizations where large
where security is not major amount data is maintain and security is
concern. also important.
10 No data integrity. Data integrity concept is present.
11 It does not support null values. Support null values.
12 Examples: FoxPro Examples: SQL Server
MS-Access Oracle


" 



#!p Both store data in the form of tables.


á!p Both are used for storage.
R!p It is possible to edit record in both DBMS and RDBMS.
o!p It is easy to retrieve data in both.








    c


p
c  

p
$

A data type is a set of data with values having predefined characteristics. Each
language has its own data types. Usually, a limited number of such data types
come built into a language. The language usually specifies the range of values for a
given data type, how the values are processed by the computer, and how they are
stored. Some data types in SQL are: char, number, date etc.
The various Data Types along with their description are shown below:

Data Type Description


char(size) Holds fixed-length character string. Size is specified in
parenthesis. Max 255 bytes.
varchar(size) Holds variable-length character string. Max size is specified in
parenthesis.
number(size) Holds Number value with a max number digits specified in
parenthesis.
Date Holds a Date value.
number(size,d) Holds a Number value with a maximum number of digits of "size"
total, with a maximum number of "d" digits to the right of the
decimal.

















    c
p
c  

p


With CREATE TABLE, a new table can be created. A table can be considered as
a basic structure within which data is stored. It consists of rows and columns. A
row represents a single record while a column represents attributes/fields which
can be thought of as one of the components contributing to make a record. While
creating a table, data types have to be mentioned for each field.


%&CREATE TABLE table_name (column_name1 data_type, column_name2


data_type, ...)

'& create table emp1(e_no number,b_no number,name varchar2(10),dept


varchar2(10),desg varchar2(10));
The above statement creates an empty table (containing no records) named Details
having fields-e_no,b_no,name,dept,desg.

' 

This statement is used to view data from the table.

%&SELECT column_name(s) FROM table_name

'&To select all the column from the table:select * from studentcse;









    c


p
c  

p
(

We might want to retrieve records which satisfy a particular condition. For
example, we want to retrieve Employee names from database table Employee with
salaries above 14000. To do this, we make use of the clause Where. Thus Where
clause is used to specify a selection criterion.

%&SELECT column_name(s) FROM table_name


WHERE condition

'&select * from studentcse where marks>300;


) 

Distinct keyword is used to retrieve values that are distinct or non-repetitive. The
SQL Select retrieves values from database table which may be repetitive. Adding
the word Distinct to Select, we can get rid of this problem.

%&SELECT DISTINCT column_name(s) FROM table_name

'&select distinct * from studentcse;



    c
p
c  

p



Sorting is an important feature of any database. We can arrange data according to
the sequence we need to put them into.



ORDER BY is used to get the result in the sorted manner. Unless Explicitly stated,
the order by clause sorts the result in ascending order.

%&SELECT column_name(s) FROM table_nameORDER BY column_name

'&select * from studentcse order by rollno;








'&select * from studentcse order by rollno desc;




' 

The SQL delete is used to delete rows from a database table.

%&DELETE FROM table_nameWHERE column_name = some_value


    c
p
c  

p

'&delete from studentcse where rollno=106;




'&delete from studentcse where name like '__n%';

'&delete from studentcse where name='Radhika' and marks>300;

  

If the user want to delete a table (the table structure, attributes, and indexes will
also be deleted) Permanently then drop command can be used for the purpose.

%&DROP TABLE <table_name>;

'&drop table studentdet;

    c


p
c  

p

   

Truncate command is used to simply get rid of the data but not the table itself.

%&TRUNCATE TABLE <table_name>;

'&truncate table student1;

' $

Update statement is used to edit or update data in the table. Once there's data in the
table, we might find that there is a need to modify the data. To do so, we can use
the UPDATE command.

%& UPDATE table_name SET column_name = new_value WHERE


column_name = old_value

    c


p
c  

p

'&update studentcse set marks=721 where rollno>205;

'& update studentcse set marks=marks+10 where rollno>205 and name like
'Anish';

    c


p
c  

p


&

&

Once a table is created in the database, there are many occasions where one may
wish to change the structure of the table. ALTER TABLE is basically used to

- Add a column
- Drop a column
- Change a column name
- Change the data type for a column

%&ALTER TABLE table_nameADD column_name datatype

'&alter table studentdet1 add(s_address varchar2(10));

%&ALTER TABLE table_name DROP COLUMN column_name

'&alter table studentdet1 drop column s_address;

%&ALTER TABLE table_nameMODIFY column_name datatype

'& alter table studentdet1 modify(s_name varchar2(20));

    c


p
c  

p

"

Column Alias are used to rename a table¶s columns for the purpose of a particular
query.

%&select column_name alias_name from table_name;

'&""$"$á 

&

This command is used to view all the tables.

%& select * from tab;

    c


p
c  

p


&

This command is used to describe the structure of the the structure of the table.


%&describe tablename;

'&describe emp2;

    c


p
c  

p
"*&

Various functions like as addition, multiplication, division, subtraction are used on


the database.

%& select <arithmetic operation>fieldname from <tablename>;

'&select sal+10 from emp2;

'&select sal/10 from emp2;






    c


p
c  

p
$:

Oracle provides a set of built-in operators-Arithmetic Operators (+, -, *, ),


Comparison Operators ( =, >, <), Logical operators (NOT, AND, OR). These
operators take as input one
or more arguments (operands) and return a result.

The various Operators along with their description are shown below in tabular
form:

Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
LIKE String comparison test
AND Logical And returns TRUE when both the specified conditions are true
OR Logical Or returns TRUE when atleast one of the specified conditions is
true
NOT Logical Not returns TRUE when none one of the specified conditions is
true

'&select * from studentcse where marks>300;





    c


p
c  

p

&


' |+ 



The IN keyword is used to test whether a value(s) is present in the list of values
specified after the keyword IN.

%& SELECT column_name FROM table_name WHERE column_name IN (


value1, value2,...')

'&select * from student where sid in(101,333,336,226,387);



select ename from employee where ecity like 'APS' AND ecode IN(select ecode
from company where desg like 'Manager');



The BETWEEN keyword is used to test whether or not a value is present between
the two values mentioned in the query followed by the keyword BETWEEN.

%& SELECT column_name(s) FROM table_name WHERE column_name


BETWEEN value1 AND value2

'&select * from students where rollno between 111 and 113;




    c


p
c  

p


 

The NOTBETWEEN ... AND operator selects a range of data between two values.
These values can be numbers, text, or dates.

%& select * from <table_name> where <column_name> Not between


<Range1> and <Range2>;

















    c


p
c  

p

 &

 ,&

The Like condition can be used to search for a particular pattern in a column in a
database table.

Syntax: SELECT column_name FROM table_name WHERE column_name LIKE


pattern

'&select * from studentcse where name like 'R%' and marks>300;

select * from studentcse where name like 'A%';

select * from studentcse where name like '__m%';

    c


p
c  

p
  

Dual is a dummy table. Its predefined in ORACLE database.

%&select * from dual;

%& Select sysdate from dual;

    c


p
c  

p
ÿÿ -- -  * |
&

Aggregate functions operate against a collection of values, but return a single


value.

./ 0-. 1/&

It returns the average value of a column.

%&SELECT avg(column) FROM <table_name>;

./ | . ""/&

It returns the lowest value of a column in a table.

%&SELECT min(column) FROM <table_name>

    c


p
c  

p

./ 2. %""/&

It returns the highest value of a column in a table.

%&SELECT max(column) FROM <table_name>;

    c


p
c  

p

ÿÿ  |* |


&

Numeric functions are applied on any table having numeric data.

./ 
. /&

It returns the absolute value of any numeric data. It can also be applied on dual
table.

%&Select abs(value) from <table_name>

./
'.
3/

It is used to find square root of any numeric value.

%&Select sqrt(value) from <table_name>;

    c


p
c  

p

./( &

This numeric function calculates the power of any numeric value.

%&Select power(value,power of value) from <table_name>

.1/ &

This function is used to get a rounded figure of a decimal value.

%& Select round(value,no. of digits desired after decimal ) from


<table_name>;

    c


p
c  

p

.1/&

It shows the specified number of digits after truncating the other digits after
decimal.

%& Select trunc(value,no. of digits desired after decimal) from <table_name>;

.1/ 2 &

It returns a value extracted from a date or an internal value.

%&Select extract (<value_name> from µvalue¶) from <table_name>;

    c


p
c  

p

.1/ &

This function returns the remainder provided two numbers dividend and divisor.

%&Select MOD(dividend,divisor) from <table_name>;

.1/* *&

It returns the immediate smaller integer of given decimal value.

%&Select FLOOR(value) from <table_name>

    c


p
c  

p

.%/ | *&

It returns the immediate greater integer value of the given decimal value.

%&Select CEIL(value) from <table_name>

    c


p
c  

p


ÿÿ
| -* |
&

There are various functions in SQL that can be applied on the string type data.

./
||&

It returns the decimal representation in the database character set of the first
character of string.

%&Select ascii(char) from <table_name>;

./ &

It returns 0 , with all letters uppercase.

%&Select upper(string/column_name) from <table_name>;

    c


p
c  

p

./ ( &

It returns 0 , with all letters lowercase.

%&Select lower(string/column_name) from <table_name>;

./| | &

It returns 0 , with first letter of each word capitalized.

%&Select initcap(string/column_name) from <table_name>;

    c


p
c  

p

.1/  + &

What this function does is that it fills up the extra space in the field with the
padding either from the left or from the right.

%& select lpad(fieldnames) from tablename;

    c


p
c  

p
ÿÿ 0 
| * |
&

(i) 4&

TO_CHAR (number) converts n to a value of VARCHAR2 datatype, using the


optional number format fmt. The value n can be of type NUMBER,
BINARY_FLOAT, or BINARY_DOUBLE, DATE. If you omit fmt, then n is
converted to a VARCHAR2 value exactly long enough to hold its significant
digits.

%&Select to_char(value, format) from <table_name>;

./4 "&

It is used to convert character to number datatype.

%&Select to_number(µvalue¶) from <table_name>;

    c


p
c  

p

./4&

It converts a character field to a date field.

%&Select to_date(µdate¶, µformat¶) from <table_name>;

    c


p
c  

p
-5 
&

GROUP BY... was added to SQL because aggregate functions (like SUM) return
the aggregate of all column values every time they are called, and without the
GROUP BY function it was impossible to find the sum for each individual group
of column values.

%&SELECT column1,<aggregate function>(column2) FROM <table_name>


GROUP BY <column1>;


    c
p
c  

p
6 0| - 
&

HAVING... was added to SQL because the WHERE keyword could not be used
against aggregate functions (like SUM), and without HAVING... it would be
impossible to test for result conditions.

%& SELECT column1,<aggregate function>(column) FROM table GROUP


BY column1 HAVING <aggregate function> condition;


    c
p
c  

p
X|
&

Sometimes we have to select data from two or more tables to make our result
complete. We have to perform a join.

ÿÿ| X| &

The INNER JOIN returns all rows from both tables where there is a match. If there
are rows in Employees that do not have matches in Orders, those rows will not be
listed.

%&SELECT <column1>, <column2>, <column3>FROM <first_table>

INNER JOIN second_table ON <first_table.keyfield> = <second_table.keyfield>;

ÿÿX&

Outer join uses two tables to extract the data .It displays all the rows of first table
or second table or both depending on left outer join ,right outer join or full outer
join.

½p * X| 

    c


p
c  

p
It displays all the rows of the first table of the join.


%& SELECT <cloumn1>, <column2>, <column3> FROM <first_table>
LEFT JOIN second_table ON <first_table.keyfield> =
<second_table.keyfield>;

½p |-6 X| &


It displays all the rows of the second table of the join.


%& SELECT <cloumn1>, <column2>, <column3> FROM
<first_table>RIGHT JOIN second_table ON <first_table.keyfield> =
<second_table.keyfield>;

    c


p
c  

p
½p *  X| 
It displays all the rows of the first table and second table of the join.


%& SELECT <cloumn1>, <column2>, <column3>FROM
<first_table>FULL JOIN second_table ON <first_table.keyfield> =
<second_table.keyfield>;















    c


p
c  

p

 | |  
$

ÿÿÿÿ&It is used to combine the tuples of two different tables.

----|  
&It select the common tuples in both the tables.














    c


p
c  

p

' 
A constraint is a condition or check applicable on field or set of fields.
Consider the following SQL command
Create table employee
(ecode integer NOT NULL,
ename varchar2(9) NOT NULl,
gross decimal);
If you write the keyword NOT NULL after the data type of a column, this means
the column can never be empty.


a.p Unique constraint
b.p Primary key constraint
c.p Default constraint
d.p Check constraint

!p 3 & This constraint ensures that no two rows have same
value in the specified column(s). Example




!p ",&This declares a column as the primary key of the
table. It is similar to default constraint except that only one column can be
specified as primary key. Example

    c


p
c  

p



!p &A default value can be specified for a column using the
DEFAULT clause. When a user does not enter value for the column (having
default value), automatically the defined default value inserted in the field. 



!p , & This constraint limits values that can be inserted into a
column of a table. Examples

    c


p
c  

p
|  2


Indices are created in an existing table to locate rows more quickly and efficiently.
It is possible to create an index on one or more columns of a table, and each index
is given a name. The users cannot see the indexes, they are just used to speed up
queries.

ÿÿ|%&

It creates a simple index on a table. Duplicate values are allowed in simple index.

%&CREATE INDEX <index_name> ON <table_name> (column_name);

'&create index id on studentcse(rollno);

ÿÿ$%&

It is used to vanish the existing index.

%&DROP INDEX index_name ON table_name;

    c


p
c  

p
'&drop index id;

    c


p
c  

p
0| (
&

A view is a virtual table based on the result-set of a SELECT statement. A view


contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database. You can add SQL functions,
WHERE, and JOIN statements to a view and present the data as if the data were
coming from a single table. The database design and structure will NOT be
affected by the functions, where, or join statements in a view.

ÿÿ  0| (&

This command creates the view of a table.

%& Create view <viewname> as select


<columnname1,columname2,«««,columname n>From <table_name>;

'&create view vw as select rollno,name from studentcse where rollno>300;

insert into vw values(&rollno,'&name');

0 

A view could be used from inside a query, a stored procedure, or from inside
another view. By adding functions, joins, etc., to a view, it allows you to present
exactly the data you want to the user.

    c


p
c  

p
| |  7
' 

 7
'  . 7
 ' / is Oracle
Corporation's proprietary procedural extension to the SQL database language, used
in the Oracle database. Some other SQL database management systems offer
similar extensions to the SQL language. PL/SQL's syntax strongly resembles that
of Ada, and just like Ada compilers of the 1980s the PL/SQL runtime system uses
Diana as intermediate representation. The key strength of PL/SQL is its tight
integration with the Oracle database. PL/SQL is one of three languages embedded
in the Oracle Database, the other two being SQL and Java.

6

PL/SQL made its first appearance in Oracle Forms v3. A few years later, it was
included in the Oracle Database server v7 (as database procedures, functions,
packages, triggers and anonymous blocks) followed by Oracle Reports v2.



 7
' programs consist of $, , and " ,.
Each of these is made up of the basic PL/SQL unit which is the block. Blocks take
the general form:

   
-- Declaration block (optional)
 -| 
-- Program proper
 2 | 
-- Exception-handling (optional)
 
/* Sample comment spanning multiple lines... */
"1

variable_name number(P[,S]) := value;

To define a numeric variable, the programmer appends the variable type


   to the name definition. To specify the (optional) precision(P) and the
(optional) scale (S), one can further append these in round brackets, separated by a
comma. ("Precision" in this context refers to the number of digits which the
variable can hold, "scale" refers to the number of digits which can follow the
decimal point.)
    c
p
c  

p
A selection of other datatypes for numeric variables would include:

binary_float, binary_double, dec, decimal, double precision, float, integer,


int, numeric, real, smallint, binary_integer

1

variable_name varchar2(L) := 'Text';

To define a character variable, the programmer normally appends the variable type
VARCHAR2 to the name definition. There follows in brackets the maximum
number of characters which the variable can store.

Other datatypes for character variables include:

varchar, char, long, raw, long raw, nchar, nchar2, clob, blob, bfile

1

variable_name date := '01-Jan-2005';

Oracle provides a number of data types that can store dates (DATE, DATETIME,
TIMESTAMP etc), however DATE is most commonly used.

Programmers define date variables by appending the datatype code "DATE" to a


variable name. The TO_DATE function can be used to convert strings to date
values. The function converts the first quoted string into a date, using as a
definition the second quoted string, for example:

TO_DATE('31-12-2004','dd-mm-yyyy')

"or"

TO_DATE ('31-Dec-2004','dd-mon-yyyy', 'NLS_DATE_LANGUAGE =


American')

To convert the dates to strings one uses the function TO_CHAR (date_string,
format_string).

    c


p
c  

p
 
'  7
' 

#! SQL is Structured Query Language used for DDL,DML.PL/SQL is used for


Cursors and Triggers .

Embeded SQL is used to embed SQL statements in C,Cobol,Pascal,Foxpro like


languages.
Embedded SQL - SQL statements are invoked from a host environment like
C/C++, Java or any other programming languages.

2. SQL is a structured query language used for various operations such as


retrieval,manipulation of data using DML,DDL statements.

PL/SQL is programming language used to write various sql statements


together.Advantage of pl/sql over sql is,you can write many sql statements within a
pl/sql block.One more advantage is subprogramming like procedures and
functions. We can write cursors for fetching number of records at a time. And also
packages and triggers.

3. Both sql and pl/sql are languages used to acess data with in oracle data
base....sql writtens querys by using ddl,dml,dcl etc...where plsql uses
cursors,triggers,procedures etc.. In sql querys process at a time where as in plsql it
done step by step or recoed by record ...

    c


p
c  

p
 7
'  % 1"

The PL/SQL engine, which processes PL/SQL program units, is a special


component of many Oracle products, including the Oracle server.

The procedure (or package) is stored in a database. When an application calls a


procedure stored in the database, Oracle loads the compiled procedure (or package)
into the shared pool in the system global area (SGA), and the PL/SQL and SQL
statement executors work together to process the statements within the procedure.

The following Oracle products contain a PL/SQL engine:

½p Oracle server
½p Oracle Forms (Version 3 and later)
½p SQL*Menu (Version 5 and later)
½p Oracle Reports (Version 2 and later)
½p Oracle Graphics (Version 2 and later)
    c
p
c  

p
You can call a stored procedure from another PL/SQL block, which can be either
an anonymous block or another stored procedure. For example, you can call a
stored procedure from Oracle Forms (Version 3 or later).

Also, you can pass anonymous blocks to Oracle from applications developed with
these tools:

½p Oracle precompilers (including user exits)


½p Oracle Call Interfaces (OCIs)
½p SQL*Plus
½p Server Manager
½p Oracle Enterprise Manager

























    c
p
c  

p
$"





1$


1$


    c
p
c  

p

"

The following code segment shows the IF-THEN-ELSIF construct. The ELSIF and
ELSE parts are optional so it is possible to create simpler IF-THEN or, IF-THEN-
ELSE constructs.

IF x = 1 THEN
sequence_of_statements_1;
ELSIF x = 2 THEN
sequence_of_statements_2;
ELSE
sequence_of_statements_N;
END IF;

The CASE statement simplifies some large IF-THEN-ELSE structures.

CASE
WHEN x = 1 THEN sequence_of_statements_1;
WHEN x = 2 THEN sequence_of_statements_2;
ELSE sequence_of_statements_N;
END CASE;


















    c


p
c  

p
( 7
' ,"""!


    c


p
c  

p

" $&

CASE x
WHEN 1 THEN sequence_of_statements_1;
WHEN 2 THEN sequence_of_statements_2;
ELSE sequence_of_statements_N;
END CASE;

$
As a procedural language by definition, PL/SQL provides several iteration
constructs, including basic LOOP statements, WHILE loops, FOR loops, and
Cursor FOR loops.
"

%&
LOOP
statement1;
statement2;
END LOOP;
Loops can be terminated by using the EXIT keyword, or by raising an exception.


















    c


p
c  

p

( 7
' ,$$!

    c


p
c  

p
(6| $

Syntax:

WHILE LOOP
...do something...
END LOOP;
*$

*$
FOR RecordIndex IN (SELECT person_code FROM people_table)
LOOP
DBMS_OUTPUT.PUT_LINE(RecordIndex.person_code);
END LOOP;

3
"

Syntax:

GOTO record

Where record is place in the PL/SQL to which goto label shift the control of
program.

    c


p
c  

p


ÿ
' .ÿ
' /

It is a part of PL/SQL. Oracle treats a series of operators as a single entity. The
changes made to the table is a two step process, First the changes requested are
done, secondly to make change permanent a commit statement has to be given at
SQL prompt. A roolback statemet given at the SQL prompt can be used to undo a
part of entire transaction.
1.p  |ÿ saves work done.
2.p
0 | ÿ identifies a point in transaction to which you can later roll
back.
3.p   )ÿ restore database to original since the last COMMIT.
4.p

| ÿ Change transaction options like isolation level and
what rollback segment to use.

%&Commit;

Rollback [to[savepoint]savepointname];

Savepoint savepoint_name;














    c


p
c  

p
'&|$$#8o888$o888!
 $          $  
$".$/9$$!

Before execution



After execution

    c


p
c  

p

'&( 7
' , &
#!p |"$á!
á!p $"+á888+#:889,!
R!p         % á89888! |
4;á89888    $9 "     
$!

    c


p
c  

p

PL/SQL uses two types of cursors:  0 and 0. PL/SQL declares a cursor
implicitly for all SQL data manipulation statements, including queries that return
only one row.

%$
The set of rows returned by a query can consist of zero, one, or multiple rows,
depending on how many rows meet your search criteria. When a query returns
multiple rows, one can explicitly declare a cursor to process the rows. Moreover,
one can declare a cursor in the declarative part of any PL/SQL block, subprogram,
or package.
We use three commands to control a cursor: OPEN, FETCH, and CLOSE. First,
we initialize the cursor with the OPEN statement, which identifies the result set.
Then, you can execute FETCH repeatedly until all rows have been retrieved. When
the last row has been processed, we release the cursor with the CLOSE statement.

 0
<* <|
 < * <(
     

  exception FALSE exception exception


 NULL TRUE NULL 0
** 6  NULL TRUE NULL 0
 TRUE TRUE FALSE 1
%  TRUE TRUE FALSE 1
* 6./

 TRUE TRUE FALSE data dependent


* 6  TRUE TRUE FALSE data dependent
 FALSE TRUE TRUE data dependent

    c


p
c  

p
 
 FALSE TRUE TRUE data dependent
 exception FALSE exception exception


When we declare a cursor, we name it and associate it with a specific query using
the syntax:
CURSOR cursor_name [(parameter[, parameter]...)]

[RETURN return_type] IS select_statement;

where return_type must represent a record or a row in a database table, and


parameter stands for the following syntax:
cursor_parameter_name [IN] datatype [{:= | DEFAULT} expression]

$
Opening the cursor executes the query and identifies the result set, which consists
of all rows that meet the query search criteria. For cursors declared using the FOR
UPDATE clause, the OPEN statement also locks those rows.

"
We use the OPEN statement to pass parameters to a cursor. Unless we want to
accept default values, each formal parameter in the cursor declaration must have a
corresponding actual parameter in the OPEN statement.

* 
The FETCH statement retrieves the rows in the result set one at a time. Each fetch
retrieves the current row and then advances the cursor to the next row in the result
set.


The CLOSE statement disables the cursor, and the result set becomes undefined.
Once a cursor is closed, we can reopen it.

    c


p
c  

p
|"$
Oracle implicitly opens a cursor to process each SQL statement not associated with
an explicitly declared cursor. We can refer to the most recent implicit cursor as the
SQL cursor. Although we cannot use the OPEN, FETCH, and CLOSE statements
to control the SQL cursor, we can use cursor attributes to get information about the
most recently executed SQL statement.

Oracle implicitly opens a cursor to process each SQL statement not associated with
an explicitly declared cursor. PL/SQL lets you refer to the most recent implicit
cursor as the SQL cursor. You cannot use the OPEN, FETCH, and CLOSE
statements to control the SQL cursor. But, you can use cursor attributes to get
information about the most recently executed SQL statement

 

1:

#/p <* 


á/p <|
 
R/p < * 
o/p <( !

When appended to the cursor or cursor variable, these attributes return useful
information about the execution of a data manipulation statement. You can use
cursor attributes in procedural statements but not in SQL statements

    c


p
c  

p
|  ||
6  | -

implicit cursor attributes return information about the execution of an insert,


update, delete, or select into statement. the values of the cursor attributes always
refer to the most recently executed sql statement. before oracle opens the sql
cursor, the implicit cursor attributes yield null

the implicit cursor attributes are referred by preceding the implicit cursor attribute
with cursor name.(i.e sql).

' <* 

Until a SQL data manipulation statement is executed, %FOUND yields NULL.


Thereafter, %FOUND yields TRUE if an INSERT, UPDATE, or DELETE
statement affected one or more rows, or a SELECT INTO statement returned one
or more rows. Otherwise, %FOUND yields FALSE.

|    %"$9   <*         
&

DELETE FROM emp WHERE empno = my_empno;


IF SQL%FOUND THEN -- delete succeeded
INSERT INTO new_emp VALUES (my_empno, my_ename, ...);


' <|
 

Oracle closes the SQL cursor automatically after executing its associated SQL
statement. As a result, %ISOPEN always yields FALSE.

' < * 

%NOTFOUND is the logical opposite of %FOUND. %NOTFOUND yields TRUE


if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT
INTO statement returned no rows. Otherwise, %NOTFOUND yields FALSE.

' <( 

%ROWCOUNT yields the number of rows affected by an INSERT, UPDATE, or


DELETE statement, or returned by a SELECT INTO statement. %ROWCOUNT
    c
p
c  

p
yields 0 if an INSERT, UPDATE, or DELETE statement affected no rows, or a
SELECT INTO statement returned no rows.

In the following example, you use %ROWCOUNT to take action if more than ten
rows have been deleted:

DELETE FROM emp WHERE ...


IF SQL%ROWCOUNT > 10 THEN -- more than 10 rows were deleted
...
END IF;

    c


p
c  

p
'&( 7
' ,$", 
3<!

$&
"$%&


"&


"$%&

    c


p
c  

p




    c


p
c  

p
'&( 7
' ,$", 
3<!

$&
"$%&



"&



"$%&

    c


p
c  

p




    c


p
c  

p
'&( 7
' , $"1  
" 7
' ,!

$&
"$%&



"&






    c
p
c  

p

"$%&


    c


p
c  

p
|"$

)1& The types of attribute are

a.p %Type
b.p %Rowtype

!p <$& This attribute is used when declaring variables that refer to data
base column by using type variable; we need the name of columns and table
to which the variable correspond.

%& variable_name <table_name>.<column_name>%type.

!p < $&This attribute is used to declare the single variable for various
columns in a table.

    c


p
c  

p


'#&( 7
' "$1
"$"#889"$ "9
"$. 99 9 96 9 /!

<$&

%

%

    c


p
c  

p
'&( 7
' "$1
"$"#889"$ "9
"$.  9 99 96 9 /!

<(5 &

Before execution



After execution

    c


p
c  

p
$$"%$""

!p & A cursor is declared in the declare section of a PL/SQL


block.
Syntax: cursor <cursor_name> is select <statement>;

!p $& It is use to open cursor explicitly that is by the user.


Syntax: open <cursor_name>;

!p *"""1&
Syntax: fetch <cursor_name> into variable_name;

!p %"$!

!p &
Syntax: close <cursor_name>;


    c
p
c  

p
'&( 7
' ,$9"9="$
$""#8!

< $&

%


%

    c


p
c  

p
'&( 7
' ,$9"9="$
$""#8!

<$&

%

%

    c


p
c  

p
'&$"9$R$"$9
"$.9"9/!

<$&

%


%

    c


p
c  

p
'&$"9$R$"$9
"$.9"9/!

< $&

%


%




    c


p
c  

p
$

%&

For <variable_name> in <cursor_name>

Loop

<SQL statement>;

'&$9"9="$$""#8 
$$!

%




    c


p
c  

p
%





    c
p
c  

p
'&$9"9$R$"$ 
$$!

%


%

    c


p