Sei sulla pagina 1di 239

PL/SQL

Venkat
Mail: vpichela@csc.com

Copyright  CSC India, 2001. All rights reserved.


SQL Concepts

Copyright  CSC India, 2001. All rights reserved.


Overview of SQL Concepts

• Schema objects
– Tables
– Views
– Sequences
– Synonyms
– Indexes
– Clusters

1-3 Copyright  CSC India, 2001. All rights reserved.


• Integrity Constraints
– Domain Integrity constraints
– Entity Integrity constraints
– Referential Integrity constraints

• Sub queries
– Single row sub queries
– Multi row sub queries
– Correlated sub queries
– Uses of sub queries

1-4 Copyright  CSC India, 2001. All rights reserved.


Joins
• Equi join
• Non Equi join
• Inner join
• Outer join
• Self join

1-5 Copyright  CSC India, 2001. All rights reserved.


Schema Objects

Copyright  CSC India, 2001. All rights reserved.


Schema Objects

Object Description

Table Basic unit of storage; composed of rows


and columns

View Logically represents subsets of data from


one or more tables

Sequence Generates primary key values

Index Improves the performance of some queries

Synonym Alternative name for an object

1-7 Copyright  CSC India, 2001. All rights reserved.


TABLE
• In a RDBMS, the data is logically perceived as
tables.
– Tables are logical data structures that we
assume hold the data that the database
intends to represent.
– Tables are not physical structures.
– Each table has a unique name.
– In general, when tables are defined, the
number of columns remain fixed for the
duration of the table, however, the number of
rows present in the table is bound to vary
– Tables are required to have at least one
column.

1-8 Copyright  CSC India, 2001. All rights reserved.


Oracle Server/ Database

• Oracle Server is an RDBMS


• User can communicate with oracle server
through SQL (Structured Query Language)
• Oracle Database is a collection of data that is
treated as a unit
• Structure of Oracle DB can be viewed as
physical or logical
• Physical DB comprises Data Files, Redo files
or control files

1-9 Copyright  CSC India, 2001. All rights reserved.


Tables in the Oracle Database

• User Tables
– Collection of tables created and
maintained by the user
– Contain user information
• Data Dictionary
– Collection of tables created and
maintained by the Oracle server
– Contain database information

1-10 Copyright  CSC India, 2001. All rights reserved.


Creating Views

Copyright  CSC India, 2001. All rights reserved.


Views
• View is a virtual or Imaginary table created on the base table or
view or synonym.
• View is a stored query.
• Provide an additional level of table security by restricting access to
a predetermined set of rows or columns of a table.
• Views hides the information.
• Simplify statements for the user
• Present the data in a different perspective from that of the base
table
Types of views
1. Simple view  Created based on a single table
2. Complex view  Created based on a Multiple table

1-12 Copyright  CSC India, 2001. All rights reserved.


What Is a View?
EMP Table
EMPNO ENAME JOB
JOB MGR
MGRHIREDATE
HIREDATE SAL COMM DEPTNO
----- --------
------- ---------
--------------
---- --------- ------
----- -----
------------
------
-7839 KING PRESIDENT 17-NOV-81 5000 10
7839
7698 KING
BLAKE MANAGER
PRESIDENT 7839 17-NOV-81
01-MAY-81 2850
5000 30
10
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7782
7566 CLARK
JONES MANAGER
MANAGER 7839 09-JUN-81
02-APR-81 2975
1500 300 20
EMPVU10
10 ViewSALESMAN 7698 28-SEP-81
7654 MARTIN 1250 1400 30
7934
7499 MILLER
ALLEN SALESMAN
CLERK 7698 23-JAN-82
7782 20-FEB-81 1600
1300 300 30
EMPNO ENAME JOB 7698 08-SEP-81
------ 107844
-------- -----------
TURNER SALESMAN 1500 0 30
7566
7900 JONES
JAMES CLERK
MANAGER 7698 02-APR-81
7839 03-DEC-81 950
2975 30
7839 207521
KING WARD
PRESIDENT
SALESMAN 7698 22-FEB-81 1250 500 30
7782 7788
CLARK
7902 FORD
SCOTT MANAGER
ANALYST
ANALYST 7566 09-DEC-82
03-DEC-81 3000
3000 20

7934 207369
MILLER
SMITH
CLERK
CLERK 7902 17-DEC-80 800 20
7876
7788 ADAMS
SCOTT ANALYST
CLERK 7566 12-JAN-83
7788 09-DEC-82 3000
1100 20
20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7369
7934 SMITH
MILLER CLERK
CLERK 7782 17-DEC-80
7902 23-JAN-82 1300
800 10
20
7902 FORD ANALYST 7566 03-DEC-81 3000
20
1-13 7698 BLAKE
Copyright MANAGER
 CSC India, 2001. All 7839 01-MAY-81
rights reserved. 2850
30
Simple Views
and Complex Views
Feature Simple Views Complex Views

Number of tables One One or more

Contain functions No Yes

Contain groups of data No Yes

DML through view Yes Not always

1-14 Copyright  CSC India, 2001. All rights reserved.


Creating a View
• You embed a subquery within the CREATE
VIEW statement.

CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view


[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
• TheREAD
[WITH subquery
ONLY] can contain complex SELECT
syntax.
• The subquery cannot contain an ORDER BY
clause.

1-15 Copyright  CSC India, 2001. All rights reserved.


Creating a View
• Create a view, EMPVU10, that contains
details of employees in department 10.

SQL> CREATE VIEW empvu10


2 AS SELECT empno, ename, job
3 FROM emp
4 WHERE deptno = 10;
View created.

1-16 Copyright  CSC India, 2001. All rights reserved.


Querying a View

SQL*Plus
USER_VIEWS
SELECT *
EMPVU10
FROM empvu10;
SELECT empno, ename, job
FROM emp
WHERE deptno = 10;
7839 KING PRESIDENT
7782 CLARK MANAGER EMP
7934 MILLER CLERK

1-17 Copyright  CSC India, 2001. All rights reserved.


Modifying a View
• Modify the EMPVU10 view by using
CREATE OR REPLACE VIEW clause. Add
an alias for each column name.
SQL> CREATE OR REPLACE VIEW empvu10
2 (employee_number, employee_name, job_title)
3 AS SELECT empno, ename, job
4 FROM emp
5 WHERE deptno = 10;
View created.

• Column aliases in the CREATE VIEW


clause are listed in the same order as the
columns in the subquery.

1-18 Copyright  CSC India, 2001. All rights reserved.


Creating a Complex View
Create a complex view that contains group
functions to display values from two tables.
SQL> CREATE VIEW dept_sum_vu
2 (name, minsal, maxsal, avgsal)
3 AS SELECT d.dname, MIN(e.sal), MAX(e.sal),
4 AVG(e.sal)
5 FROM emp e, dept d
6 WHERE e.deptno = d.deptno
7 GROUP BY d.dname;
View created.

1-19 Copyright  CSC India, 2001. All rights reserved.


Rules for Performing
DML Operations on a View
• You can perform DML operations on
simple views.
• You cannot remove a row if the view
contains the following:
– Group functions
– A GROUP BY clause
– The DISTINCT keyword

1-20 Copyright  CSC India, 2001. All rights reserved.


Rules for Performing
DML Operations on a View
• You cannot modify data in a view if it contains:
– Any of the conditions mentioned in the previous
slide
– Columns defined by expressions
– The ROWNUM pseudocolumn
• You cannot add data if:
– The view contains any of the conditions mentioned
above or in the previous slide
– There are NOT NULL columns in the base tables that
are not selected by the view

1-21 Copyright  CSC India, 2001. All rights reserved.


Using the WITH CHECK OPTION
Clause
• You can ensure that DML on the view stays
within the domain of the view by using the
WITH CHECK OPTION clause.
SQL> CREATE OR REPLACE VIEW empvu20
2 AS SELECT *
3 FROM emp
4 WHERE deptno = 20
5 WITH CHECK OPTION CONSTRAINT empvu20_ck;
View created.

• Any attempt to change the department


number for any row in the view will fail
because it violates the WITH CHECK OPTION
constraint.
1-22 Copyright  CSC India, 2001. All rights reserved.
Denying DML Operations
• You can ensure that no DML operations
occur by adding the WITH READ ONLY
option to your view definition.
SQL> CREATE OR REPLACE VIEW empvu10
2 (employee_number, employee_name, job_title)
3 AS SELECT empno, ename, job
4 FROM emp
5 WHERE deptno = 10
6 WITH READ ONLY;
View created.

• Any attempt to perform a DML on any


row in the view will result in Oracle
Server error.
1-23 Copyright  CSC India, 2001. All rights reserved.
Removing a View

Remove a view without losing data


because a view is based on underlying
tables in the database.
DROP VIEW view_name;

SQL> DROP VIEW empvu10;


View dropped.

1-24 Copyright  CSC India, 2001. All rights reserved.


Summary
• A view is derived from data in other tables
or other views.
• A view provides the following
advantages:
– Restricts database access
– Simplifies queries
– Provides data independence
– Allows multiple views of the same data
– Can be dropped without removing the
underlying data
1-25 Copyright  CSC India, 2001. All rights reserved.
SEQUENCE
The sequence generator provides a Unique sequential
series of numbers.
The sequence generator is especially useful in multi-
user environments for generating unique sequential
numbers without the overhead of disk I/O .
Ex:
Sql> Create sequence token_seq
start with 2
minvalue 1
maxvalue 50
increment by 1
cycle
cache 30;
Sql> Create sequence empno_seq;
Sql>1-26select * from user_sequences;
Copyright  CSC India, 2001. All rights reserved.
Accessing the sequence values.
• CURRVAL - refers the current value of the sequence
• NEXTVAL - refers the next value of the sequence

Sql> select token_seq.currval from dual;

Sql> select token_no.nextval from dual;

Sql> Insert into transactions (accno,trans_amt,token_no)


values(101,50000,token_seq.nextval);
Note:
we can alter the all the seqvence values except the start with
clause.

1-27 Copyright  CSC India, 2001. All rights reserved.


SYNONYMS
• A synonym is an alias for any table, view, materialized view, sequence, procedure,
function, or package.
• synonym is simply an alias, it requires no storage other than its definition in the
data dictionary.
Uses;
• Mask the name and owner of an object
• Provide location transparency for remote objects of a distributed database
• Simplify SQL statements for database users
Types of synonyms
1. Private Synonym – is in the schema of a specific user and accessible
to the specific users
2. Public Synonym – Every user in the database can access
Ex:
Sql> Create synonym emp_syn for emp;
Sql> Create public synonym emp_pub for emp;

1-28 Copyright  CSC India, 2001. All rights reserved.


INDEXES
Indexes speed the SQL statements execution
Indexes are optional structures associated with tables and clusters.
Oracle automatically maintains and uses indexes once they are created.
Indexes improves retrieval performance but slowdowns the performance of
updates , deletes , and inserts.
• Indexes can be unique or nonunique.
• Unique indexes guarantee that no two rows of a table have duplicate
values in the key column .
– Unique index will be created automatically when we define
PRIMARY KEY or UNIQUE constraint .

1-29 Copyright  CSC India, 2001. All rights reserved.


Types of INDEXES

• Simple Index
• Unique Index
• Bitmap Index

Sql> Create index empno_ind on emp (empno);


Sql> Create Unique index empno_unique on emp(empno);
• A composite index (also called a concatenated index) is an index that
you create on multiple columns in a table.
Sql> Create index comp_ind on emp(empno,ename);
• Composite index can define on maximum on 32 columns
• Bitmap index can define on maximum on 30 columns

1-30 Copyright  CSC India, 2001. All rights reserved.


A function-based index computes the value of the function or
expression and stores it in the index. You can create a function-
based index as either a B-tree or a bitmap index.

Sql> CREATE INDEX uppercase_idx ON emp UPPER(ename));

Sql> SELECT * FROM employees WHERE UPPER(ename) =


‘SMITH';

Sql>CREATE BITMAP INDEX BIT_IND ON EMP(COMM);

If the number of different key values is small, then bitmap indexes


are very space efficient.

1-31 Copyright  CSC India, 2001. All rights reserved.


Clusters
•A cluster is a group of tables that share the same data blocks because
they share common columns and are often used together.
•Oracle physically stores all rows for group of clustered tables in the same
data blocks.
•Disk I/O is reduced for joins of clustered tables.
•Access time improves for joins of clustered tables.

SQL>CREATE CLUSTER CC(DNO NUMBER(4));

SQL> CREATE INDEX CC_IND ON CLUSTER CC compute statistics;

SQL>CREATE TABLE EMP1(EMPNO NUMBER,ENAME VARCHAR2(15),SAL


NUMBER,DEPTNO NUMBER(4)) CLUSTER CC(DEPTNO);

SQL>CREATE TABLE DEPT1 (DEPTNO NUMBER(4),DNAME VARCHAR2(20),LOC


VARCHAR2(20)) CLUSTER CC(DEPTNO);

SQL> INSERT INTO EMP1(SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP);


SQL>INSERT INTO DEPT1(SELECT * FROM DEPT);

1-32 Copyright  CSC India, 2001. All rights reserved.


Clustered Table Data

1-33 Copyright  CSC India, 2001. All rights reserved.


Including Constraints

Copyright  CSC India, 2001. All rights reserved.


What Are Constraints?
• Constraints enforce rules at the table level.
• Constraints prevent the deletion of a table
if there are dependencies.
• The following constraint types are valid in
Oracle:
– NOT NULL
– UNIQUE
– PRIMARY KEY
– FOREIGN KEY
– CHECK
1-35 Copyright  CSC India, 2001. All rights reserved.
Constraint Guidelines
• Name a constraint or the Oracle Server will
generate a name by using the SYS_Cn
format.
• Create a constraint:
– At the same time as the table is created
– After the table has been created
• Define a constraint at the column or table
level.
• View a constraint in the data dictionary.
1-36 Copyright  CSC India, 2001. All rights reserved.
Defining Constraints
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);

CREATE TABLE emp(


empno NUMBER(4),
ename VARCHAR2(10),
...
deptno NUMBER(7,2) NOT NULL,
CONSTRAINT emp_empno_pk
PRIMARY KEY (EMPNO));

1-37 Copyright  CSC India, 2001. All rights reserved.


Defining Constraints

• Column constraint level


column [CONSTRAINT constraint_name] constraint_type,

• Table constraint level


column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),

1-38 Copyright  CSC India, 2001. All rights reserved.


The NOT NULL Constraint
Ensures that null values are not permitted
for the column
EMP
EMPNO ENAME JOB ... COMM DEPTNO

7839 KING PRESIDENT 10


7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...

NOT NULL constraint Absence of NOT NULL NOT NULL constraint


(no row can contain constraint
a null value for (any row can contain
this column) null for this column)

1-39 Copyright  CSC India, 2001. All rights reserved.


The NOT NULL Constraint
Defined at the column level
SQL> CREATE TABLE emp(
2 empno NUMBER(4),
3 ename VARCHAR2(10) NOT NULL,
4 job VARCHAR2(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL);

1-40 Copyright  CSC India, 2001. All rights reserved.


The UNIQUE Key Constraint
UNIQUE key constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Insert into Not allowed


50 SALES DETROIT (DNAME-SALES
already exists)
60 BOSTON Allowed

1-41 Copyright  CSC India, 2001. All rights reserved.


The UNIQUE Key Constraint
– Maintains the Uniqueness in the values for the
columns on which it is defined.
– Allows the NULL values.

SQL> CREATE TABLE dept(


2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE(dname));

1-42 Copyright  CSC India, 2001. All rights reserved.


PRIMARY KEY
– Combination of UNIQUE and NOT NULL
– No two rows can have the same values
– No single row can have the NULL value
– Table can have only one primary key column

1-43 Copyright  CSC India, 2001. All rights reserved.


The PRIMARY KEY Constraint
PRIMARY KEY
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Insert into Not allowed


20 MARKETING DALLAS (DEPTNO-20 already
exists)
FINANCE NEW YORK Not allowed
(DEPTNO is null)

1-44 Copyright  CSC India, 2001. All rights reserved.


The PRIMARY KEY Constraint
Defined at either the table level or the column
level
SQL> CREATE TABLE dept(
2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE (dname),
6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));

1-45 Copyright  CSC India, 2001. All rights reserved.


FOREIGN KEY
– Used to establish Master Detail relationship
between the tables.
– requires values in one table to match values in
another table.
– The table which contains primary key is called
Master table.
– The table which contains foreign key is called
Detail table.
– Before defining the foreign key in the Detail
table primary key should be defined in the
Master table.

1-46 Copyright  CSC India, 2001. All rights reserved.


The FOREIGN KEY Constraint
DEPT
PRIMARY DEPTNO DNAME LOC
KEY ------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
...
EMP
EMPNO ENAME JOB ... COMM DEPTNO FOREIGN
KEY
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
...
Not allowed
(DEPTNO 9
Insert into does not exist
in the DEPT
7571 FORD MANAGER ... 200 9 table)
7571 FORD MANAGER ... 200 20 Allowed

1-47 Copyright  CSC India, 2001. All rights reserved.


The FOREIGN KEY Constraint
Defined at either the table level or the
column level
SQL> CREATE TABLE emp(
2 empno NUMBER(4),
3 ename VARCHAR2(10) NOT NULL,
4 job VARCHAR2(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL,
10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno)
11 REFERENCES dept (deptno));

1-48 Copyright  CSC India, 2001. All rights reserved.


FOREIGN KEY Constraint
Keywords
• FOREIGN KEY
Defines the column in the child table at
the table constraint level
• REFERENCES
Identifies the table and column in the parent
table
• ON DELETE CASCADE
Allows deletion in the parent table and deletion
of the dependent rows in the child table

1-49 Copyright  CSC India, 2001. All rights reserved.


The CHECK Constraint
• Defines a condition that each row must satisfy
– To satisfy the constraint, each row in the
table must make the condition either TRUE
or unknown (due to a null).
Expressions that are not allowed:
– References to CURRVAL, NEXTVAL, LEVEL, and
ROWNUM pseudo columns
– Calls to SYSDATE, UID, USER, and USERENV
functions
– Queries that refer to other values in other rows
..., deptno NUMBER(2),
CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...

1-50 Copyright  CSC India, 2001. All rights reserved.


Adding a Constraint

ALTER TABLE table


ADD [CONSTRAINT constraint] type (column);

• Add or drop, but not modify, a


constraint
• Enable or disable constraints
• Add a NOT NULL constraint by using
the MODIFY clause

1-51 Copyright  CSC India, 2001. All rights reserved.


Adding a Constraint
Add a FOREIGN KEY constraint to the
EMP table indicating that a manager must
already exist as a valid employee in the
EMP table.
SQL> ALTER TABLE emp
2 ADD CONSTRAINT emp_mgr_fk
3 FOREIGN KEY(mgr) REFERENCES emp(empno);
Table altered.

1-52 Copyright  CSC India, 2001. All rights reserved.


Dropping a Constraint
• Remove the manager constraint from
the EMP table.
SQL> ALTER TABLE emp
2 DROP CONSTRAINT emp_mgr_fk;
Table altered.

• Remove the PRIMARY KEY constraint


on the DEPT table and drop the
associated FOREIGN KEY constraint on
the EMP.DEPTNO column.
SQL> ALTER TABLE dept
2 DROP PRIMARY KEY CASCADE;
Table altered.

1-53 Copyright  CSC India, 2001. All rights reserved.


Disabling Constraints
• Execute the DISABLE clause of the
ALTER TABLE statement to deactivate
an integrity constraint.
• Apply the CASCADE option to disable
dependent integrity constraints.
SQL> ALTER TABLE emp
2 DISABLE CONSTRAINT emp_empno_pk CASCADE;
Table altered.

1-54 Copyright  CSC India, 2001. All rights reserved.


Enabling Constraints
• Activate an integrity constraint currently
disabled in the table definition by using
the ENABLE clause.
SQL> ALTER TABLE emp
2 ENABLE CONSTRAINT emp_empno_pk;
Table altered.

• A UNIQUE or PRIMARY KEY index is


automatically created if you enable a
UNIQUE key or PRIMARY KEY
constraint.

1-55 Copyright  CSC India, 2001. All rights reserved.


Manipulating Data

Copyright  CSC India, 2001. All rights reserved.


Data Manipulation Language

• A DML statement is executed when you:


– Add new rows to a table
– Modify existing rows in a table
– Remove existing rows from a table
• A transaction consists of a collection of
DML statements that form a logical unit
of work.

1-57 Copyright  CSC India, 2001. All rights reserved.


Database Transactions

Consist of one of the following


statements:
• DML statements that make up one
consistent change to the data
• One DDL statement
• One DCL statement

1-58 Copyright  CSC India, 2001. All rights reserved.


Database Transactions

• Begin when the first executable SQL


statement is executed
• End with one of the following events:
– COMMIT or ROLLBACK is issued
– DDL or DCL statement executes
(automatic commit)
– User exits
– System crashes

1-59 Copyright  CSC India, 2001. All rights reserved.


Advantages of COMMIT
and ROLLBACK Statements
• Ensure data consistency
• Preview data changes before making
changes permanent

1-60 Copyright  CSC India, 2001. All rights reserved.


Controlling Transactions
Transaction

INSERT UPDATE INSERT DELETE

COMMIT Savepoint A Savepoint B

ROLLBACK to Savepoint B

ROLLBACK to Savepoint A

ROLLBACK
1-61 Copyright  CSC India, 2001. All rights reserved.
100 SMITH 20000
101 ALLEN 25000 Commit
102 JAMES 20000
103 MILLER 30000 Savepoint A
105 BLAKE 35000
106 JONES 20000 Savepoint B
107 CLARK 25000
108 KING 40000

SQL>Rollback;
SQL>Rollback to A;

1-62 Copyright  CSC India, 2001. All rights reserved.


Implicit Transaction Processing

• An automatic commit occurs under the


following circumstances:
– DDL statement is issued
- Normal exit from SQL*Plus, without
explicitly issuing COMMIT or
ROLLBACK
• An automatic rollback occurs under an
abnormal termination of SQL*Plus or a
system failure.

1-63 Copyright  CSC India, 2001. All rights reserved.


State of the Data Before
COMMIT or ROLLBACK
• The previous state of the data can be
recovered.
• The current user can review the results of
the DML operations by using the SELECT
statement.
• Other users cannot view the results of the
DML statements by the current user.
• The affected rows are locked; other users
cannot change the data within the affected
rows.
1-64 Copyright  CSC India, 2001. All rights reserved.
State of the Data After COMMIT

• Data changes are made permanent in the


database.
• The previous state of the data is
permanently lost.
• All users can view the results.
• Locks on the affected rows are released;
those rows are available for other users to
manipulate.
• All savepoints are erased.
1-65 Copyright  CSC India, 2001. All rights reserved.
State of the Data After ROLLBACK
Discard all pending changes by using the
ROLLBACK statement.
• Data changes are undone.
• Previous state of the data is restored.
• Locks on the affected rows are released.

SQL> DELETE FROM employee;


14 rows deleted.
SQL> ROLLBACK;
Rollback complete.

1-66 Copyright  CSC India, 2001. All rights reserved.


Rolling Back Changes
to a Marker
• Create a marker in a current transaction
by using the SAVEPOINT statement.
• Roll back to that marker by using the
ROLLBACK TO SAVEPOINT statement.

SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.

1-67 Copyright  CSC India, 2001. All rights reserved.


Read Consistency
• Read consistency guarantees a
consistent view of the data at all times.
• Changes made by one user do not
conflict with changes made by another
user.
• Read consistency ensures that on the
same data:
– Readers do not wait for writers
– Writers do not wait for readers

1-68 Copyright  CSC India, 2001. All rights reserved.


Implementation of Read
Consistency
UPDATE emp Data
SET sal = 2000 blocks
WHERE ename =
'SCOTT';
Rollback
segments
User A
changed
SELECT * and
FROM emp; Read unchanged
consistent data
image before
change
“old” data
User B

1-69 Copyright  CSC India, 2001. All rights reserved.


Summary

Statement Description

INSERT Adds a new row to the table

UPDATE Modifies existing rows in the table

DELETE Removes existing rows from the table

COMMIT Makes all pending changes permanent

SAVEPOINT Allows a rollback to the savepoint marker

ROLLBACK Discards all pending data changes

1-70 Copyright  CSC India, 2001. All rights reserved.


DECODE Function

Facilitates conditional inquiries by doing


the work of a CASE or IF-THEN-ELSE
statement
DECODE (col /expression, search1, result1
[, search2, result2,...,]
[, default])

1-71 Copyright  CSC India, 2001. All rights reserved.


Using the DECODE Function

SQL> SELECT job, sal,


2 DECODE(job, 'ANALYST', SAL*1.1,
3 'CLERK', SAL*1.15,
4 'MANAGER', SAL*1.20,
5 SAL)
6 REVISED_SALARY
7 FROM emp;

JOB SAL REVISED_SALARY


--------- --------- --------------
PRESIDENT 5000 5000
MANAGER 2850 3420
MANAGER 2450 2940
...
14 rows selected.

1-72 Copyright  CSC India, 2001. All rights reserved.


Using the DECODE Function
Display the applicable tax rate for each
employee in department 30.
SQL> SELECT ename, sal,
2 DECODE(TRUNC(sal/1000, 0),
3 0, 0.00,
4 1, 0.09,
5 2, 0.20,
6 3, 0.30,
7 4, 0.40,
8 5, 0.42,
9 6, 0.44,
10 0.45) TAX_RATE
11 FROM emp
12 WHERE deptno = 30;

1-73 Copyright  CSC India, 2001. All rights reserved.


Displaying Data
from Multiple Tables

Copyright  CSC India, 2001. All rights reserved.


Obtaining Data from Multiple Tables
EMP DEPT
EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC
------ ----- ... ------ ------ ---------- --------
7839 KING ... 10 10 ACCOUNTING NEW YORK
7698 BLAKE ... 30 20 RESEARCH DALLAS
... 30 SALES CHICAGO
7934 MILLER ... 10 40 OPERATIONS BOSTON

EMPNO DEPTNO LOC


----- ------- --------
7839 10 NEW YORK
7698 30 CHICAGO
7782 10 NEW YORK
7566 20 DALLAS
7654 30 CHICAGO
7499 30 CHICAGO
...
14 rows selected.

1-75 Copyright  CSC India, 2001. All rights reserved.


What Is a Join?
Use a join to query data from more than one
table.

SELECT table1.column, table2.column


FROM table1, table2
WHERE table1.column1 = table2.column2;

• Write the join condition in the WHERE clause.


• Prefix the column name with the table name
when the same column name appears in more
than one table.

1-76 Copyright  CSC India, 2001. All rights reserved.


Cartesian Product

• A Cartesian product is formed when:


– A join condition is omitted
– A join condition is invalid
– All rows in the first table are joined to
all rows in the second table
• To avoid a Cartesian product, always
include a valid join condition in a
WHERE clause.

1-77 Copyright  CSC India, 2001. All rights reserved.


Generating a Cartesian Product
EMP (14 rows) DEPT (4 rows)
EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC
------ ----- ... ------ ------ ---------- --------
7839 KING ... 10 10 ACCOUNTING NEW YORK
7698 BLAKE ... 30 20 RESEARCH DALLAS
... 30 SALES CHICAGO
7934 MILLER ... 10 40 OPERATIONS BOSTON

ENAME DNAME
------ ----------
KING ACCOUNTING
“Cartesian BLAKE ACCOUNTING
product: ...
KING RESEARCH
14*4=56 rows” BLAKE RESEARCH
...
56 rows selected.

1-78 Copyright  CSC India, 2001. All rights reserved.


Types of Joins

Equijoin Non-equijoin Outer join Self join

1-79 Copyright  CSC India, 2001. All rights reserved.


What Is an Equijoin?
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
------ ------- ------- ------- ---------- --------
7839 KING 10 10 ACCOUNTING NEW YORK
7698 BLAKE 30 30 SALES CHICAGO
7782 CLARK 10 10 ACCOUNTING NEW YORK
7566 JONES 20 20 RESEARCH DALLAS
7654 MARTIN 30 30 SALES CHICAGO
7499 ALLEN 30 30 SALES CHICAGO
7844 TURNER 30 30 SALES CHICAGO
7900 JAMES 30 30 SALES CHICAGO
7521 WARD 30 30 SALES CHICAGO
7902 FORD 20 20 RESEARCH DALLAS
7369 SMITH 20 20 RESEARCH DALLAS
... ...
14 rows selected. 14 rows selected.

Foreign key Primary key


1-80 Copyright  CSC India, 2001. All rights reserved.
Retrieving Records
with Equijoins
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno=dept.deptno;

EMPNO ENAME DEPTNO DEPTNO LOC


----- ------ ------ ------ ---------
7839 KING 10 10 NEW YORK
7698 BLAKE 30 30 CHICAGO
7782 CLARK 10 10 NEW YORK
7566 JONES 20 20 DALLAS
...
14 rows selected.

1-81 Copyright  CSC India, 2001. All rights reserved.


Qualifying Ambiguous
Column Names
• Use table prefixes to qualify column
names that are in multiple tables.
• Improve performance by using table
prefixes.
• Distinguish columns that have identical
names but reside in different tables by
using column aliases.

1-82 Copyright  CSC India, 2001. All rights reserved.


Using Table Aliases
Simplify queries by using table aliases.
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno =dept.deptno;

SQL> SELECT e.empno, e.ename, e.deptno,


2 d.deptno, d.loc
3 FROM emp e, dept d
4 WHERE e.deptno =d.deptno;

1-83 Copyright  CSC India, 2001. All rights reserved.


Joining More Than Two Tables
CUSTOMER ORD
NAME CUSTID CUSTID ORDID
----------- ------ ------- -------
JOCKSPORTS 100 101 610
TKB SPORT SHOP 101 102 611
VOLLYRITE 102 104 612
JUST TENNIS 103 106 601
K+T SPORTS 105 102 602 ITEM
SHAPE UP 106 106 604
ORDID ITEMID
WOMENS SPORTS 107 106 605
------ -------
... ... ...
610 3
9 rows selected. 21 rows selected.
611 1
612 1
601 1
602 1
...
64 rows selected.

1-84 Copyright  CSC India, 2001. All rights reserved.


Non-Equijoins
EMP SALGRADE
EMPNO ENAME SAL GRADE LOSAL HISAL
------ ------- ------ ----- ----- ------
7839 KING 5000 1 700 1200
7698 BLAKE 2850 2 1201 1400
7782 CLARK 2450 3 1401 2000
7566 JONES 2975 4 2001 3000
7654 MARTIN 1250 5 3001 9999
7499 ALLEN 1600
7844 TURNER 1500
7900 JAMES 950
... “salary in the EMP
14 rows selected. table is between
low salary and high
salary in the SALGRADE
table”

1-85 Copyright  CSC India, 2001. All rights reserved.


Retrieving Records
with Non-Equijoins
SQL> SELECT e.ename, e.sal, s.grade
2 FROM emp e, salgrade s
3 WHERE e.sal
4 BETWEEN s.losal AND s.hisal;

ENAME SAL GRADE


---------- --------- ---------
JAMES 950 1
SMITH 800 1
ADAMS 1100 1
...
14 rows selected.

1-86 Copyright  CSC India, 2001. All rights reserved.


Outer Joins
EMP DEPT
ENAME DEPTNO DEPTNO DNAME
----- ------ ------ ----------
KING 10 10 ACCOUNTING
BLAKE 30 30 SALES
CLARK 10 10 ACCOUNTING
JONES 20 20 RESEARCH
... ...
40 OPERATIONS

No employee in the
OPERATIONS department

1-87 Copyright  CSC India, 2001. All rights reserved.


Outer Joins
• You use an outer join to also see rows
that do not usually meet the join
condition.
• Outer join operator is the plus sign (+).
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) = table2.column;

SELECT table1.column, table2.column


FROM table1, table2
WHERE table1.column = table2.column(+);

1-88 Copyright  CSC India, 2001. All rights reserved.


Joining a Table to Itself
SQL> SELECT worker.ename||' works for '||manager.ename
2 FROM emp worker, emp manager
3 WHERE worker.mgr = manager.empno;

WORKER.ENAME||'WORKSFOR'||MANAG
-------------------------------
BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.

1-89 Copyright  CSC India, 2001. All rights reserved.


Summary

SELECT table1.column, table2.column


FROM table1, table2
WHERE table1.column1 = table2.column2;

Equijoin Non-equijoin Outer join Self join

1-90 Copyright  CSC India, 2001. All rights reserved.


Practice Overview

• Joining tables using an equijoin


• Performing outer and self joins
• Adding conditions

1-91 Copyright  CSC India, 2001. All rights reserved.


Subqueries

Copyright  CSC India, 2001. All rights reserved.


Using a Subquery
to Solve a Problem
“Who has a salary greater than Jones’?”

Main Query

“Which employees have a salary greater


? than Jones’ salary?”

Subquery

?
“What is Jones’ salary?”

1-93 Copyright  CSC India, 2001. All rights reserved.


Subqueries
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

• The subquery (inner query) executes once


before the main query.
• The result of the subquery is used by the main
query (outer query).

1-94 Copyright  CSC India, 2001. All rights reserved.


Using a Subquery
SQL> SELECT ename
2 FROM emp 2975
3 WHERE sal >
4 (SELECT sal
5 FROM emp
6 WHERE empno=7566);

ENAME
----------
KING
FORD
SCOTT

1-95 Copyright  CSC India, 2001. All rights reserved.


Guidelines for Using Subqueries
• Enclose subqueries in parentheses.
• Place subqueries on the right side of
the comparison operator.
• Do not add an ORDER BY clause to a
subquery.
• Use single-row operators with single-
row subqueries.
• Use multiple-row operators with
multiple-row subqueries.

1-96 Copyright  CSC India, 2001. All rights reserved.


Types of Subqueries
• Single-row subquery
Main query
returns
Subquery CLERK

• Multiple-row subquery
Main query
returns CLERK
Subquery
MANAGER
• Multiple-column subquery
Main query
returns
Subquery CLERK 7900
MANAGER 7698
1-97 Copyright  CSC India, 2001. All rights reserved.
Single-Row Subqueries
• Return only one row
• Use single-row comparison operators
Operator Meaning

= Equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

<> Not equal to

1-98 Copyright  CSC India, 2001. All rights reserved.


Executing Single-Row Subqueries
SQL> SELECT ename, job
2 FROM emp
3 WHERE job = CLERK
4 (SELECT job
5 FROM emp
6 WHERE empno = 7369)
7 AND sal > 1100
8 (SELECT sal
9 FROM emp
10 WHERE empno = 7876);

ENAME JOB
---------- ---------
MILLER CLERK

1-99 Copyright  CSC India, 2001. All rights reserved.


Using Group Functions
in a Subquery
SQL> SELECT ename, job, sal
800
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp);

ENAME JOB SAL


---------- --------- ---------
SMITH CLERK 800

1-100 Copyright  CSC India, 2001. All rights reserved.


HAVING Clause with Subqueries
• The Oracle Server executes subqueries
first.
• The Oracle Server returns results into
the HAVING clause of the main query.
SQL> SELECT deptno, MIN(sal)
2 FROM emp
3 GROUP BY deptno
800
4 HAVING MIN(sal) >
5 (SELECT MIN(sal)
6 FROM emp
7 WHERE deptno = 20);

1-101 Copyright  CSC India, 2001. All rights reserved.


What Is Wrong
with This Statement?
SQL> SELECT empno, ename
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp
6 GROUP BY deptno);

ERROR:
ORA-01427: single-row subquery returns more than
one row

no rows selected

1-102 Copyright  CSC India, 2001. All rights reserved.


Multiple-Row Subqueries
• Return more than one row
• Use multiple-row comparison operators
Operator Meaning

IN Equal to any member in the list

ANY Compare value to each value returned by


the subquery

Compare value to every value returned by


ALL
the subquery

1-103 Copyright  CSC India, 2001. All rights reserved.


Using ANY Operator
in Multiple-Row Subqueries
SQL> SELECT empno, ename, job 1300
2 FROM emp 1100
800
3 WHERE sal < ANY 950
4 (SELECT sal
5 FROM emp
6 WHERE job = 'CLERK')
7 AND job <> 'CLERK';

EMPNO ENAME JOB


--------- ---------- ---------
7654 MARTIN SALESMAN
7521 WARD SALESMAN

1-104 Copyright  CSC India, 2001. All rights reserved.


Using ALL Operator
in Multiple-Row Subqueries
SQL> SELECT empno, ename, job 1566.6667
2 FROM emp 2175
2916.6667
3 WHERE sal > ALL
4 (SELECT avg(sal)
5 FROM emp
6 GROUP BY deptno);

EMPNO ENAME JOB


--------- ---------- ---------
7839 KING PRESIDENT
7566 JONES MANAGER
7902 FORD ANALYST
7788 SCOTT ANALYST

1-105 Copyright  CSC India, 2001. All rights reserved.


Summary
Subqueries are useful when a query is
based on unknown values.
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

1-106 Copyright  CSC India, 2001. All rights reserved.


Multiple-Column Subqueries

Copyright  CSC India, 2001. All rights reserved.


Multiple-Column Subqueries
Main query
MANAGER 10

Subquery
SALESMAN 30
MANAGER 10
CLERK 20

Main query Values from a multiple-row and


compares to
multiple-column subquery
SALESMAN 30
MANAGER 10
MANAGER 10
CLERK 20
1-108 Copyright  CSC India, 2001. All rights reserved.
Using Multiple-Column
Subqueries
Display the order number, product number, and
quantity of any item in which the product
number and quantity match both the product
number and quantity of an item in order 605.
SQL> SELECT ordid, prodid, qty
2 FROM item
3 WHERE (prodid, qty) IN
4 (SELECT prodid, qty
5 FROM item
6 WHERE ordid = 605)
7 AND ordid <> 605;

1-109 Copyright  CSC India, 2001. All rights reserved.


Using a Subquery
in the FROM Clause
SQL> SELECT a.ename, a.sal, a.deptno, b.salavg
2 FROM emp a, (SELECT deptno, avg(sal) salavg
3 FROM emp
4 GROUP BY deptno) b
5 WHERE a.deptno = b.deptno
6 AND a.sal > b.salavg;

ENAME SAL DEPTNO SALAVG


---------- --------- --------- ----------
KING 5000 10 2916.6667
JONES 2975 20 2175
SCOTT 3000 20 2175
...
6 rows selected.

1-111 Copyright  CSC India, 2001. All rights reserved.


Sub query’s examples;
SQL> Select Ename,sal from emp
where sal=(select max(sal) from emp);

SQL> Select Ename,deptno,sal from emp


where (deptno,sal) in(select deptno,max(sal) from emp
group by deptno);

SQL> Create table emp1 as select * from emp;

SQL> Create table emp2 as select * from emp where 1=2;

SQL> Insert into emp2(select * from emp);

SQL> Insert into emp2(empno,ename) (select empno,ename from emp);

SQL> Update emp set sal=4000 where deptno=(select deptno from dept
where dname=‘SALES’);

1-112 Copyright  CSC India, 2001. All rights reserved.


• To find the employees getting maximum salary of any dept.
Sql> Select ename, deptno,sal from emp WHERE sal> ANY (select
max(sal) from emp group by deptno);
To find the employees getting maximum salary of every dept.

Sql> Select ename, deptno,sal from emp WHERE sal> ALL (select
max(sal) from emp group by deptno);

Sql> Select ename, deptno,sal from emp WHERE sal> ALL (select
max(sal) from emp where deptno in(20,30) group by deptno);

• To select Duplicate rows present in the table


SQL>Select count(rowid), empno from emp
group by empno
having count(rowid)>1;
SQL> select * from emp
where rowid not in (select min(rowid) from emp group by empno);
1-113 Copyright  CSC India, 2001. All rights reserved.
Top N Analysis
• To display 5th row.

Sql> Select ename, sal from emp


Where rowid = (select rowid from emp where rownum <= 5
MINUS
select rowid from emp where rownum < 5);
• To display last 2 rows.
Sql> select ename, sal from emp where rowid in
(select rowid from emp
minus
select rowid from emp where rownum <= (select count(*)-2
from emp));
• To display rows from m to n.
Sql> select ename from emp
group by rownum, ename
having rownum > 1 and rownum < 4
1-114 Copyright  CSC India, 2001. All rights reserved.
• To display top 5 paid employees

Sql> select ename, deptno, sal


from (select * from emp order by sal desc)
where rownum < 5;

• To display alternate rows

Sql> select * from emp where (rowid,1) in


( select rowid,mod(rownum,2) from emp )

1-115 Copyright  CSC India, 2001. All rights reserved.


Updating with
Multiple-Column Subquery
Update employee 7698’s job and department
to match that of employee 7499.
SQL> UPDATE emp
2 SET (job, deptno) =
3 (SELECT job, deptno
4 FROM emp
5 WHERE empno = 7499)
6 WHERE empno = 7698;
1 row updated.

1-116 Copyright  CSC India, 2001. All rights reserved.


Updating Rows Based
on Another Table
Use subqueries in UPDATE statements to
update rows in a table based on values
from another table.
SQL> UPDATE employee
2 SET deptno = (SELECT deptno
3 FROM emp
4 WHERE empno = 7788)
5 WHERE job = (SELECT job
6 FROM emp
7 WHERE empno = 7788);
2 rows updated.

1-117 Copyright  CSC India, 2001. All rights reserved.


Correlated query Example;
• To find employee details who are getting salary greater than
avg salary of their own department
SQL> Select ename,sal,deptno from emp e
where sal>(select avg(sal) from emp m
where m.deptno =e.deptno);
• To find N th max sal
SQL> select * from emp x where &no=(select count (distinct sal)
from Emp y where y.sal>=x.sal);
• To find N th least sal
SQL> select * from emp x where &no=(select count (distinct sal)
from Emp y where y.sal<=x.sal)

• To select Duplicate rows present in the table


SQL> select * from dept1
where rowid not in (select min(rowid) from dept1 group by deptno)

1-118 Copyright  CSC India, 2001. All rights reserved.


Deleting Rows Based
on Another Table
Use subqueries in DELETE statements to
remove rows from a table based on values
from another table.
SQL> DELETE FROM employee
2 WHERE deptno =
3 (SELECT deptno
4 FROM dept
5 WHERE dname ='SALES');
6 rows deleted.

1-119 Copyright  CSC India, 2001. All rights reserved.


THANK YOU

1-120 Copyright  CSC India, 2001. All rights reserved.


PL/SQL Programming

Copyright  CSC India, 2001. All rights reserved.


SQLSQL statement
Statement Executor
Executor

1-122 Copyright  CSC India, 2001. All rights reserved.


Main Features

• Block Structure
PL/SQL is a block-structured language. That is, the basic
units (procedures, functions, and anonymous blocks) that
make up a PL/SQL program are made of PL/SQL blocks.

•Variables and Constants


PL/SQL allows you to declare constants and variables, then use
them in SQL and procedural statements anywhere an expression
can be used. However, forward references are not allowed.
1-123 Copyright  CSC India, 2001. All rights reserved.
•Modularity
Modularity lets you break an application down into
manageable, well-defined logical modules.

•Subprograms
PL/SQL has two types of subprograms called procedures and
functions, which can take parameters and be invoked (called).

•Packages
PL/SQL lets you bundle logically related types, variables,
cursors, and subprograms into a package.

•Error Handling
Oracle has a robust error-handling mechanism. It allows us to
create custom error code as well.

1-124 Copyright  CSC India, 2001. All rights reserved.


Advantages of PL/SQL

• Support for SQL

Better performance
Without PL/SQL, Oracle must process SQL statements one at a time.
Each SQL statement results in another call to Oracle and higher
performance overhead. In a networked environment, the overhead can
become significant. Every time a SQL statement is issued, it must be
sent over the network, creating more traffic. However, with PL/SQL,
an entire block of statements can be sent to Oracle at one time. This can
drastically reduce communication between your application and Oracle.

• PL/SQL stored procedures are compiled once and stored in executable form, so
procedure calls are quick and efficient. Also, stored procedures, which
execute in the server, can be invoked over slow network connections with
a single call. That reduces network traffic and improves round-trip
response times.

1-125 Copyright  CSC India, 2001. All rights reserved.


• PL/SQL adds functionality to non-procedural tools such as Oracle Forms
andOracle Reports. With PL/SQL in these tools, you can use familiar
procedural constructs to build applications. For example, you can
use an entire PL/SQL block in an Oracle Forms trigger. Thus,
PL/SQL increases productivity by putting better tools in your hands.

•Full portability
Applications written in PL/SQL are portable to any operating system
and platform on which Oracle runs. In other words, PL/SQL
programs can run anywhere Oracle can run; you need not tailor
them to each new environment. That means you can write portable
program libraries, which can be reused in different environments.

1-126 Copyright  CSC India, 2001. All rights reserved.


Types of PL/SQL Programs

Anonymous blocks( unnamed blocks)


Stored procedures
Stored functions
Packages
Triggers

1-127 Copyright  CSC India, 2001. All rights reserved.


Block Structure
All the modules have a common block structure. The block is broken up into four
different sections.
The Header
This only applies to the named blocks i.e. Procedure and Functions and
determines the way the block is called. The header includes the Block name,
parameter list and a RETURN clause if the block is a Function.
The Declaration Section
This is the part that declares variables, cursors and exceptions used in the
module. This section is optional but if used, it must come before the execution and
exception sections.
The Execution Section
This is the part that contains the PL/SQL executable statements that are executed
by the PL/SQL run time engine. This section contains the LOOPs, IF-THEN_ELSEs
and assignment statements. Every block must have an executable section.
The Exception Section
This is the section that handles the exceptions to the normal processing,
designers can create named exceptions. This section is optional!. If this section is
included then when transfer is controlled to this section the error is either handled
or control passes to the block that called the current block.

1-128 Copyright  CSC India, 2001. All rights reserved.


Anonymous PL/SQL Block Structure

DECLARE

<Variable Declarations>;

BEGIN

<SQL & PL/SQL Statements>;

EXCEPTION

<Error Handling>;
END;

Copyright  CSC India, 2001. All rights reserved.


Parts of PL/SQL Block
PL/SQL Block contains three parts.
1.Declarative part:

Used to declare the variables,constants,cursors,types,exceptions and


Pragmas. Declaration Part is optional.

2.Executable part:

Used to include SQL(Non procedural) and PL/SQL (Procedural Statements).


This part is Mandatory.

3.Exception handling part:

Used to handle the runtime errors occurred in the executable part.


This part is optional.

1-130 Copyright  CSC India, 2001. All rights reserved.


Variables
A variable is storage location which can hold the data.

Use variables for:


• Temporary storage of data
• Manipulation of stored values
• Reusability
• Ease of maintenance

Handling Variables in PL/SQL


• Declare and initialize variables in the declaration section.
• Assign new values to variables in the executable section.
• Pass values into PL/SQL blocks through parameters.
• View results through output variables.

1-131 Copyright  CSC India, 2001. All rights reserved.


Variables
Types of variables :
Scalar Variables:
Made up of a single value, such as a number, date, or Boolean.

Composite Variables:
Made up of multiple values, such as a record or collection (PL/SQL
tables, NESTED tables and VARRAY’S).

• RECORD: contains multiple scalar values, similar to a table record


• TABLE: tabular structure with multiple columns and rows
• VARRAY: variable-sized array

1-132 Copyright  CSC India, 2001. All rights reserved.


Declaring Variables

Syntax:
Variable_name datatype [CONSTANT] [NOT NULL] [:= | DEFAULT initial_value];

Examples:
V_hiredate date;
V_deptno Number(2) Not Null:=10;
V_name Varchar2(15):=‘SMITH’;
V_comm Constant Number:=500;
V_bonus Number Default 500;

1-133 Copyright  CSC India, 2001. All rights reserved.


Attributes
Types of Attributes
1.%TYPE

The %TYPE attribute provides the datatype of a variable or database


column.
Example: V_ename Emp.Ename%type;

2. %ROWTYPE

The %ROWTYPE attribute provides a record type that represents a


row in a table. The record can store an entire row of data selected from
the table or fetched from a cursor or cursor variable.

Example: Emp_Rec Emp%rowtype;


1-134 Copyright  CSC India, 2001. All rights reserved.
DBMS_OUTPUT.PUT_LINE

An Oracle Supplied Packaged Procedure Used to display data from PL/SQL block
Must be enabled at SQL*PLUS with

SET SERVEROUTPUT ON

Example:
Declare
V_annual_sal Number:=60000;
V_sal Number;
Begin
V_sal:=V_annual_sal/12;
Dbms_Output.put_line (‘The monthly Sal is ‘||V_sal);
End;

1-135 Copyright  CSC India, 2001. All rights reserved.


Examples

Using SQL functions in PL/SQL

Declare
N number:=5;
P number;
Begin
P:=power(N,2);
dbms_output.put_line ('the power value of '||N||' is '||P);
End;

1-136 Copyright  CSC India, 2001. All rights reserved.


-- Selecting data from the database table
Declare
V_Ename Emp.Ename%type;
V_Sal Emp.Sal%type;
V_empno Emp.empno%type:=&V_empno;
Begin
Select Name ,Sal into V_Ename,V_Sal
from Emp
where Empno =V_empno;
Dbms_output.put_line(V_Ename||' '||V_Sal);
End;

1-137 Copyright  CSC India, 2001. All rights reserved.


Example 2 :
--Inserting data into the database table

Declare
V_Deptno Dept.deptno%type:=&v_deptno;
V_Dname Dept.dname%type:=‘&v_dname;
V_loc Dept.loc%type:=‘&loc’;
Begin
Insert into Dept Values (V_deptno,V_Dname,V_loc);
Commit;
End;

--Updating existing data

Declare
V_Ename Emp.Ename%type:='&v_ename';
V_newsal Number(10,2):=&newsal;
Begin
Update Emp set Sal=V_newsal where Ename=V_Ename;
Rollback;
End;

1-138 Copyright  CSC India, 2001. All rights reserved.


Working with %Rowtype

Declare
Emp_rec Emp%rowtype;
Begin
Select * into Emp_rec from Emp where ename=‘&ename’;
Dbms_Output.Put_Line(Emp_rec.Empno || ' '|| Emp_rec.Ename);
End;

1-139 Copyright  CSC India, 2001. All rights reserved.


Control Structures

Copyright  CSC India, 2001. All rights reserved.


Control Structures
Used to execute the statements conditionally

Types of Control structures

1. Conditional Control

2. Iterative Control

3. Sequential Control

1-141 Copyright  CSC India, 2001. All rights reserved.


Conditional Control
If statements are used to control the Execution of the statements
Types of IF statements.
If – Then – End if
Syntax: If <condition> Then
<statements>;
End if;
If – Then – Else – End if
If <condition> Then
<statements1>;
Else <Statements2>;
End if;
If – Then – Elsif – Else – End if
If <condition> Then
<statements1>;
Elsif <condition2> Then
<statements2>;
1-142
Else <Statements3>;
Copyright  CSC India, 2001. All rights reserved.
End if;
Examples1:

Declare
N Number:=&no;
Begin
If N Between 0 and 10 then
Dbms_output.put_line(N||' b/w 0 and 10');
Elsif N Between 11 and 20 then
Dbms_output.put_line(N||' b/w 11 and 20');
Else
Dbms_output.put_line(N||' out of range ');
End if;
End;

1-143 Copyright  CSC India, 2001. All rights reserved.


Example2:

DECLARE
Acct_balance NUMBER (11, 2);
Acct CONSTANT NUMBER (4):= 3;
Debit_amt CONSTANT NUMBER (5, 2):= 500.00;
BEGIN
SELECT bal into Acct_balance from BANK
WHERE Accno = Acct FOR UPDATE OF bal;
IF Acct_balance >= Debit_amt THEN
UPDATE BANK SET bal = bal - Debit_amt
Where Accno =acct;
ELSE
INSERT into TEMP1 values (Acct, Acct_balance, 'Insufficient funds');
END IF;
COMMIT;
END;

1-144 Copyright  CSC India, 2001. All rights reserved.


CASE Expressions

• The CASE statement evaluates a condition and performs an action for


each case.
DECLARE
Grade char (1):='&grade';
Appraisal varchar2 (20);
BEGIN
CASE
WHEN grade = 'A' THEN Appraisal:='Excellent';
WHEN grade = 'B' THEN Appraisal:='Very Good';
ELSE
Appraisal:='No such Grade';
End Case;
dbms_output.put_line (Appraisal);
END;

1-145 Copyright  CSC India, 2001. All rights reserved.


Iterative Control

Looping structures are used to execute the statements repeated times.

Types of Loops;
1. Simple Loop
2. While Loop
3. For Loop

Syntax for Simple Loop;


Loop
<Sequence of Statements>;
End loop;

EXIT Statement:
Used to Close the loop

Types of Exit statements:


1. Exit
2. Exit when <condition>

1-146 Copyright  CSC India, 2001. All rights reserved.


Example1:
DECLARE
A Number:=&NO;
BEGIN
Loop
A:=nvl(A,0)+1;
Dbms_output.put_line(A);
Exit When A=10;
End loop;
END;

Ex2: Fetching the data from Database table dept

DECLARE
Dept_rec dept%rowtype;
Dno number:=0;
BEGIN
LOOP
Dno:=dno+10;
Select * into dept_rec from DEPT where deptno =dno;
dbms_output.put_line (dept_rec.deptno||' '||dept_rec.dname||' '||dept_rec.loc);
EXIT when dno =40; --closes the loop conditionally
END LOOP;
END;

1-147 Copyright  CSC India, 2001. All rights reserved.


While Loop
WHILE-LOOP statement associates a condition with a sequence of statements.

Syntax:
While <condition> loop
<Statements>;
End loop;

Example:
DECLARE
A number;
BEGIN
WHILE nvl (A, 0) <10 LOOP
A:= Nvl (A, 0) +1;
Dbms_output.put_line (A);
END LOOP;
END;

1-148 Copyright  CSC India, 2001. All rights reserved.


FOR LOOP
FOR-LOOP Executes the statements in specified number of times.
Syntax:
Syntax:
For <Index_varible> in <lower bound>..<Upper bound> loop
<Statements>;
End loop;
Example:

DECLARE
X NUMBER:= 10;
BEGIN
FOR I IN 1..X LOOP
IF MOD (I, 2) = 0 THEN -- I is even
INSERT INTO temp VALUES (I, I||' is even');
ELSE
INSERT INTO temp VALUES (I, I||' is odd');
END IF;
IF I=X THEN
DBMS_OUTPUT.PUT_LINE (I||' ROWS INSERTED');
END IF;
END LOOP;
END;

1-149 Copyright  CSC India, 2001. All rights reserved.


Example2:

DECLARE
A number:=&no;
B number:=0;
BEGIN
For I in reverse 1..10 loop
B:=A*I;
Dbms_output.put_line (a|| ‘ * '||I||' = '||B);
End loop;
END;

1-150 Copyright  CSC India, 2001. All rights reserved.


Sequential Control

GOTO statement lets you branch to a label unconditionally


The label, an undeclared identifier enclosed by double angle brackets, ex: <<my_label>>
Example:
DECLARE
Dept_rec dept%rowtype;
Dno number:=0;
BEGIN
<<TOP>>
Dno:=dno+10;
Select * into dept_rec from dept where deptno=Dno;
dbms_output.put_line (dept_rec.deptno||' '||dept_rec.dname||' '||dept_rec.loc);
IF dno<40 then
GOTO TOP;
End if;
END;

1-151 Copyright  CSC India, 2001. All rights reserved.


DECLARE
V_empno Emp.empno%type:=&empno;
V_comm Emp.comm%type;
BEGIN
Select comm into V_comm from EMP where empno =v_empno;
IF V_comm is null then
GOTO UPDATE_COMM;
ELSE
dbms_output.put_line (v_comm);
END IF;
<<UPDATE_COMM>>
IF V_comm is null then
Update EMP set comm =500 where empno =v_empno;
dbms_output.put_line (v_empno||' comm is updated to '||999);
END IF;
END;
/

1-152 Copyright  CSC India, 2001. All rights reserved.


Exceptions

Copyright  CSC India, 2001. All rights reserved.


EXCEPTIONS

Exception is an error or warning in pl/sql that is raised during the Execution of block.

When it is raised?

• An oracle error occurs


• You raise it explicitly

How to handle it?

• Trap it in Exception handling part


• Propagate it to the calling environment

1-154 Copyright  CSC India, 2001. All rights reserved.


Exception types

Predefined Exceptions
• Raised implicitly by Oracle when pl/sql program violates oracle rule.
Non Predefined Exceptions
• Declared in the Declarative section and Oracle raises implicitly
User defined Exceptions
• User defined exceptions must be declared and raised explicitly by RAISE
statements.

1-155 Copyright  CSC India, 2001. All rights reserved.


Trapping predefined oracle errors
Trap using predefined Named exceptions present in package STANDARD.
Sample Predefined Exceptions:

• NO_DATA_FOUND
• TOO_MANY_ROWS
• DUP_VAL_ON_INDEX
• INVALID_NUMBER
• ZERO_DEVIDE
• INVALID_CURSOR
• STORAGE_ERROR
• CURSOR_ALREADY_OPEN
• CASE_NOT_FOUND
• PROGRAM_ERROR

1-156 Copyright  CSC India, 2001. All rights reserved.


Exception Name Oracle Error

CURSOR_ALREADY_OPEN ORA-06511
DUP_VAL_ON_INDEX ORA-00001
INVALID_CURSOR ORA-01001
INVALID_NUMBER ORA-01722
LOGIN_DENIED ORA-01017
NO_DATA_FOUND ORA-01403
NOT_LOGGED_ON ORA-01012
PROGRAM_ERROR ORA-06501
STORAGE_ERROR ORA-06500
TIMEOUT_ON_RESOURCE ORA-00051
TOO_MANY_ROWS ORA-01422
VALUE_ERROR ORA-06502
ZERO_DIVIDE ORA-01476

1-157 Copyright  CSC India, 2001. All rights reserved.


Ex: No_data_found

DECLARE
Emp_rec emp%rowtype;
v_empno number:=&eno;
BEGIN
SELECT * into emp_rec from emp where empno =v_empno;
dbms_output.put_line(emp_rec.ename);

EXCEPTION
WHEN NO_DATA_FOUND then
dbms_output.put_line ('empno not exist');
END;

1-158 Copyright  CSC India, 2001. All rights reserved.


Ex: TOO_MANY_ROWS

DECLARE
emp_rec emp%rowtype;
v_deptno emp.deptno%type:=&v_deptno;
BEGIN
SELECT * into emp_rec from emp where deptno =v_deptno;
dbms_output.put_line(emp_rec.ename||' '||emp_rec.sal);
EXCEPTION
WHEN TOO_MANY_ROWS Then
dbms_output.put_line ('Trying to fetch more than one row');
END;

1-159 Copyright  CSC India, 2001. All rights reserved.


Ex: ZERO_DIVIDE

DECLARE
A number:=&no;
B number:=0;
BEGIN
A:=A/B;
dbms_output.put_line(A);
EXCEPTION
when ZERO_DIVIDE then
Null;
END;
/

1-160 Copyright  CSC India, 2001. All rights reserved.


Ex: DUP_VAL_ON_INDEX

BEGIN
INSERT into dept values (&dno, '&dname', '&loc');
dbms_output.put_line('1 Row created');
EXCEPTION
when DUP_VAL_ON_INDEX then
dbms_output.put_line ('trying to enter duplicate deptno');
END;

1-161 Copyright  CSC India, 2001. All rights reserved.


Ex: VALUE_ERROR

DECLARE
V_ename number;
BEGIN
Select Ename into V_ename from EMP where empno =7566;
dbms_output.put_line (V_ename);
EXCEPTION
When VALUE_ERROR then
dbms_output.put_line ('Value Error ');
END;

1-162 Copyright  CSC India, 2001. All rights reserved.


Ex: CASE_NOT_FOUND

DECLARE
Grade char (1):='&Grade';
Appraisal varchar2 (20);
BEGIN
CASE
When Grade = 'A' then Appraisal:='Excellent';
When Grade = 'B' then Appraisal:='Very Good';
END case;
dbms_output.put_line (Appraisal);
EXCEPTION
When CASE_NOT_FOUND Then
Dbms_output.put_line ('Case Not Matching');
END;

1-163 Copyright  CSC India, 2001. All rights reserved.


Ex: User Defined Exception

DECLARE
V_ename EMP.Ename%type:='&ename';
V_comm number;
Null_comm Exception;
BEGIN
Select comm into V_comm from EMP where Ename= v_ename;

IF V_comm is null then


RAISE Null_comm;
ELSE
dbms_output.put_line (V_ename||' Comm is '||V_comm);
END IF;
EXCEPTION
When Null_comm then
Update EMP set comm =250 where Ename=V_ename;
Dbms_output.put_line (V_ename||' Comm is updated to 250');
When OTHERS then
Dbms_output.put_line (Sqlcode||' '||Sqlerrm);
END;

1-164 Copyright  CSC India, 2001. All rights reserved.


OTHERS handler
Used to handle all exceptions not named specifically
•Last handler in the block
Syntax;
EXCEPTION
WHEN OTHERS THEN
<STATEMENTS>;
END;

DECLARE
emp_rec emp%rowtype;
v_deptno emp.deptno%type:=&v_deptno;
BEGIN
SELECT * into emp_rec from emp where deptno =v_deptno;
dbms_output.put_line(emp_rec.ename||' '||emp_rec.sal);
EXCEPTION
When OTHERS Then
dbms_output.put_line ('Trying to fetch more than one row');
END; 1-165 Copyright  CSC India, 2001. All rights reserved.
Functions for Trapping Exceptions

1-166 Copyright  CSC India, 2001. All rights reserved.


Retrieving the Error Code and Error Message

SQLCODE – returns the oracle error number


SQLERRM – returns the error message
maximum length of an Oracle error message is 512 characters including
the error code.

DECLARE
emp_rec emp%rowtype;
v_empno number:=&eno;
BEGIN
SELECT * into emp_rec from emp where empno =v_empno;
dbms_output.put_line(emp_rec.ename);

EXCEPTION
When OTHERS then
dbms_output.put_line (SQLCODE||’ ‘||SQLERRM);
END;

1-167 Copyright  CSC India, 2001. All rights reserved.


Nested sub blocks

DECLARE
No number;
BEGIN
NULL;
BEGIN -- sub-block begins
SELECT 10/0 INTO no FROM dual;

EXCEPTION
WHEN ZERO_DIVIDE THEN
dbms_output.put_line ('zero divide');
END; -- sub-block ends

INSERT INTO Emp (empno,sal) VALUES (100,5000);


dbms_output.put_line( Row inserted');
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line(sqlcode||' '||sqlerrm);
END;

1-168 Copyright  CSC India, 2001. All rights reserved.


PRAGMA EXCEPTION_INIT
• Used to handle oracle errors which do not have predefined names.
• Processed at compile time

Syntax:
PRAGMA EXCEPTION_INIT (exception_name, -Oracle_error_number);
DECLARE
RESOURCE_BUSY Exception;
Pragma Exception_Init (RESOURCE_BUSY, -54);
V_Sal Number;
BEGIN
Select sal into V_Sal from emp where empno = 7566 for update of sal NO WAIT;
dbms_output.put_line(v_sal);
Exception
when RESOURCE_BUSY then
Dbms_Output..Put_Line ('Resource is Busy');
End;

1-169 Copyright  CSC India, 2001. All rights reserved.


Trapping errors occurred in declarative part

BEGIN
Declare
X Number := ‘ABC';
Begin --inner block starts
Dbms_Output.Put_Line(X);
Exception
When Value_Error then
Dbms_Output.Put_Line('Value Error in Innerblock');
End; -- inner block ends
EXCEPTION
When Value_Error then
Dbms_Output.Put_Line('Value Error in Outerblock');
END;

1-170 Copyright  CSC India, 2001. All rights reserved.


RAISE_APPLICATION_ERROR

Used to display user defined error number and error message

DECLARE
v_empno emp.empno%type:=&empno;
v_comm number;
BEGIN
SELECT comm INTO v_comm FROM EMP WHERE empno =
v_empno;
IF v_comm IS NULL THEN
-- Issue user-defined error message.
RAISE_APPLICATION_ERROR (-20101, 'Comm is missing');
ELSE
dbms_output.put_line(v_comm);
END IF;
END;

1-171 Copyright  CSC India, 2001. All rights reserved.


CURSORS

Copyright  CSC India, 2001. All rights reserved.


CURSORS
A Cursor is a private SQL work area used to process the SQL
statements

Types of Cursors
Static Cursor:
• Implicit cursor
• Explicit cursor

Dynamic cursors:
Ref cursor
• Weak cursor
• Strong cursor

1-173 Copyright  CSC India, 2001. All rights reserved.


Explicit Cursors

• Explicit Cursors are used for queries that return multiple rows.
• Explicit Cursors must be declared.
Syntax
Cursor <Cursor_Name> is <Select_Statement>;
Ex:
Cursor C1 is Select * from Emp where deptno =10;

Cursor Control

OPEN – Executes the SQL Statement Associated with the Cursor


Syntax: OPEN <Cursor_Name>;
FETCH – Returns rows from the cursor into variables.
Syntax: FETCH <Cursor_Name> into <Varible_Name>;
CLOSE – Closes the cursor after fetching all the rows.
Syntax: CLOSE C1;

1-174 Copyright  CSC India, 2001. All rights reserved.


1-175 Copyright  CSC India, 2001. All rights reserved.
1-176 Copyright  CSC India, 2001. All rights reserved.
Ex:1 To retrieve the Employee info

DECLARE
V_deptno Emp.deptno%type:=&deptno;
Cursor c1 is select * from EMP where deptno =V_deptno;
Emp_rec c1%rowtype;
BEGIN
OPEN C1;
LOOP
FETCH c1 into Emp_rec;
Dbms_output.put_line (Emp_rec.empno||'
'||Emp_rec.ename);
EXIT;
END LOOP;
CLOSE C1;
EXCEPTION
When OTHERS Then
Dbms_output.put_line (SQLCODE||' '||SQLERRM);

END;

1-177 Copyright  CSC India, 2001. All rights reserved.


Explicit Using Cursor Attributes

• Returns status of the execution of multi-row query


• Controls the flow of Execution of the multi-row query

Explicit cursor has four attributes:

1-178 Copyright  CSC India, 2001. All rights reserved.


Ex: %NOTFOUND

DECLARE
Cursor C1 is select * from Emp where deptno=&deptno;
Emp_rec C1%rowtype;
BEGIN
OPEN C1;
LOOP
FETCH C1 into Emp_rec;
EXIT WHEN C1%NOTFOUND;
Dbms_output.put_line(Emp_rec.empno||' '||Emp_rec.ename);
END LOOP;
CLOSE C1;
END;

1-179 Copyright  CSC India, 2001. All rights reserved.


Ex: %ROWCOUNT

DECLARE
Emp_rec Emp%rowtype;
Cursor C1 is select * from Emp;
v_count number;
BEGIN
OPEN C1;
LOOP
FETCH C1 into Emp_rec;
v_count:=C1%rowcount;
Dbms_output.put_line(Emp_rec.empno||' '||Emp_rec.ename);
Exit when C1%rowcount=5;
END LOOP;
Dbms_output.put_line(v_count||' rows selected ');
Close c1;
EXCEPTION
when others then
dbms_output.put_line(sqlcode||' '||sqlerrm);
END;

1-180 Copyright  CSC India, 2001. All rights reserved.


Cursor For Loop
•Simplifies the Explicit cursor process.
•Implicit Open,Fetch,Exit, and Close occurs
•Record is implicitly declared
DECLARE
Emp_rec Emp%rowtype;
Cursor c1 is select * from Emp;
BEGIN
FOR I IN C1 LOOP
Dbms_output.put_line(I.EMPNO||' '||I.ENAME);
END LOOP;
EXCEPTION
WHEN OTHERS Then
Dbms_output.put_line(SQLCODE||' '||SQLERRM);
END;
1-181 Copyright  CSC India, 2001. All rights reserved.
Ex: INVALID_CURSOR Exception

DECLARE
Emp_rec Emp%Rowtype;
Cursor c1 is Select * from Emp;
V_count number;
BEGIN
FOR I IN C1 LOOP
V_count:=C1%rowcount;
Dbms_output.put_line(I.EMPNO||' '||I.ENAME);
EXIT When C1%rowcount>5;
END LOOP;
--Dbms_output.put_line(C1%rowcount||' Rows selected ');
Dbms_output.put_line(V_count||' Rows selected ');
EXCEPTION
When INVALID_CURSOR Then
Dbms_output.put_line ('Invalid Cursor');
When OTHERS THEN
Dbms_output.put_line(SQLCODE||' '||SQLERRM);
END;

1-182 Copyright  CSC India, 2001. All rights reserved.


Where Current of Cursor
• Use cursors to update or delete the current row
• Include the FOR UPDATE clause in the cursor

DECLARE
Cursor C1 IS Select * from Emp FOR UPDATE OF SAL;
BEGIN
FOR I IN C1 LOOP
IF I.Comm is null Then
UPDATE Emp SET comm= Sal*0.1 WHERE CURRENT OF C1;
END IF;
END LOOP;
EXCEPTION
When OTHERS Then
Dbms_output.put_line(SQLCODE||' '||SQLERRM);
END;

1-183 Copyright  CSC India, 2001. All rights reserved.


Cursors with parameters
•Pass parameter values to a cursor when the cursor is opened and the
query is Executed
•Open the Explicit cursor several times with a different active set each time.
DECLARE
Cursor C1(V_deptno Number) is select * from Emp where deptno =v_deptno;
Emp_rec C1%rowtype;
BEGIN
OPEN C1(10);
LOOP
FETCH c1 into Emp_rec;
EXIT When C1%notfound;
Dbms_output.put_line(Emp_rec.empno||' '||Emp_rec.ename);
END LOOP;
CLOSE C1;
OPEN C1(20);
LOOP
FETCH c1 into Emp_rec;
EXIT When C1%notfound;
Dbms_output.put_line(Emp_rec.empno||' '||Emp_rec.ename);
END LOOP;
1-184CLOSE C1; Copyright  CSC India, 2001. All rights reserved.
END;
Cursor FOR LOOP Using Subqueries

•No need to declare the cursor

DECLARE
Bonus Number(10,2);
BEGIN
FOR emp_rec IN (SELECT Empno, Sal, comm FROM Emp) LOOP
bonus := (Emp_rec.sal * 0.05) + NVL(Emp_rec.comm,1) * 0.25;
INSERT INTO Bonuses VALUES (Emp_rec.empno, Bonus);
END LOOP;
COMMIT;
END;

1-185 Copyright  CSC India, 2001. All rights reserved.


Working with Group Functions
DECLARE
Cursor c1 is Select max(sal) max_sal,min(sal) min_sal,deptno
from Emp
group by deptno;
Emp_rec c1%rowtype;

BEGIN
Dbms_output.put ('MAXSAL'||' '||'MINSAL'||' '||'DEPTNO');
FOR I IN C1 LOOP
Dbms_output.put_line(' ');
Dbms_output.put_line(I.MAX_SAL||' '||I.MIN_SAL||' '||I.DEPTNO);
END LOOP;
EXCEPTION
When OTHERS THEN
Dbms_output.put_line(SQLCODE||' '||SQLERRM);
END;

1-186 Copyright  CSC India, 2001. All rights reserved.


• c10
Cursor variables
•Cursor variable refers to the current row in the in the result set
of multi row query
•To use cursor variables, you must first create a REF_CURSOR type,
then declare a cursor variable based on that type.

REF cursor :
A cursor variable is a reference type. A reference type is similar to a pointer.
It can name different storage locations as the program runs. In order to use
the reference type, the variable has to be declared and storage has to be
allocated. REF cursors are further classified based on the return type
1. Strong Cursor : A strong cursor is a cursor whose return type is specified.
2. Weak Cursor : A weak cursor is a cursor whose return type is not specified.

1-187 Copyright  CSC India, 2001. All rights reserved.


Ref Cursors
DECLARE
Type Test is Ref Cursor;
V_cur Test;
v_Emp Emp%RowType;
V_Dept Dept%RowType;
BEGIN
Open V_cur for Select * from Emp;
Loop
Fetch V_cur into v_Emp;
Dbms_Output.Put_Line(v_Emp.Ename);
If V_cur%NotFound then Exit;
End If;
End Loop;
Dbms_Output.Put_Line(Chr(10));
Open V_cur for Select * from dept;
Loop
Fetch V_cur into V_Dept;
Dbms_Output.Put_Line(V_Dept.Dname);
If V_cur%NotFound then Exit;
End If;
End Loop;
Close V_cur;
END;
1-188 Copyright  CSC India, 2001. All rights reserved.
IMPLICIT CURSORS
Oracle implicitly opens a cursor to process each SQL statement
not Associated with an Explicitly declared cursor

Implicit Cursor Attributes'


SQL%ROWCOUNT Number of rows affected by the
most recent SQL statement (an integer
value).
SQL%FOUND Boolean attribute that evaluates to
TRUE if the most recent SQL
statement affects one or more rows.
SQL%NOTFOUND Boolean attribute that evaluates to
TRUE if the most recent SQL
statement does not affect any rows.
SQL%ISOPEN Always evaluates to FALSE because
PL/SQL closes implicit cursors
immediately after they are executed.

1-189 Copyright  CSC India, 2001. All rights reserved.


BEGIN
UPDATE Emp SET SAL=Sal*1.1 Where Deptno=&deptno_tobe_updated;
If SQL%Found Then
Dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated');
Else
Dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated');
End if;
Delete from Emp where deptno=&deptno_tobe_deleted;
If SQL%Found Then
Dbms_output.put_line(SQL%ROWCOUNT||' Rows deleted');
Else
Dbms_output.put_line(SQL%ROWCOUNT||' Rows deleted');
End if;
EXCEPTION
WHEN OTHERS Then
Dbms_output.put_line(SQLCODE||’ ‘||SQLERRM);
END;

1-190 Copyright  CSC India, 2001. All rights reserved.


Overview of Subprograms

A Subprogram:

Is a Named PL/SQL block that can accept parameters and be invoked


from the Calling environment
Is of two types:

• Procedure that performs an action


• Function that computes a value

Is based on standard pl/sql block structure


Provides Modularity,Reusability,Extensibility, and Maintainability
Provides easy Maintenance,Improved data security and Integrity,
Improved Performance, and Improved code clarity

1-191 Copyright  CSC India, 2001. All rights reserved.


Subprograms

Copyright  CSC India, 2001. All rights reserved.


Overview of Subprograms

Sub programs are named PL/SQL blocks that can accept


parameters and can be invoked whenever required. Similar
to a PL/SQL block, a subprogram can also have a
declarative part, an executable part and an exception
handling part. Some of the important features are
Modularity : subprograms allow us to break a program into
manageable, well-defined logical modules.
Reusability : subprograms once executed can be used in
any number of applications.

1-193 Copyright  CSC India, 2001. All rights reserved.


Types of Subprograms

Procedures : Procedures are usually used


to perform any specific task.
Functions : Functions are used to
compute a value.

1-194 Copyright  CSC India, 2001. All rights reserved.


Block structure for PL/SQL Subprograms

1-195 Copyright  CSC India, 2001. All rights reserved.


PL/SQL Subprograms

1-196 Copyright  CSC India, 2001. All rights reserved.


Procedure
•Used to perform an Action
•Procedure may or may not return rows

• Syntax:

CREATE [OR REPLACE]


PROCEDURE procedure_name [(parameter [, parameter]...)] IS/AS
[Local declarations]
BEGIN
Executable statements
[EXCEPTION Exception handlers]
END [Procedure_Name]

1-197 Copyright  CSC India, 2001. All rights reserved.


Ex1 :

CREATE OR REPLACE Procedure GET_EMP_DET(V_deptno Number) is


Cursor C1 is select * from Emp where deptno=V_deptno;
Emp_rec C1%rowtype;
BEGIN
For I in C1 LOOP
Dbms_output.put_line(I.Ename||' '||I. Sal);
END LOOP;
EXCEPTION
When OTHERS Then
Dbms_output.put_line(SQLCODE||' '||SQLERRM);
END GET_EMP_DET;

1-198 Copyright  CSC India, 2001. All rights reserved.


Executing stored Procedures
Execute at SQL*PLUS Environment
SQL> EXEC Procedure_Name[parameter1,parameter2…]
Ex:
SQL>EXEC GET_EMP_DET(10)

Executing from Anonymous block:

Ex:

Declare
V_deptno Emp.empno%type:=&v_deptno;
Begin
GET_EMP_DET(V_deptno);
End;

1-199 Copyright  CSC India, 2001. All rights reserved.


Working with local subprograms

Ex2:
CREATE or Replace Procedure Emp_Insert
(V_empno in number, V_ename in varchar2) is
Procedure Emp_Log is
BEGIN
INSERT into LOG Values (User, Sysdate);
END Emp_Log;
BEGIN
INSERT into EMP (Empno, Ename) Values (V_empno, V_ename);

Emp_Log;
EXCEPTION
When Others then
Dbms_output.put_line (sqlcode||' '||sqlerrm);

END Emp_Insert;

1-200 Copyright  CSC India, 2001. All rights reserved.


Types of Parameters

In Parameter – This mode is used to pass value


to the sub program when invoked and no caller
procedure is required.
Out Parameter – This mode is used to return
values to the caller of a subprogram. So calling
procedure is required.
In Out Parameter – This mode is used to pass
initial values to the sub program when invoked
and it is also return values to the caller. So
calling procedure is required

1-201 Copyright  CSC India, 2001. All rights reserved.


Formal V/S Actual Parameters
Formal Parameters: Variables declared in the Parameter list of a
subprogram specification
Ex:
Create Procedure Raise_sal (p_empid number,p_amount number) is
Begin
<Executable statements>;
End ;

Actual Parameters: Variables or Expressions referred in the


Subprogram call
Ex:
Raise_sal(7566,10000)

1-202 Copyright  CSC India, 2001. All rights reserved.


Functions
A Function is a stored PL/SQL block which returns a value.
Can be stored in the database as a schema object for repeated
Execution.
A Function is called as part of an expression.
• Syntax:

[CREATE [OR REPLACE]]


FUNCTION function_name [(parameter [, parameter]...)] RETURN Datatype
{IS | AS}
[Local declarations]
BEGIN
Executable statements
[EXCEPTION Exception handlers]

END [name];

1-203 Copyright  CSC India, 2001. All rights reserved.


Locations to call User-Defined Functions

•Select list of a SELECT command


•Condition of the WHERE and HAVING clauses
•ORDER BY and GROUP BY clauses.
•VALUES clauses of the INSERT command
•SET clause of the UPDATE command

1-204 Copyright  CSC India, 2001. All rights reserved.


CREATE or REPLACE Function Get_Ename(p_empno in number)
Return Varchar2 is
V_ename varchar2(20);
BEGIN
Select Ename into V_ename from Emp where Empno =p_empno;
RETURN V_ename;
END Get_Ename;

SQL>Select Get_Ename (&empno) from dual; --Calling from SQL *plus

--Calling from Anonymous block


DECLARE
V_empno Emp.empno%type:=&empno;
V_Ename Emp.Ename%type;
BEGIN
V_Ename:=Get_Ename(V_empno);
Dbms_output.put_line(V_ename);
EXCEPTION
When OTHERS Then
Dbms_output.put_line(SQLCODE||'
1-205 '||SQLERRM);
Copyright  CSC India, 2001. All rights reserved.
END;
1-206 Copyright  CSC India, 2001. All rights reserved.
1-207 Copyright  CSC India, 2001. All rights reserved.
Packages

Copyright  CSC India, 2001. All rights reserved.


Packages
•A package is an encapsulated collection of related program objects stored
together in the database.
• Program objects are procedures, functions, variables, constants, cursors,
and exceptions.
•Let you organize your application development more efficiently.
•Let you grant privileges more efficiently.
•Let you modify package objects without recompiling dependent schema
objects.
•Enable Oracle to read multiple package objects into memory at once.
•Let you overload procedures or functions.
•Can contain global variables and cursors that are available to all procedures
and functions in the package.
• Unlike subprograms, packages cannot be called, parameterized, or nested

1-209 Copyright  CSC India, 2001. All rights reserved.


Parts of the Package
Package contains two parts
• Specification
• Body
The specification is the interface to the applications.
It declares the types, variables, constants, exceptions, cursors,
and subprograms available for use.
The body fully defines cursors and subprograms,and so implements the
spec.

1-210 Copyright  CSC India, 2001. All rights reserved.


Package Specification:

Pack_Spec:

Create or Replace Package Emp_pack is


V_totsal number;
Cursor c1 is select Ename from Emp;
Procedure Get_empsal(V_Ename in varchar2);
Function Get_totsal Return Number;
END Emp_pack;

1-211 Copyright  CSC India, 2001. All rights reserved.


Package Body
Pack_Body:

CREATE or Replace Package body Emp_pack is


Procedure Get_Empsal (V_Ename in varchar2) is
BEGIN
Select sal into V_totsal from Emp where Ename=V_Ename;
Dbms_output.put_line(V_totsal);
END Get_empsal;

Function Get_Totsal Return Number is


BEGIN
Select sum(sal) into V_totsal from Emp;
Return (V_totsal);
END Get_totsal;
END Emp_pack;

1-212 Copyright  CSC India, 2001. All rights reserved.


Calling the Packaged Procedures

SQL> EXEC Emp_Pack.Get_Enpsal ('JONES')

Ex3:

SQL> BEGIN
For I in Emp_pack.c1 Loop
Emp_pack.Get_empsal(I.Ename);
End Loop;
END;

1-213 Copyright  CSC India, 2001. All rights reserved.


Calling the Packaged Functions

SQL> Select Emp_Pack.Get_Totsal From Dual;

Ex4:

SQL> BEGIN
Emp_Pack.V_totsal:=Emp_Pack.Get_totsal;
Dbms_output.put_line(Emp_Pack.V_totsal);
END;

1-214 Copyright  CSC India, 2001. All rights reserved.


Database Triggers

Copyright  CSC India, 2001. All rights reserved.


Database Triggers
•A trigger is a stored PL/SQL block associated with a table, view,
schema, or the database itself.
•Oracle automatically executes a trigger when a specified event takes place.
•A trigger can be either a database trigger or an application trigger.

Advantages of Triggers
•Auditing transactions
•Prevent invalid transactions
•Enforce complex business rules
•Enforce complex security authorizations
•Provide transparent event logging
•Automatically generate derived column values
•Enable building complex views that are updatable
•Track system events

1-216 Copyright  CSC India, 2001. All rights reserved.


Guidelines Designing Triggers

Design Trigger to:


• Perform Related Actions.
• Centralize global operations.

Do not Design Triggers:


• Where functionality is already built into the oracle server.
• That duplicate other triggers.

Create stored procedures and invoke them in a trigger, if the


PL/SQL Code is very lengthy.

1-217 Copyright  CSC India, 2001. All rights reserved.


Triggers v/s Procedures and Packages

Triggers are similar to stored procedures. A trigger can include


SQL and PL/SQL statements to execute as a unit and can invoke
stored procedures. Triggers are stored in the database separate
from their associated tables.

Procedures and triggers differ in the way that they are invoked.
• A procedure is explicitly executed by a user, application, or
trigger.
• Triggers (one or more) are implicitly fired (executed) by
Oracle when a triggering INSERT, UPDATE, or DELETE
statement is issued, no matter which user is connected or
which application is being used.

1-218 Copyright  CSC India, 2001. All rights reserved.


Types of Triggers

Application Trigger:
•Fires whenever an event occurs with a particular application

Database Trigger:

• Fire whenever a data event ( such as DML) or System event on


Schema or Database

Database Triggers can be:

• DML triggers on tables or views.


• INSTEAD OF triggers on views.
• System triggers on DATABASE or SCHEMA

1-219 Copyright  CSC India, 2001. All rights reserved.


1-220 Copyright  CSC India, 2001. All rights reserved.
1-221 Copyright  CSC India, 2001. All rights reserved.
1-222 Copyright  CSC India, 2001. All rights reserved.
Syntax:

CREATE [OR REPLACE] TRIGGER <trigger_name>

{BEFORE|AFTER} {INSERT|DELETE|UPDATE} ON <table_name>

[REFERENCING [NEW AS <new_row_name>]


[OLD AS <old_row_name>]]

[FOR EACH ROW [WHEN (<trigger_condition>)]]

<Trigger body>

1-223 Copyright  CSC India, 2001. All rights reserved.


Trigger Components

Trigger Timing:
• BEFORE
• AFTER
• INSTEAD OF
Triggering Event
• INSERT
• UPDATE
• DELETE
Trigger type:
• STATEMENT
• ROW
Trigger body:
• Complete PL/SQL block

1-224 Copyright  CSC India, 2001. All rights reserved.


DML Trigger
CREATE or REPLACE Trigger Week_End

BEFORE INSERT OR UPDATE OR DELETE ON EMP

BEGIN

If to_char(sysdate,'dy') ='fri' then

raise_application_error(-20000,‘Friday no transactions pls..');

End if;

END;

1-225 Copyright  CSC India, 2001. All rights reserved.


Create or Replace Trigger Emp_count
AFTER INSERT OR DELETE ON Emp
DECLARE
N number;
BEGIN
Select count(*) into n from Emp;
Dbms_output.put_line(' There are now ' || n ||
' employees.');
END;

1-226 Copyright  CSC India, 2001. All rights reserved.


Using OLD and NEW Qualifiers
•Old and New qualifiers are available in Row level triggers

• Used to reference the value of the column before and after the data
change by prefixing it with the OLD and NEW qualifiers

Data operation Old value New value


INSERT NULL Inserted value
UPDATE Value before update Value after update
DELETE Value before delete NULL

1-227 Copyright  CSC India, 2001. All rights reserved.


CREATE OR REPLACE trigger Print_salary_change
BEFORE UPDATE of sal on Emp
FOR EACH ROW
WHEN (OLD.DEPTNO =20)

DECLARE
sal_diff number;

BEGIN
sal_diff := :new.Sal - :old.sal;
Dbms_output.put('Old salary: ' || :old.sal);
Dbms_output.put (' New salary: ' || :new.sal);
Dbms_output.put_line(' Difference ' || sal_diff);
END;

1-228 Copyright  CSC India, 2001. All rights reserved.


CREATE OR REPLACE trigger update_emp BEFORE update of sal on Emp
for each row
BEGIN
IF :NEW.SAL < :OLD.SAL then
Raise_application_error(-20000,'new sal should be greater than old sal');
END IF;
END;

1-229 Copyright  CSC India, 2001. All rights reserved.


DML Triggers

CREATE or REPLACE trigger upper_ename BEFORE update on Emp


for each row
BEGIN
:new.ename:=upper (:new.ename);
END;

1-230 Copyright  CSC India, 2001. All rights reserved.


Using conditional predicates
Create or Replace Trigger Emp_Audit
Before insert or update or delete on Emp for each row
BEGIN
If INSERTING then
Insert into Emp_trans values(user,sysdate,:new.empno,'insertion');
Elsif DELETING then
Insert into Emp_trans values (user, sysdate, :old.empno, 'deletion');
Elsif UPDATING then
Insert into Emp_trans values (user, sysdate, :old.empno, 'updation');
End if;
END;

1-231 Copyright  CSC India, 2001. All rights reserved.


Schema Trigger

CREATE or REPLACE trigger t4 before alter on schema


BEGIN
if user='SCOTT' THEN
RAISE_APPLICATION_ERROR(-20000,'U CANOT MODIFY');
END IF;
END;
/

1-232 Copyright  CSC India, 2001. All rights reserved.


CREATE OR REPLACE TRIGGER emp_delete
BEFORE DELETE on Emp
FOR EACH ROW
WHEN ( old.deptno=10)
BEGIN
raise_application_error(-20000,'u cannot delete dept..10');

END;

1-233 Copyright  CSC India, 2001. All rights reserved.


DDL Trigger

CREATE or REPLACE Trigger ddl_trigger

BEFORE CREATE OR ALTER OR DROP ON SCHEMA

BEGIN

Raise_application_error(-20000,'sorry');

END;

1-234 Copyright  CSC India, 2001. All rights reserved.


1-235 Copyright  CSC India, 2001. All rights reserved.
1-236 Copyright  CSC India, 2001. All rights reserved.
Instead of Trigger
CREATE or replace trigger trig_view
INSTEAD OF insert or update on emp_dept
referencing new as new
for each row
DECLARE
Rowcnt number;
BEGIN
IF inserting then
SELECT count(*) into Rowcnt from EMP Where empno =:new.empno;
IF rowcnt = 0 Then
INSERT into EMP (empno, ename) VALUES (:new.empno, :new.ename);
ELSE
UPDATE Emp SET Emp.ename =:new.ename
WHERE Emp.empno =:new.empno;
END IF;
SELECT COUNT(*) INTO rowcnt FROM Dept WHERE deptno = :new.deptno;
IF rowcnt = 0 THEN
INSERT INTO Dept (deptno, dname) VALUES (:new.deptno, :new.dname);
ELSE
UPDATE Dept SET Dept.dname = :new.dname
WHERE Dept.deptno = :new.deptno;
END IF;
End 1-237
if;
Copyright  CSC India, 2001. All rights reserved.
END;
1-238 Copyright  CSC India, 2001. All rights reserved.
1-239 Copyright  CSC India, 2001. All rights reserved.
Advanced PL/SQL

Copyright  CSC India, 2001. All rights reserved.

Potrebbero piacerti anche