You are on page 1of 91

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


0
Introduction to PL/SQL
PL/SQL stands for Procedural Language extension of SQL , developed by
Oracle corporation. PL/SQL is a combination of SQL along with the procedural
features of programming languages. PL/SQL is the superset of SQL.

Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL
code can be stored in the client system (client-side) or in the database
(server-side).
PL/SQL Feature s
Variables
Block structure, Nested block structure
Conditional and sequential statements - (IF,CASE,CONTINUE,NULL)
Loop statements : WHILE loop, FOR loop
Exception and Error handling
Data types: string, numbers, date & timestamp, Boolean and LOB
Record | Collection | Cursor
Procedures, Functions, Packages
Object-orientation features
Dynamic SQL and Dynamic PL/SQL

PL/SQL some Advantages

PL/SQL is very useful language to manipulate , Control, Validate, and
Restricted the Unauthorized access of Data from the database. It sends an
entire block of ( pl/sql statements ) execute to the oracle engine at a time. It
is dealing with Error and returns user friendly error message.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Overview of PL/SQL Elements

A PL/SQL block is made up of three sections , they are
The DECLARATION Section (optional)
The EXECUTABLE section (mandatory).
The EXCEPTION section (optional)

Basic structure of PL/SQL block
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

Declaration :
This section starts with the reserved keyword DECLARE. It is an
optional section and defines all variables, cursors, subprograms, and
other elements to be used in the program.
Executable Commands (mandatory)


This section is enclosed between the keywords BEGIN and END. It
consists of the executable PL/SQL statements of the program. It
should have at least one executable line of code. This is the section
where the program logic is written to perform any task.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
Exception Handling
This section starts with the keyword EXCEPTION. This section is again
optional and contains exception(s) that handle errors in the program.

Sample Program

DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
** Every PL/SQL statement end with a semicolon (;) **
PL/SQL Program Units

PL/SQL block
Function
Package
Package body
Procedure
Trigger
Type
Type body
POINTS TO REMEMBER

PL/SQL is tightly integrated with SQL.
It offers extensive error checking.
It offers numerous data types.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
It offers a variety of programming structures.
It supports object oriented programming.
It supports developing web applications and server pages.
PL/SQL provides access to predefined SQL packages.
It supports structured programming through functions and procedures.

PL/SQL consists of blocks of code, which can be nested within each
other. Each block forms a unit of a task

PL/SQL allows sending an entire block of statements to the database
at one time. This reduces network traffic and provides high
performance for the applications.
PL/SQL Data types

PL/SQL provides a variety of predefined datatypes, which can be divided into
four categories ;
DATA TYPES IN VARIOUS CATEGORIES
SCALAR NUMBER, CHAR, VARCHAR2, DATE, BOOLEAN
COMPOSITE RECORD, TABLE and VARRAY.
REFERENCE REF CURSOR, REF Object_type
LOB BFILE, BLOB, CLOB, and NCLOB.
SCALAR
Single values with no internal components, ( NUMBER, DATE, or BOOLEAN)
NUMERIC - Numeric values, arithmetic operations are performed.
CHARACTER - Single characters or strings of characters
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
BOOLEAN - Logical values (logical operations are performed).
DATETIME - DATES and TIMES.
NUMERIC CHAR LOB
NUMBER CHAR BFILE
INT VARCHAR2 BLOB
INTEGER RAW CLOB
SMALLINT NCHAR NCLOB
NUMERIC LONG
DECIMAL ROWID
FLOAT UROWID
REAL
BINARY_INTEGER
BINARY_FLOAT
BINARY_DOUBLE
LARGE OBJECT (LOB)
Pointers to large objects that are stored separately from other data items,
such as text, graphic images, video clips, etc ..
BFILE - Used to store large binary objects In OS files outside the database.
BLOB - Used to store large binary objects in the database
CLOB - Used to store large blocks of character data in the database.
NCLOB. - Used to store large blocks of NCHAR data in the database.

REFERENCE
Pointers to the other data items.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
COMPOSITE
Data items that have internal components that can be accessed
individually. For ex : Collections and records.
PL/SQL Variables
Depending upon kind of data want to store , we can define variable name
with datatype. EX: Number (n,m) , Char (n) , Varchar2 (n) , Date , Long ,
Long raw, Raw, Blob, Clob, Nclob, Bfile.
DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c : ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f : ' || f);
END;
/

Variable Scope in PL/SQL

PL/SQL allows the nesting of Blocks i.e., each program block may contain
another inner block . If a variable is declared within an inner block, it is not
accessible to the outer block. However, if a variable is declared and accessible
to an outer block , it is also accessible to all nested inner Blocks.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Local Variables Vs Global Variables

SQL> SET SERVEROUTPUT ON;
<<BLOCK1>>
DECLARE
num1 number:= 70;
num2 number:= 78;
BEGIN
dbms_output.put_line('LINE 1 : Outer Variable num1:' || num1);
dbms_output.put_line('LINE 2 : Outer Variable num2:' || num2);
<<BLOCK2>>
DECLARE
num3 number := 100;
num4 number := 200;
BEGIN
dbms_output.put_line('LINE 3 :Inner variable num3:' || num3);
dbms_output.put_line('LINE 4 :Inner variable num4:' || num4);
dbms_output.put_line(' This is from block1.num2:' || num2);
END;
END;
/


DBMS_OUTPUT.PUT_LINE
In executable section to display any message want to the screen. PL/SQL
provides a procedure i.e. ( PUT_LINE) to allow the user to display the output
on the screen.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

SQL> SET SERVEROUTPUT ON;
Put the command at the beginning of the program
POINTS TO NOTE :
DBMS_OUTPUT.PUT_LINE procedure writes the message to be displayed
to the buffer for storage. Once a program has been completed, the
information in the buffer is displayed on the screen.
The size of the buffer is initialized at 2000 bytes, and can be set between
2000 and 1,000,000 bytes. To change the buffer size, use the following
command instead of the default SET SERVEROUTPUT ON:
SQL> SET SERVEROUTPUT ON SIZE 10000;
To Turn off the feature of displaying a message on screen
SQL> SET SERVEROUTPUT OFF;

Program for declaring constant Values

DECLARE
pi constant number := 3.141592654;
radius number(5,2);
dia number(5,2);
circumference number(7, 2);
area number (10, 2);
BEGIN
radius := 9.5;
dia := radius*2;
circumference := 2.0*pi*radius;
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
area := pi*radius*radius;
dbms_output.put_line('Radius: ' || radius);
dbms_output.put_line('Diameter: ' || dia);
dbms_output.put_line('Circumference: ' || circumference);
dbms_output.put_line('Area: ' || area);
END;
/


When the above code is executed at SQL prompt, output is :


Radius: 9.5
Diameter: 19
Circumference: 59.69
Area: 283.53
PL/SQL procedure successfully completed.

PLSQL- CONDITIONS

Decision making structures require one or more conditions to be evaluated or
tested by the program along with a statement or statements.

The selection structure tests a condition, then executes one sequence of
statements instead of another, depending on whether the condition is TRUE
or FALSE. The IF statement execute sequence of statements conditionally.

Three forms of IF STATEMENTS :
If IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF,


INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
Example for IF -THEN
If varl > 10 then
var2 := varl + 20;
END IF;

IF NOT(varl <= 10) THEN
var2 := varl + 20;
END IF;

IF varl > 10 THEN
IF var2 < varl THEN
var2 := varl + 20;
END IF;
END IF;

Example for IF-THEN-ELSE

If varl > 10 then
var2 := varl + 20;
END IF;

IF NOT (varl <= 10) THEN
var2 := varl + 20;
END IF;
Ggfgggggggggggggggggggggggggggggggggggggggggggggggggd

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
IF varl > 10 THEN
IF var2 < varl THEN
var2 := varl + 20;
END IF;
END IF;

Example for IF-THEN-ELSIF
IF varl > 10 THEN
var2 := varl + 20;
ELSIF varl BETWEEN 7 AND 8 THEN
var2 := var2 * varl;
ELSE
var2 := varl * varl;
END IF;

IF varl > 10 THEN
var2 := varl + 20;
ELSIF varl BETWEEN 7 AND 8 THEN
var2 := 2 * varl;
END IF;

POINTS TO NOTE :

The third form of IF statement uses the keyword ELSIF (NOT ELSEIF) to
introduce additional conditions.

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Example for IF-THEN-ELSIF
DECLARE
i number(1);
j number(1);
BEGIN
<< OUTER_LOOP >>
FOR i IN 1..2 LOOP
<< INNER_LOOP >>
FOR j IN 1..3 LOOP
dbms_output.put_line(' i is : ' || i || ' and j is : ' || j );
END loop inner_loop;
END loop outer_loop;
END;
/

When the above code is executed at SQL prompt, output is :


i is :1 and j is :1
i is :1 and j is :2
i is :1 and j is :3
i is :2 and j is :1
i is :2 and j is :2
i is :2 and j is :3

PL/SQL procedure successfully completed..
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

While- loop [ SYNTAX ]
WHILE <condition> LOOP
statement 1;
statement 2; Sequence of statements ;
...
Statement N;
END LOOP;

SQL> DECLARE
a number := 10;
BEGIN
WHILE
a < 20 loop
dbms_output.put_line('value of a: '||a);
a:=a+1;
end loop;
end;
/
When the above code is executed at SQL prompt, output is :


value of a: 10
value of a: 11
..
value of a: 19

PL/SQL procedure successfully completed.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

FOR- loop [ SYNTAX ]

FOR i in 1 .. 100000 loop
Insert into table_name values ( ** , *** , *** );
End loop ;

FOR i in reverse 1..1000 loop
insert into table_name values ( ** , *** , *** );
End loop ;

SQL> DECLARE
i number := 100;
BEGIN
for i in 1..5 loop
dbms_output.put_line(i);
i:=i+1;
end loop;
END;
/
i:=i+1;
* ERROR at line 6:
ORA-06550: line 6, column 1:
PLS-00363: expression 'I' cannot be used as an assignment target
ORA-06550: line 6, column 1:
PL/SQL: Statement ignored
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Program rewritten as following below ;

SQL> DECLARE
i number := 100;
x number :=0;
BEGIN
For i in 1..5 loop
dbms_output.put_line(i);
x := i+1;
end loop;
END;
/
1
..
..
5
PL/SQL procedure successfully completed.

REVERSE FOR LOOP

SQL> BEGIN
for i in REVERSE 1..3 loop
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
/
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


In order for Oracle to process SQL statement , Oracle creates a memory
area, known as CONTEXT AREA for processing an SQL statement, which
contains all information needed for processing the statement, for example,
number of rows processed , etc ..

PLSQL CURSORS
A cursor is a temporary work area created in the system memory when a
SQL statement is executed. A cursor contains information on a select
statement and the rows of data accessed by it.
This temporary work area is used to store the data retrieved from the
database, and manipulate this data.
A cursor is a pointer to this context area.
PL/SQL controls the context area through a cursor .
A cursor can hold more than one row, but can process only one row at a
time. The cursor holds "set of rows" - it is called 'active set'
Two types of Cursors
IMPLICIT CURSORS EXPLICIT CURSORS
Implicit Cursors
Implicit cursors are automatically created by Oracle ; whenever an SQL
statements like INSERT, UPDATE, and DELETE are executed. If DML
statements is issued, an implicit cursor is associated with this statement.
For INSERT operations, the cursor holds the data that need to be inserted.
For UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Implicit Cursors Applications :
As I said , when we execute DML statements like DELETE, INSERT, UPDATE
and SELECT statements, implicit statements are created to process these
statements. Oracle provides few attributes called as implicit cursor
attributes to check the status of DML operations.
Cursor Attributes are

%FOUND %NOTFOUND %ROWCOUNT %ISOPEN.

% FOUND ATT RIBUTE and Its DESCRIPTION

The return value is TRUE ;
If the DML statements like INSERT, DELETE and UPDATE affect at least
one row and if SELECT .INTO statement return at least one row.

The return value is FALSE ;
If DML statements like INSERT, DELETE and UPDATE do not affect row and
if SELECT.INTO statement do not return a row.
% NOT FOUND ATT RIBUTE and Its DESCRIPTION

It returns TRUE (OPPOSITE of %FOUND).
If an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT
INTO statement returned no rows. Otherwise, it returns FALSE.
DML statements do NOT affect single row and , It returns TRUE.
% ROW COUNT ATT RIBUTE and Its DESCRIPTION

It Return the number of rows affected by the DML operations INSERT,
DELETE, UPDATE, or returned by a SELECT INTO statement.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

% IS OPEN ATT RIBUTE and Its DESCRIPTION

Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
Example Program for IMPLICIT CURSOR Attributes

SQL> select * from emp;
NO NAME QUAL SALARY BONUS
1 sam m.sc 18000 1800
3 sona m.b.a 16000 1200
2 rose m.sc 20000 1200
4 sandya b.tech 20000 1600
5 maya m.c.a 18000 1600

SQL> DECLARE
row_cnt number:=0;
BEGIN
update emp set bonus = bonus+500;
IF SQL%FOUND then
row_cnt:=SQL%ROWCOUNT;
dbms_output.put_line('records updated count:' || row_cnt);
ELSIF SQL%NOTFOUND then
dbms_output.put_line('None of the salaries where updated');
end if;
end;
/
records updated count: 5
PL/SQL procedure successfully completed.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Program for to count deleted records (SQL%ROWCOUNT)
SQL> DECLARE
row_del NUMBER;
BEGIN
delete from emp;
row_del := SQL%ROWCOUNT;
dbms_output.put_line(' Deleted lines count is : || row_del );
end;
/
Deleted lines count is : 5
PL/SQL procedure successfully completed.

POINTS TO REMEMBER
IMPLICIT CURSOR is used to process INSERT/UPDATE/DELETE and
SELECT INTO statements. Oracle automatically performs the OPEN ,
FETCH and CLOSE operations during the processing of an implicit
cursor. NOTE : Most recently Implicit cursor is SQL Cursor [ SQL%].
PL/SQL provides some attributes for Implicit cursors;
%ROWCOUNT Number of rows processed by SQL statement.
%FOUND TRUE , If atleast one row processed.
%NOTFOUND TRUE, If no rows were processed.
%ISOPEN TRUE, IF cursor is open or false.
FALSE , If cursor has not been opened or has been closed.
IMPLICIT CURSORS are used in statements that return only one row at a time ,
if SQL statement returns more than one row error will occur.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


EXPLICIT CURSORS
EXPLICIT CURSORS are programmer defined cursors. Users can do
operations on a set of rows can be processed one by one .
Explicit Cursors should be defined in the DECLARATION SECTION of
the PL/SQL Block and created on SELECT statements which returns
more than one row.

When we executing a SELECT statement that returns more than one
row. Even though the cursor stores multiple records, only one record
can be processed at a time, which is called as current row. When
fetching a row the current row position moves to next row .

General Syntax of EXPLICIT CURSORS
CURSOR cursor_name IS select_statement ;
cursor_name : Name of the cursor.
select_statement : Select query which returns multiple rows.
Once we declare the cursor, EXPLICIT CURSOR involves four steps;
DECLARE Declaring the cursor in declaration area. i..e.
Initializes the cursor into memory .
OPEN Open the cursor in execution area. (Allotted memory ).
FETCH Fetch the data from cursors (now access data).
CLOSE Closing the cursor to release allocated memory.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


DECLARING THE CURSOR
DECLARE
CURSOR cursor_name IS
SELECT * from table_name WHERE column_name > 5000 ;
When declaring the CURSOR , should define the cursor name and
associated SELECT statement.
OPENING THE CURSOR
OPEN cursor_name ;
Once the cursor is created in the declaration section , user can access
the CURSOR in the EXECUTION section; Opening the cursor and
allocates memory for the cursor. Now the CURSOR is ready for
fetching the rows returned by the SQL statement .

FETCHING THE CURSOR

FETCH cursor_name INTO RECORD_NAME ; or
FETCH cursor_name INTO VARIABLE_LIST ;
FETCHING the cursor involves accessing one row at a time , user can
fetch a rows from opened cursor

CLOSING THE CURSOR

CLOSE cursor_name IS
Closing the cursor means releasing allocated memory opened cursors.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

EXPLICIT CURSOR ATTRIBUTES
Oracle provides some attributes ( EXPLICIT CURSOR ATTRIBUTES ) to
check status of an EXPLICIT CURSOR.

% FOUND ATT RIBUTE and Its DESCRIPTION

TRUE , if fetch statement returns at least one row..
FALSE , If fetch statement does NOT return a row.
Ex: cursor_name%FOUND

% NOT FOUND ATT RIBUTE and Its DESCRIPTION

TRUE , if fetch statement does NOT return a row.
FALSE , If fetch statement returns at least. one row.
Ex: cursor_name%NOTFOUND

% ROW COUNT ATT RIBUTE and Its DESCRIPTION

The number of rows fetched by the fetch statement
If NO row is returned PL/SQL statement throws error.
Ex: cursor_name%ROWCOUNT

% ISOPEN ATT RIBUTE and Its DESCRIPTION

TRUE , if the cursor is already open in the program.
FALSE , If the cursor is NOT opened in the program.
Ex: cursor_name%ISNAME

When we declare a cursor in declaration part , always start with initial
C_cursor_name , it will be always be clear that name refers to cursor.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

General form of EXPLICIT CURSOR

DECLARE
variables;
records;
CREATE a cursor;
BEGIN
OPEN the cursor;
FETCH the cursor;
Process the records;
CLOSE the cursor;
END;
Before we start sample programs Let us understand .

WHAT ARE RECORDS ?

Records are another type of data- types ( composite data types) ,
which means it is a combination of different scalar data types like char,
varchar, number etc. Each scalar data types I n the record holds a value.
RECORD TYPES

Assume , the record is a variable which holds table row or some
columns of a table. PL/SQL supports three (3) kinds of records.
TABLE BASED CURSOR BASED PROGRAMMER DEFINED
Lets discuss later about records. To create TABLE BASED AND
CURSOR BASED RECORD always prefer to use %ROWTYPE attribute.
~#~---@@-@@@@
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

CURSOR BASED RECORD :

A CUROSR BASED RECORD is whose structure matches the elements
of pre defined cursor. To create cursor based record we can use
%ROWTYPE attribute.
Ex: <record_name> <cursor_name>%ROWTYPE
cust_rec C_cr1%rowtype;

SQL> DECLARE
cursor C_cr1 Is select id , first_name , last_name from customers;
cust_rec C_cr1%rowtype;
BEGIN
OPEN C_cr1;
LOOP
FETCH C_cr1 into cust_rec;
EXIT WHEN C_cr1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(cust_rec.id || cust_rec.first_name|| '.'
|| cust_rec.last_name);
end loop;
close C_cr1;
END;
/
1tilak.sham
2sandya.gupta
3uma.saran

PL/SQL procedure successfully completed.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


EXPLICIT CURSOR USING %ROW TYPE Vs %TYPE


SQL>DECLARE
CURSOR c1 is select * From tab2;
dis_tab2 c1%rowtype;
i number:=1;
BEGIN
OPEN c1;
for i in 1..5 loop
FETCH c1 into dis_tab2;
dbms_output.put_line( dis_tab2.no || dis_tab2.first_name|| '.'
|| dis_tab2.last_name || dis_tab2.salary ||
dis_tab2.bonus || dis_tab2.qual);
end loop;
CLOSE c1;
END;
/
<< OUTPUT>>
PL/SQL procedure successfully completed.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

POINTS TO NOTE :

%ROWTYPE for record. This is more convenient in most situations when
there are 2 or more columns. %ROWTYPE attribute provides a record type
that represents a row in a database table. The record can store an entire row
of data selected from the table or fetched from a cursor or cursor variable.

EXPLICIT CURSOR USING %TYPE

%TYPE is used for scalar variables. Mostly %TYPE is using for when
there's just one column in the result set, With %TYPE, we have to
declare a separate variable for each column.

SQL> DECLARE
empno tab2.no%type;
efirst_name tab2.first_name%type;
elast_name tab2.last_name%type;
esalary tab2.salary%type;
ebonus tab2.bonus%type;
equal tab2.qual%type;
CURSOR c2 is
select no ,first_name , last_name , salary , bonus, qual from tab2;
BEGIN
OPEN c2;
LOOP
FETCH c2 into empno , efirst_name , elast_name ,
esalary , ebonus , equal;
EXIT WHEN c2%NOTFOUND;
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
dbms_output.put_line(empno || efirst_name || . ||
elast_name || esalary || ebonus || equal);
end loop;
close c2;
END;
/
.. << output>>

PL/SQL procedure successfully completed.
Difference between %TYPE Vs %ROWTYPE

%ROWTYPE is used to declare a record with same types found in the
specified table , view or cursor. %ROWTYPE permits to create
composite data type ( all the columns of a row in the table referenced
and lumped together into a single record. (ex If emp table contains
some columns like (empno , name , job ) ;

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

%TYPE is used to declare a field with the same type as that of a specified
tables column: (the variable that deal with table individual column).


POINTS TO REMEMBER

When the data is fetched it is copied to the record or variables and the
logical pointer moves to the next row and it becomes the current row.

On every fetch statement, the pointer moves to the next row. If more
than one row in a cursor , we can use loops along with explicit cursor
attributes to fetch all the records.

We can fetch the rows in a cursor to a PL/SQL Record or a list of variables
created in the PL/SQL Block. When fetching a cursor to a PL/SQL Record,
the record should have the same structure as the cursor.
R9hg9eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeergbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbggg
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

PL/SQL RECORDS
A PL/SQL RECORDS are composite data types, which means it is a
combination of different scalar data types like char , varchar , number etc

Each scalar data types in the record holds a value. It can be visualized as
a row of data i.e. (records consist of different fields , similar to a row of a
database table)". RECORDS makes easier by transferring the entire row
into a record , rather than transferring each column into a variable
separately.
PL/SQL handles three types of records ;

1. Table based.
2. Cursor based records.
3. User defined records.
TABLE BASED RECORDS
SQL> set serveroutput on;
SQL> DECLARE
2 val_disp customers%rowtype;
3 BEGIN
4 select * into val_disp from customers where no=100;
5 DBMS_OUTPUT.PUT_LINE(Customer ID : || val_disp.no);
6 DBMS_OUTPUT.PUT_LINE(Customer Name : || val_disp.name);
7 DBMS_OUTPUT.PUT_LINE(Customer Mobie : || val_disp.mobile);
8 DBMS_OUTPUT.PUT_LINE(Customer City : || val_disp.city);
9 END;
10 /
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

When the Program code is executed , it produces the result as

Customer ID: 5
Customer Name: Hardik
Customer Mobile : 9999999999
Customer City: Chenani

PL/SQL procedure successfully completed.
Trying to get more than one record using FOR LOOP
SQL> DECLARE
val_disp customers%rowtype;
i number :=1;
BEGIN
for i in 1..5 loop
select * into val_disp from customers;
DBMS_OUTPUT.PUT_LINE(val_disp.no);
DBMS_OUTPUT.PUT_LINE(val_disp.name);
DBMS_OUTPUT.PUT_LINE(val_disp.mobile);
DBMS_OUTPUT.PUT_LINE(val_disp.city);
end loop;
END;
/
DECLARE
* ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Cause of the Error :
In first example, the select statement specifies a where clause which
means that only one row is returned.
In second example the where clause is not present resulting in more than
one row being returned by the select statement. When using a select
into statement, only allowed to return one row.

CURSOR BASED RECORDS
SQL> DECLARE
CURSOR C_cr2 IS
select * from customers;
val_disp C_cr2%rowtype;
BEGIN
OPEN C_cr2;
LOOP
FETCH C_cr2 into val_disp;
EXIT WHEN C_cr2%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(val_disp.name || val_disp.mobile);
END LOOP;
CLOSE C_cr2;
END;
/
<< OUTPUT >>
PL/SQL procedure successfully completed.

RECORD NAME TABLE or cursor_name%ROWTYPE ; C_cr2%rowtype.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu



PROGRAMMER (USER) DEFINED RECORDS

General Syntax of RECORD TYPE
SYNTAX :
TYPE <type_name> IS RECORD
(<field_name 1> <datatype1>,
<field_name 2> <datatype2>,
...
<field_name N> <datatypeN>
);
EXAMPLE :
TYPE EMP_DETAILS IS RECORD
( e_id emp.eid%TYPE ,
e_name emp.ename%TYPE ,
e_qual emp.equal%TYPE
e_salary emp.esalary%TYPE
e_city emp.ecity%TYPE );
SYNTAX
<record_name> <record_type> ;
EXAMPLE
emp_detail EMP_DETAILS ;
variable_name VARIABLE_TYPE;

A cursor and record datatype created in declaration part of PL/SQL Block
having the same variables with same datatype. Lets see.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Sample Program
SQL> DECLARE
CURSOR C_cr IS
select eid, ename , equal , esalary , ecity from emp;
TYPE EMP_DETAILS IS RECORD
(e_id emp.eid%TYPE,
e_name emp.ename%TYPE,
e_qual emp.equal%TYPE,
e_salary emp.esalary%TYPE,
e_city emp.ecity%TYPE);
emp_detail EMP_DETAILS;
BEGIN
OPEN C_cr;
LOOP
FETCH C_cr into emp_detail;
EXIT WHEN C_cr%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(emp_detail.e_id || emp_detail.e_name ||
emp_detail.e_qual || emp_detail.e_salary || emp_detail.e_city);
END LOOP;
DBMS_OUTPUT.PUT_LINE(Total records count || C_cr%ROWCOUNT);
CLOSE C_cr;
END;
/
PL/SQL procedure successfully completed.
** emp_detail is a variable of type EMP_DETAILS. **
I am using lower case for variable names, and upper case for type names.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

EXCEPTION (ERROR) HANDLING :

What is an Exception :
In PL/SQL, errors and warnings are called as EXCEPTIONS.
Exception is raised during Program Execution.
When PL/SQL detects an error, normal execution stops and an exception
is raised). This exception can be captured and processed within the block
by the exception handler - if it is present.
Internal exceptions are raised by (automatically) by the run-time system.
User defined exceptions must be raised explicitly by RAISE statements.
Whenever a pre defined error occurs , PL/SQL raises an exception.
Oracle provides many predefined exceptions for common errors ;
ORA-01016
ACCESS _INTO_ NULL
ORA-01001
INVALID_CURSOR
ORA-01017
LOGIN_DENIED
ORA-01422
TOO_MANY_ROWS
ORA-01403
NO_DATA_FOUND


Simple Program for Predefined Exception :
SQL> DECLARE
disp_val varchar2(15);
BEGIN
select ename into disp_val from emp;
DBMS_OUTPUT.PUT_LINE(disp_val);
END;
/
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

DECLARE
* ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at line 4

Program rewritten with Manual Exceptions

SYNTAX
BEGIN
select ...
EXCEPTION
when too_many_rows then
statements;

SQL> DECLARE
disp_val varchar2(15);
BEGIN
Select ename into disp_val from emp;
DBMS_OUTPUT.PUT_LINE(disp_val);
EXCEPTION
WHEN TOO_MANY_ROWS then
DBMS_OUTPUT.PUT_LINE('CONSIDER CURSOR');
END;
/
CONSIDER CURSOR
PL/SQL procedure successfully completed.
In above program, user has created own exception to deal with errors.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Two Types of errors can be found in a program :

COMPILATION ERRORS AND RUN TIME ERRORS
PL/SQL block that handles the run time error. This is called EXCEPTION
HANDLING section. EXCEPTION (RUN TIME ERRORS) can arise from coding
mistakes, hardware failures, and many other sources.

General Structure for Exception Handling

EXCEPTION
WHEN EXCEPTION_NAME THEN
ERROR PROCESSING STATEMENTS;
General Structure for Exception Handling

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
WHEN EXCEPTION_NAME1 THEN
EXCEPTION1- ( ERROR PROCESSING STATEMENTS) ;
WHEN EXCEPTION_NAME2 THEN
EXCEPTION2 - ( ERROR PROCESSING STATEMENTS) ;
WHEN EXCEPTION_NAME3 THEN
EXCEPTION3 - ( ERROR PROCESSING STATEMENTS) ;
........
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

WHEN OTHERS THEN
ERROR PROCESSING STATEMENTS
END ;
/

Let us write simple code to illustrate the concept.

SQL> select * from emp;
EID ENAME EQUAL ESALARY ECITY
1 sona mba 10000 mumbai
2 maya mca 15000 calcutta
SQL> DECLARE
e_eid emp.eid%type :=3;
e_ename emp.ename%type;
e_equal emp.equal%type;
e_salary emp.esalary%type;
e_ecity emp.ecity%type;
BEGIN
select eid , ename , equal , esalary, ecity into e_eid, e_ename ,
e_equal , e_salary , e_ecity
from EMP where eid=e_eid;
DBMS_OUTPUT.PUT_LINE(e_eid);
DBMS_OUTPUT.PUT_LINE(e_ename);
DBMS_OUTPUT.PUT_LINE(e_equal);
DBMS_OUTPUT.PUT_LINE(e_salary);
DBMS_OUTPUT.PUT_LINE(e_ecity);
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO SUCH CUSTOMERS');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('ERROR');
*END;
/
NO SUCH CUSTOMERS
PL/SQL procedure successfully completed.

Exception Categories :

INTERNALLY DEFINED
PRE DEFINED
USER DEFINED

INTERNALLY DEFINED

System raises Internally defined Exceptions (automatically).
Examples of internally defind exceptions are ORA-00060 (deadlock)
and ORA-27102( out of memory).
REF_LINK for Internally Defined Exceptions.
http://docs.oracle.com/cd/E11882_01/server.112/e17766/toc.htm
INTERNALLY DEFINED EXCEPTION does nt have a name unless either
PL/SQL gives it one. If Internally defined exceptions dont have
names that we can write exception handlers for them. Otherwise we
can handle only with OTHERS EXCEPTION HANDLERS. Lets see.
PRE
DEFINED
EXCEPTION

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

EXCEPTION NAME DECLARTION and Its SYNTAX :

SYNTAX :
exception_name EXCEPTION
PRAGMA EXCEPTION_INIT (exception_name , error_code)
EXAMPLE :
SQL> CREATE OR REPLACE PACKAGE my_package
AS e_bulk_plsql_error EXCEPTION;
PRAGMA EXCEPTION_INIT(e_bulk_plsql_error, -24381) ;

When Oracle raises error ORA-24381, we can handle it by using your
exception name e_bulk_plsql_error. This may be raised and handled when
various conditions occur depending only on your program logic.

PRE - DEFINED

PREDEFINED EXCEPTIONS are internally defined exceptions that have
predefined names, which PL/SQL declares globally in the
package STANDARD. The runtime system raises predefined exceptions
implicitly (automatically). Some predefined exceptions names, are

EXCEPTION NAME ERROR CODE
INVALID_CURSOR -1001
INVALID_NUMBER -1722
NO_DATA_FOUND +100
PROGRAM_ERROR -6501
TOO_MANY_ROWS -1422
VALUE_ERROR -6502
ZERO_DEVIDE -1476
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

User - Defined Exceptions

Users can declare own exceptions in the declarative part of any PL/SQL
anonymous block, subprogram, or package.
An Exception name declaration has this syntax:
exception_name EXCEPTION;
User must raise user-defined exception explicitly. RAISING EXCEPTIONS.

POINTS TO NOTE :

Oracle recommends against redeclaring predefined exceptions. If anyone
redeclare a predefined exception, local declaration overrides the global
declaration in package STANDARD.

Raising Exceptions
To raise an exception explicitly, should use either following below.
RAISE statement , or RAISE_APPLICATION_ERROR procedure.
To invoke RAISE_APPLICATION_ERROR (should assign error_code , to
the user defined Exception_INIT pragma.

SYNTAX
PRAGMA EXCEPTION_INIT (exception_name, error_code)
EXAMPLE :
SQL> CREATE OR REPLACE PACKAGE my_package
AS e_bulk_plsql_error EXCEPTION;
PRAGMA EXCEPTION_INIT(e_bulk_plsql_error, -24381) ;
The error_code is an integer in the range -20000..-20999.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Sample Program for User Defined Exceptions:

SIMPLE SYNTAX
DECLARE
.. ...
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
PROGRAM
SQL>DECLARE
e_id emp.eid%type := &ccid;
e_name emp.ename%type;
e_qual emp.equal%type;
e_salary emp.esalary%type;
e_city emp.ecity%type;
ex_invalid_id EXCEPTION;
BEGIN
If e_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
select EID , ENAME , EQUAL , ESALARY , ECITY into e_id , e_name ,
e_qual , e_salary , e_city from emp
where eid=e_id;
DBMS_OUTPUT.PUT_LINE(e_id);
DBMS_OUTPUT.PUT_LINE(e_name);
DBMS_OUTPUT.PUT_LINE(e_salary);
DBMS_OUTPUT.PUT_LINE(e_city);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
DBMS_OUTPUT.PUT_LINE('ID must be greater than 0');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO SUCH CUSTOMER');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('ERROR');
END;
/
Enter value for ccid: 0
old 2: e_id emp.eid%type := &ccid;
new 2: e_id emp.eid%type := 0;
ID must be greater than 0

PL/SQL procedure successfully completed.


&ccid is a variable. "&" is used as substitution variable(for run time value from
the user) in oracle. In this example &ccid will ask, hold and pass the value to
the program entered by end user.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

PROCEDURES and FUNCTIONS


PL/SQL SUB - PROGRAMS -

A SUB - PROGRAMS is a named block of PL/SQL.
There are two types of SUB- PROGRAMS in PL/SQL.
They are named and stored within the database.
PROCEDURES and FUNCTIONS.
Every Sub - Program will have following Parts;
DECLARATIVE_PART
EXECUTALE_PART and
EXCEPTION_HANDLING_PART which is optional;
DECLARATIVE_PART contains variable declarations.
EXECUTALE_PART contains executable statements of SQL and PL/SQL.
EXCEPTION _PART handles exceptions.
When client executes a Procedure or Function , the processing done in the
server. This reduces network traffic. The sub - programs are compiled and
stored in the oracle database as stored programs and can be invoked
whenever required.

Procedures and Functions :
PROCEDURE OR FUNCTION is a named PL/SQL block.
Procedures and functions are normally stored in the database within
package specifications. Although they may also be stored in the database
individually. A procedure or function is parsed or compiled at the time it is
stored.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Anonymous blocks
An anonymous block is an unnamed. (block without name)
Since they are unnamed, anonymous blocks cannot be referenced by other
program units. A block of PL/SQL code that is not stored in the database
is Anonymous Block.

General format of an ANONYMOUS BLOCKS


[ DECLARE
... optional declaration statements ... ] ;
BEGIN
... executable statements ;
[ EXCEPTION
... optional exception handler statements ... ] ;
END ;

Anonymous block has three (3) sections, that are declaration , ececution ,
and exception handling . Only execution section is mandatory and others are
optional. The anonymous block cannot be called by any other block

SQL> BEGIN
DBMS.OUTPUT.PUT_LINE( WELCOME TO PL/SQL);
END;
/
PL/SQL procedure successfully completed.
This is the case for anonymous blocks. Next, we will rewrite the
anonymous block above as a procedure. we now use the user function
to greet the user.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Program rewritten as PROCEDURE

SQL> CREATE OR REPLACE PROCEDURE WELCOME IS
user_name varchar2(8) := user;
BEGIN
DBMS_OUTPUT.PUT_LINE( user_name || ' WELCOME TO PL/SQL);
END;
/
Procedure created.
SQL> execute welcome;
HR WELCOME TO PL/SQL
PL/SQL procedure successfully completed.

Creating Procedures :


CREATE [ OR REPLACE ] PROCEDURE [proc_name]
[ ( parameter[,parameter, ...])] { IS | AS }
[ local declarations ]
BEGIN
Executable statements
[ EXCEPTION
Exception handlers ]
END [proc_name];

Its Possible to define a procedure locally with in another PL/SQL unit. i.e.
inside a function, another procedure, or an anonymous block. These locally
defined procedures are always named. If they are defined inside a function
or another procedure , then they are stored in the database.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

If they are defined inside an anonymous block , then they are not stored in
the database."
Simple Procedure Program using Anonymous Block
SQL> DECLARE -- Begin anonymous block
PROCEDURE HELLO AS -- Define procedure in block
BEGIN
DBMS_OUTPUT.PUT_LINE(' THIS IS PLSQL - WELCOME ');
END; -- End of procedure definition
BEGIN -- Begin code section of anonymous block
DBMS_OUTPUT.PUT_LINE(' THIS IS PROCEDURE');
HELLO; -- Call previously defined procedure
END; -- End of anonymous block
/
THIS IS PROCEDURE
THIS IS PLSQL - WELCOME
PL/SQL procedure successfully completed.

In this example , an anonymous block that defines a procedure (HELLO) within
itself. The procedure HELLO is only visible inside. Once the block has
completed, the procedure hello no longer exists. Oracle compiles and runs an
anonymous block in a single pass , then throws it away.
As I said , If they are defined inside an anonymous block , then they are
not stored in the database. An anonymous block of PLSQL code that is
never called using EXECUTE.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

SQL> EXECUTE HELLO;
BEGIN HELLO; END;
* ERROR at line 1:
ORA-06550: line 1, column 7:
PLS-00201: identifier 'HELLO' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Once the block has completed, the procedure hello no longer exists.
Stored Procedure Version
SQL> create procedure my_proc as -- Begin procedure definition
PROCEDURE HELLO AS --Define procedure in procedure
BEGIN
DBMS_OUTPUT.PUT_LINE(' THIS IS PLSQL - WELCOME ');
END; -- End of inner procedure definition
BEGIN -- Begin code section of stored procedure
DBMS_OUTPUT.PUT_LINE(' THIS IS PROCEDURE');
HELLO; -- Call previously defined procedure
END; -- End of stored procedure definition
/
Procedure created.

NOTE : Anonymous block version the results were returned immediately
while in the stored procedure version there were no results.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


The CREATE PROCEDURE command just compiles the code and stores it in the
database, it does not actually run it. In order to get results, need to actually
run the procedure.

Procedure Vs Stored Procedure :

PROCEDURE and STORED PROCEDURE are same. Any procedure, which
we store with some name Is called STORED PROCEDURE.

Group of SQL statements that has been created at once and will be stored in
the server database. The compile format is saved and called whenever it
required.

Procedure is a anonymous block of PL/SQL code , it never stored in
database. Stored procedure is a named block of PL/SQL code , but it is
stored in the database.

STORED PROGRAM UNITS

PROCEDURES | FUNCTIONS | PACKAGES
Parameters (MODE) in Procedure and Functions

When creating Procedure or Function , we may define parameters. There
are three types of parameters can be declared. They are following below ,
IN (default) | OUT | IN OUT

IN PARAMETER (DEFAULT) :
Passes values to sub-program. (used to send a values) . In sub - program
IN parameter acts like a constant and it cannot be assigned a value.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


OUT PARAMETER
Must be specified. Actual parameter must be a variable.
Parameter acts like uninitialized variable.
Cannot be used in expression and must be assigned a value.
Returns value to the caller. i.e. ( to get values from stored procedures
- similar to return type in function).

IN OUT PARAMETER (DEFAULT) :
Must be specified . Actual Parameter must be a variable.
Parameter acts like uninitialized variable and should be assigned a value.
Passing initial value to a sub- program and returns updated values to the
caller. i.e. (used to send values and get value s from stored procedures).

General SYNTAX for IN Parameter
CREATE [OR REPLACE] PROCEDURE procedure_name
( param_name1 IN datatype, param_name2 IN datatype ... )

datatype defines the datatype of the variable.
param_name1 , param_name2... are unique parameter names.

General SYNTAX for OUT Parameter
CREATE [OR REPLACE] PROCEDURE proc2 (param_name OUT datatype)

General SYNTAX for IN OUT Parameter
CREATE [OR REPLACE] PROCEDURE proc3 (param_name IN OUT datatype)
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Example Program for IN and OUT Mode

<< Here code formatted , with a couple of comments added:>>
<< structure and comments in the code may help you understand... >>
SQL> DECLARE
/* DECLARATION SECTION */
a number :=10;
b number :=20;
c number;

/* The following is a declaration of a Procedure, it is not
executed until called by the execution block */
procedure findmin(x IN number , y IN number , Z OUT number) IS
BEGIN
<< BLOCK1>>
/* Procedure Execution Block - Executed when procedure is called
if x < Y then
z:=x;
else
z:=y;
end if;
END;
/* END OF DECLARATION SECTION */
BEGIN
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
<< BLOCK2>>
/* EXECUTION SECTION */
findmin(x=>a, y=>b, z=>c); or findmin(a, b,c);
DBMS_OUTPUT.PUT_LINE(c);
/* END OF EXECUTION SECTION */
END;
/

Example Program for IN OUT Mode
SQL> DECLARE
a number :=20;
procedure sqrt (x IN OUT NUMBER ) IS
BEGIN
x:=x*x;
END;
BEGIN
DBMS_OUTPUT.PUT_LINE(' BEFORE EXECUTION a is :' || a);
sqrt(a);
DBMS_OUTPUT.PUT_LINE('AFTER EXECUTION a is :' ||a );
END;
/
BEFORE EXECUTION a is :20
AFTER EXECUTION a is :400
PL/SQL procedure successfully completed.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Procedure emp_details which gives the details of the emp table :-.
SQL> create or replace procedure emp_details IS
Cursor C_cremp IS
select * From emp;
emp_rec C_cremp%rowtype;
BEGIN
for emp_rec in C_cremp
LOOP
DBMS_OUTPUT.PUT_LINE(emp_rec.eid);
DBMS_OUTPUT.PUT_LINE(emp_rec.ename);
DBMS_OUTPUT.PUT_LINE(emp_rec.equal);
DBMS_OUTPUT.PUT_LINE(emp_rec.esalary);
DBMS_OUTPUT.PUT_LINE(emp_rec.eperk);
DBMS_OUTPUT.PUT_LINE(emp_rec.ecity);
END LOOP;
END;
/
Procedure created.
How to execute a Stored Procedure?
SQL> EXECUTE [or EXEC] procedure_name;
SQL> EXECUTE emp_details;
emp_details is a stored procedure for emp table.

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Procedure Program for passing arguments
Using IN parameter in Procedures:

SQL> CREATE or REPLACE procedure emp_details
(id IN emp.eid%TYPE) IS
BEGIN
UPDATE emp
SET eperk = esalary * CASE
WHEN esalary <= 20000
THEN 0.25
WHEN esalary <= 30000
THEN 0.40
ELSE 0.5
END
WHERE eid = id
AND esalary >= 10000;
END;
/
Procedure created.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Procedure Program for passing arguments
SQL> declare
2 i_no number :=2;
3 begin
4 select eid into i_no from emp where eid=i_no;
5 emp_det(i_no);
6 DBMS_OUTPUT.PUT_LINE('input no is :' || i_no);
7 exception
8 when no_data_found THEN
9 dbms_output.put_line('no Such record');
10* end;
/
input no is :2
PL/SQL procedure successfully completed.
SQL> commit ;
Commit complete.

Record no 2 only updated in EPERK column


INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Drop a Procedure
SQL> Drop procedure <proc_name>
SQL> Drop procedure salary_details;
Procedure dropped.

FUNCTIONS
A FUNCTION is a named block of PL/SQL code and stored within the
database (which is similar to procedure). A function is must always
return a value but procedure may or may not return a value.
General SYNTAX of CREATE FUNCTION
CREATE [ OR REPLACE ] FUNCTION function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
Declaration_section
BEGIN
executable_section
EXCEPTION
exception_section
Return return_variable;
END [function_name];

Functions can be stored in the database itself, and are also referred to
as stored functions. It returns value to the host or calling environment.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


LETS check simple example :
SQL> CREATE OR REPLACE FUNCTION
mult(n1 NUMBER , n2 NUMBER)
RETURN NUMBER
AS
BEGIN
RETURN n1 * n2;
END;
/
Function created.
Call the above function from SQL:
SQL> select mult(10, 2) from dual;
MULT(10,2)
20


PONTS TO REMEMBER
FUNCTION-NAME specifies the name of the function.
[ OR REPLACE] option allows modifying an existing function.
The function must contain a return statement.
RETURN clause specifies that data type, to return from the function.

Three types of parameters that can be declared ;
IN | OUT | IN OUT
we may define above parameters , when creating a procedure or function.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

IN - The parameter can be referenced by the procedure or function. The
value of the parameter cannot be overwritten by the procedure or
function.
OUT - The parameter cannot be referenced by the procedure or
function, but the value of the parameter can be overwritten by the
procedure or function.
IN OUT - The parameter can be referenced by the procedure or function
and the value of the parameter can be overwritten by the procedure or
function.
Simple Program to display enames from emp table.
SQL> CREATE or REPLACE FUNCTION emp_disp
return varchar2 IS
emp_name varchar2(15);
BEGIN
select ename into emp_name from emp where eid='1';
return emp_name; **| ename = emp table column name **
END;
Function created.

Calling Function to get output
SQL> select emp_disp from dual;
EMP_NAME
***********
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Methods to EXECUTE the PL/SQL Function :
SQL> exec DBMS_OUTPUT.PUT_LINE(emp_disp);
<< OUTPUT >>
PL/SQL procedure successfully completed.
METHOD 1 :
SQL> DECLARE
2 emp_name VARCHAR(15);
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE(emp_disp);
5 emp_name:=emp_disp;
6 END;
7 /
<< OUTPUT >>
PL/SQL procedure successfully completed.

Program to display Total count of employees in emp table


FIG: EMP TABLE DETAILS
*********************************************************************************
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Example Program
SQL> create or replace function emp_count
return number IS
tot_count number:=0;
BEGIN
select count(*) into tot_count from emp;
return tot_count;
END;
/
Function created.

Executing the Function Vs Calling the function
SQL> exec DBMS_OUTPUT.PUT_LINE(emp_count);
5
PL/SQL procedure successfully completed.

SQL> DECLARE
N number:=0;
BEGIN
n:=emp_count();
DBMS_OUTPUT.PUT_LINE(emp_count);
end;
/
5
PL/SQL procedure successfully completed.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Function computes and returns the maximum of two values.
SQL>DECLARE
a number := 10;
b number := 20;
c number;
function maxx(x IN number , y IN number)
return number IS
c number;
BEGIN
if x > b THEN
c:=x;
else
c:=y;
end if;
return c;
END;
BEGIN
c := maxx(a,b);
DBMS_OUTPUT.PUT_LINE(c);
end;
/
20
PL/SQL procedure successfully completed.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


TRIGGER

A trigger is a program in a database that gets called each time a
row in a table is INSERTED/UPDATED/DELETED. Triggers are normally
written in PL/SQL or JAVA. It allows to check any changes are correct
before it is committed.
Prerequisites

A trigger is a program in a database that gets called each time a
row in a table is INSERTED/UPDATED/DELETED. Triggers are normally
written in PL/SQL or JAVA. It allows to check any changes are correct
before it is committed.
How the triggers are attached to the table ?

When we write a trigger, we have to give the reference of the table the
trigger has to be fired on.
Trigger Attributes

Triggers can be fired bases on following things .
CATEGORY (INSERT/UPDATE/DELETE)
- DML statement causes the trigger to fire.
TIMING (BEFORE/AFTER)
- Trigger fires before the statement is executed of after.

LEVEL (ROW or STATEMENT) A row level trigger is
fired each time the table is affected by the triggering
statement. - Ex If an UPDATE statement updates
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

multiple rows of a table, a row trigger is fired once for each
row affected by the UPDATE statement.
A statement trigger is fired once on behalf of the triggering
statement , regardless of the number of rows in the table that the
triggering statement affects.
- Ex : If a DELETE statement deletes several rows from a table, a
statement-level DELETE trigger is fired only once .

Triggers on System Events and User Events

System Events
Database startup and shutdown.
Server error message events.
User Events
User logon and logoff.
DDL statements (CREATE, ALTER, and DROP).
DML statements (INSERT, DELETE, and UPDATE).
POINTS TO NOTE

Oracle automatically executes a trigger when specified conditions
occur. When we create trigger , the database enables it automatically.
We can subsequently disable and enable a trigger with DISABLE and
ENABLE clause of ALTER TRIGGER.
SQL > alter trigger trigger-name ENABLE;
SQL > alter trigger trigger-name DISABLE;
SQL > alter table tab_name DISABLE ALL TRIGGERS;
** ( If table is having multiple triggers) **
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Types of Trigger
DDL TRIGGERS
DML TRIGGERS
INSTEAD OF TRIGGERS
SYSTEM/ DATABASE EVENT TRIGGERS
COMPOUND TRIGGERS
ROW TRIGGERS and STATEMENT TRIGGERS
DDL Triggers fire when we create, change or remove objects in a
database schema. Events : Drop, Grant, Rename, Revoke, Truncate, ..
DML Triggers fire when we insert, update or delete data from a table.
We can fire them once all changes to a table (statement trigger) or
we can fire them for each row change (row-level trigger).
COMPOUND Triggers acts as both statement and row-level triggers.
When we insert, update or delete data from a table. Please see
(ROW or STATEMENT) level explanation.
SYSTEM/DB Event Triggers fire when a system activity occurs such as
user logon and logoff , database startup/shutdown, server error msg.
INSTEAD OF Triggers provide a transparent way of modifying views that
cannot be modified directly through DML statements (INSERT, UPDATE,
and DELETE). These triggers are called INSTEAD OF triggers.
This trigger enables to stop performing a DML statement and redirect
the DML statement. INSTEAD OF triggers are activated for each row of
the view that gets modified. This method to create a trigger on a view.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
Listing Information about Triggers

USER_TRIGGERS
ALL_TRIGGERS
DBA_TRIGGERS

General Syntax for Triggers
SQL>CREATE [ OR REPLACE ] TRIGGER Trigger_name
{ BEFORE | AFTER | INSTEAD OF }
{ INSERT [or] | UPDATE [or] | DELETE }
[ OF column_names] ON Table_name
[ REFERENCING { OLD AS old , NEW AS new ]
[ FOR EACH ROW ] [ WHEN condition]]
BEGIN
PL/SQL STATEMENTS
END;

CREATE [ OR REPLACE ] TRIGGER trigger_name - This clause creates a
trigger with the given name or overwrites an existing trigger.
{ BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time
trigger get fired Ex : Before or after updating a table. It indicates the
triggering event. More than one triggering events can be used together
separated by OR keyword.
If the triggering event will be on UPDATE, DELETE INSERT, a
combination or all of these. The "ON table_name" identifies the table
for which the trigger will be created.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

[OF col_name] - This clause is used when we want to trigger an event
only when a specific column is updated. only affects an UPDATE.
[ ON Table_name] This clause identifies the name of the table or view
to which the trigger is associated.
[REFERENCING ] - This clause is used to reference the old and new
values if the data being changed, By default, they are named :OLD and
:NEW. We can refer to them as :OLD.col_name and :NEW.col_name we
cannot reference old values when inserting a record, or new values
when deleting a record, because they do not exist.
[FOR EACH ROW] This clause is used to determine whether the trigger
must fire when each row gets affected ( i.e. a Row Level Trigger) when
the entire sql statement is executed(i.e.statement level Trigger).
[ WHEN condition] - This clause is valid only for row level triggers. The
trigger is fired only for rows that satisfy the condition specified. Oracle
will test before executing a trigger.

PLSQL System Triggers
AFTER LOGON ON DATABASE
BEFORE LOGOFF ON DATABASE
AFTER STARTUP ON DATABASE
BEFORE SHUTDOWN ON DATABASE
AFTER SERVERERROR ON DATABASE
If an oracle database instance shuts down abnormally SHUTDOWN ABORT,
this event will not be fired.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Syntax for System Triggers

SQL> CREATE [ OR REPLACE ] TRIGGER trigger_name
{ BEFORE | AFTER }
{ SERVERERROR | LOGON | LOGOFF | STARTUP | SHUTDOWN }
ON DATABASE
BEGIN
. .. ..
PL/SQL Statements
END ;

Creating Logging Records Automatically
SQL> create table logtab(username varchar2(15) , logdate date);
Table created.

SQL> create trigger tr_userlog
2 after logon ON database
3 begin
4 insert into logtab(userid , logdate) values(user , sysdate);
5 end;
6 /
Trigger created
SQL> conn sam/sam
Connected.
SQL>conn /as sysdba
Conncted.

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
SQL> select * from logtab;
USERID LOGDATE
SAM 15-MAY-13
*** **-***-**

Example Trigger Program for user LOGIN/LOGOUT details

SQL> desc user_login
Name Null? Type
USERNAME VARCHAR2(30)
ISDBA VARCHAR2(20)
EXTERNAL_NAME VARCHAR2(30)
AUTHENTICATION_TYPE VARCHAR2(30)
HOST VARCHAR2(20)
SESSIONID NUMBER
LOGIN_DATE DATE
LOGIN_TIME VARCHAR2(15)

SQL> create or replace trigger tri_login
2 AFTER LOGON ON DATABASE
3 BEGIN
4 Insert into user_login(username, isdba, external_name, AUTH_TYPE,
5 HOST,SESSION_ID,LOGIN_DATE,login_time) SELECT
6 SYS_CONTEXT ('USERENV', 'SESSION_USER'),
7 SYS_CONTEXT ('USERENV', 'ISDBA'),
8 SYS_CONTEXT ('USERENV', 'EXTERNAL_NAME'),
9 SYS_CONTEXT ('USERENV', 'AUTHENTICATION_TYPE'),
10 SYS_CONTEXT ('USERENV', 'HOST'),
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
11 SYS_CONTEXT ('USERENV','SESSIONID'),
12 sysdate, to_char(sysdate, 'HH24:MM:SS') from dual;
13 end ;
14 /
Trigger created.



EX : Program to illustrate the use of BEFORE TRIGGER

SQL> create table emp
2 (Eid number , Ename varchar2(15) ,
3 City varchar2(15), salary number , Perks number);
SQL> select * From emp;
EID ENAME CITY SALARY PERKS
1 Red Chennai 15000 680
2 Carig Mumbai 18000 1020
3 evens Calacutta 22000 420
4 smith Delhi 12000 378
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

SQL> CREATE OR REPLACE TRIGGER TRI_CAPS
2 BEFORE INSERT OR UPDATE ON emp
3 for each row
4 BEGIN
5 :NEW.Ename :=UPPER(:NEW.Ename);
6 end;
7 /
Trigger created.

SQL> update emp set ename='evEns' where ename='evens';
1 row updated.

SQL> select * from emp where eid=3 or eid=4;

EID ENAME CITY SALARY PERKS
3 EVENS Calacutta 22000 420
4 smith Delhi 12000 378
This trigger will always enter the name of employee in capital letters.

Example for after statement level Trigger

SQL> desc emp;
Name Null? Type
EID NUMBER
ENAME VARCHAR2(30)
ESAL_ACCNO VARCHAR2(10)
ESAL NUMBER
PERKS NUMBER
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

SQL> desc EMP_AUDTING;
Name Null? Type
USER_NAME VARCHAR2(15)
ACTION_DATE DATE
ACTION_INFO VARCHAR2(100) 6 end;

Program for whenever an insert, update, or delete operation occurs on
the emp table, a row is added to the emp_auditing table and recording the
user, date and action.
Trigger Program to fire any INSERT/UPDATE/DELETE

SQL> Create or replace trigger tri_emp
2 after insert or update or delete on emp
3 declare
4 action varchar2(200);
5 BEGIN
6 IF INSERTING THEN
7 action := 'added employee';
8 ELSIF UPDATING THEN
9 action := 'updated employee';
10 ELSIF DELETING THEN
11 action := 'deleted employee';
12 end if;
13 insert into emp_auditing values(user, sysdate, action);
14 end;
15 /
Trigger created.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

SQL> select * From emp;
EID ENAME ESAL_ACCNO ESAL PERKS
1020 sam Az25841260 25000 1090
1030 roselin BX25421412 40000 6800
1040 red Ax25411541 20000 2000
1060 carig BS25412684 30000 2800

USER is "HR"
SQL> update rose.emp set ename='rose' where ename='roselin';
1 row updated.
USER is "SYS"
SQL>insert into rose.emp values(1000,'san','cx65424381',45000,3200);
1 row created.
SQL>insert into rose.emp values(1010,'JOE','Bx37142120',28000 ,1060);
1 row created.
USER is "SAM"
SQL>delete from rose.emp where ename='sandya' or ename='JOE';
2 rows deleted.
USER is "ROSE"
SQL> select * from emp_audting;
USER_NAME ACTION_DA ACTION_TEXT
HR 24-JUN-13 updated employee
SYS 24-JUN-13 added employee
SYS 24-JUN-13 added employee
SAM 24-JUN-13 deleted employee
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Trigger Program prevents us from updating DOB
SQL> desc emp;
Name Null? Type
EID NOT NULL NUMBER
ENAME VARCHAR2(15)
SALARY NUMBER
PERKS NUMBER
DOB VARCHAR2(15)

SQL> create or replace trigger tri_dob
2 BEFORE UPDATE OF DOB ON EMP
3 FOR EACH ROW
4 BEGIN
5 RAISE_APPLICATION_ERROR(-20000 ,'CANNOT CHANGE DOB');
6 END;
7 /
Trigger created.

SQL> update emp set DOB='15.06.1984' where eid='1';
update emp set DOB='15.06.1984' where eid='1'
*ERROR at line 1:
ORA-20000: CANNOT CHANGE DOB
ORA-06512: at "SAM.TRI_DOB", line 2
ORA-04088: error during execution of trigger 'SAM.TRI_DOB'
Should also notice the error code of ORA-20000. This is our -20000
parameter to RAISE APPLICATION ERROR.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Example Program for tracing information in SECRET TABLE
SQL> select * from emp;
EID ENAME CITY SALARY PERKS DOB
1 RED Chennai 15000 1440 12.08.1985
2 CARIG Mumbai 18000 820 20.06.1988
3 EVENS Calacutta 22000 420 01.08.1984
4 SMITH Delhi 12000 695 06.12.1985

Creating Tracking Table

SQL> create table user_track (eid number,
ename varchar2(15) , old_Perks number, new_perks number,
uname varchar2(15), action_date_time varchar2(10));
Table created.

Trigger Program for tracing User_nmae/ Action date and time
SQL> create or replace trigger tri_track
2 After UPDATE ON EMP
3 FOR EACH ROW
4 BEGIN
5 insert into user_track( EID,ENAME,OLD_PERKS, NEW_PERKS ,
6 UNAME, ACTION_DATE,ACTION_TIME) values
7 (:old.eid, :old.ename , :old.perks, :new.perks, user,
8 to_char(sysdate, 'MM-DD-RRRR | HH24:MI:SS'));
8 end;
9 /
Trigger created.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

SQL> USER is "SYS"
SQL> update sam.emp set perks=990 where eid='1';
1 row updated.
SQL> update sam.emp set perks=640 where eid='2';
1 row updated.
SQL> update sam.emp set perks=860 where eid='3';
1 row updated.
SQL> update sam.emp set perks=950 where eid='4';
1 row updated.
Commit complete.

Checking user_track (secret table)
SQL> show user;
USER is "SAM"

Here , secret table (user_track) has tracked all updated informations from the
emp table. This is example for row level trigger.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

ORA-04082: NEW or OLD references not allowed in table level triggers



Row level triggers has the option to refer old and new values not the
statement level triggers. A DML trigger by default, is a statement level. When
we use "FOR EACH ROW" clause it turns into a row level trigger.
Cannot reference :old and :new column values in a statement level

Interpreting TR_TRACK TRIGGER
TRIGGER_TYPE After each row
TRIGGERING_EVENT Update
BASE_OBJECT_TYPE Table
STATUS Enabled
REFERENCING_NAMES Referencing new as new old as old
ACTION_TYPE PL/SQL
DESCRIPTION Tr_track, AFTER UPDATE ON EMP , FOR EACH ROW
TRIGGER_BODY BEGIN insert into user_track (NO,NAME,OLD_PERKS
,NEW_PERKS,UNAME,ACTION_DT_TIME)
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Trigger Maintenance - to enable or disable
SQL> alter trigger trigger_name enable;
SQL> alter table tab_name enable all triggers;
SQL> alter trigger trigger_name disable;
SQL> alter table tab_name disable all triggers;

To find trigger program errors
SQL> show errors trigger trigger_name;

Recompiling
SQL> alter trigger trigger_name compile;

Detect broken code
SQL> select object_name from dba_objects where status = 'INVALID';

Useful Views
DBA_TRIGGERS USER_TRIGGERS



















INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


POINTS TO REMEMBER :


A trigger is a pl/sql block structure (procedure) which is fired when a DML
statements like Insert, Delete, Update is executed on a database table.
Triggers are associated with tables, and are called whenever a certain
modication (event) occurs i.e. a trigger is triggered automatically when an
associated DML statement is executed.

General structure of Trigger

SQL> CREATE [ OR REPLACE ] TRIGGER trigger_name
BEFORE (or AFTER )
INSERT OR UPDATE [ OF COLUMNS ] OR DELETE
ON table_name
[ FOR EACH ROW [ WHEN ( condition)]]
BEGIN
... PL/SQL block
END;

The PL/SQL block (between BEGIN and END) is a usual code block where we
can place PL/SQL commands. Triggers could be defined on the table, view,
schema, or database with which the event is associated.


A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON/LOGOFF, STARTUP/SHUTDOWN)

Statement Vs Row
ROW LEVEL TRIGGER STATEMENT LEVEL TRIGGER
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

A DML trigger by default, is a statement level trigger. When we use "FOR
EACH ROW", we turn it into a row level trigger.

Who performs an update that will affect 10 rows - A statement level trigger
will fire once and a row level trigger will fire 10 times. Statement level triggers
cannot access row level column data.


Ex for ROW LEVEL TRIGGER Vs STATEMENT LEVEL TRIGGER

USER is "ROSE"
SQL> select * from emp;
NO NAME SALARY PERKS DOB
1 rose 10000 296 20-05-85
2 sona 20000 455 12-08-88
3 sony 30000 890 28-02-87
4 sam 40000 995 06-03-85

Creating table for to trace ROW_LEVEL

SQL> create table row_level ( no number, name varchar2(15),
2 uname varchar2(15), ACTION_DATE_TIME varchar2(15));
Table created.

Example Program
SQL> create or replace trigger tri_rowlevel
2 AFTER UPDATE ON EMP
3 FOR EACH ROW
4 BEGIN
5 insert into row_level(no , name , uname , ACTION_DATE_TIME ) values
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
**************************************************
6 (:old.no,:old.name,user,to_char(sysdate,'MM-DD-RRRR|HH24:MI:SS));
7 end;
8 /
Trigger created.
Only row level triggers have access to the "old" and "new" values of any
particular row. So I do NOT include old "old" and "new" values for
following statement level trigger. Lets see .


Creating table for to trace STATEMENT_LEVEL

SQL> create table stat_level uname varchar2(15),
ACTION_DATE_TIME varchar2(25));
Table created.
SQL> create or replace trigger tri_statlevel
2 AFTER UPDATE ON EMP
3 BEGIN
4 insert into stat_level(uname , ACTION_DATE_TIME ) values
5 (user , to_char(sysdate ,'MM-DD-RRRR | HH24:MI:SS'));
6 end;
7 /
Trigger created.

Updating Records from SYS user
USER is "SYS"
SQL> update rose.emp set perks=1200 where no >=2;
3 rows updated.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
SQL> commit;
Commit complete.

If FOR EACH ROW is not specified, the trigger is executed at a statement level.
Lets see following scrren s hot. How both triggers are acted.


An instead of triggers is built on a view.
A trigger cannot include COMMIT, SAVEPOINT and ROLLBACK.
BEFORE or AFTER CREATE trigger is fired when a schema object is created.
BEFORE or AFTER ALTER trigger is fired when a schema object is altered.
BEFORE or AFTER DROP trigger is fired when a schema object is dropped.

Triggers Advantages

Provide auditing
Prevent invalid transactions.
Publish information about database events, user events, and SQL statements
to subscribing applications.

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


PACKAGES***********************
PACKAGE is a group of procedures , function, types , cursors, exceptions
etc .. A package is compiled and stored in the database and it can be
used by many applications.
Packages can be compiled and stored in an Oracle database,. When we
call a packaged subprogram for the first time, the whole package is
loaded into memory.
A Package Exists in Two Parts

PACKAGE SPECIFICATION PACKAGE BODY
To create a Package specification , use CREATE PACKAGE .
To create a Package body , use CREATE PACKAGE.
Usually Package specification are visible and accessible to applications.
PACKAGE SPECIFICATION
The specification is the interface to the package.
It contains all information about the content of the package, but excludes
the logical code for the subprograms. i.e. (DECLARES the types, variables,
constants, exceptions, cursors, and subprograms that can be referenced
from outside the package ).
Public Objects Vs Private Objects

All objects placed in the specification are called PUBLIC objects. Any
subprogram not in the package specification but coded in the package body is
called a PRIVATE object. Lets see .
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


Snippet shows for Public Objects Vs Private Objects
SQL> create package pkg as
procedure proc1;
procedure proc2;
end;

Creating a Package body

SQL> create package body pkg as
procedure proc0 as
...
Procedure proc1 as
...
Procedure proc2 as
...
end;
In this package proc0 is private. It can only be called from within the package.

Package body

Package body contains the actual code. that is , (collection of related
procedures, stored functions, and other program objects stored together
in the database. The package body defines these objects

The body holds implementation details of public procedures and private
procedures, functions etc. which are hidden from code outside the
package. Private units units are only accessible within the scope of the
package itself.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Constructs listed in package body but not in package specification are
private and accessible only to other constructs in the same package.
Snippet shows a Package specification for single Procedure
SQL>CREATE OR REPLACE PACKAGE PKG_UTIL IS
PROCEDURE P_ENAME(PVAR VARCHAR2);
END;
/
Package created.


Snippet shows the Package body declaration for the PKG _UTIL
SQL> CREATE OR REPLACE PACKAGE BODY PKG _UTIL IS
PROCEDURE P_ENAME(PVAR VARCHAR2) IS
BEGIN
DBMS_OUTPUT.PUT_LINE(P_VAR);
END;
END PKG_UTIL;
/
Package body created.

Executing the Code :
SQL> EXEC PKG_UTIL.P_ENAME('THIS IS PLSQL PACKAGE !');
THIS IS PLSQL PACKAGE !
PL/SQL procedure successfully completed
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Public Object Vs Private Object

In this program subprogram not in the package specification , but coded
in the Package body . Lets see how it works .
SCOTT> CREATE OR REPLACE PACKAGE test_pk
AS
FUNCTION hello
RETURN VARCHAR2;
END test_pk;
/
Package created.

SCOTT>CREATE OR REPLACE PACKAGE BODY test_pk
AS FUNCTION who RETURN VARCHAR2
IS
BEGIN
RETURN 'World';
END who;
FUNCTION hello
RETURN VARCHAR2
IS
BEGIN
RETURN 'Hello, ' || who || '!';
15 END hello;
16 END test_pk;
/
Package body created.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu


The function who is defined only in the package body, so it can only be called
from inside the package. The function hello is declared in the package spec,
so we can call it from outside the package.
SCOTT>select test_pk.hello as test_pk_hello from dual;
TEST_PK_HELLO
Hello, World!
SCOTT> select test_pk.who as test_pk_who from dual;
SELECT test_pk.who AS test_pk_who from dual
* ERROR at line 1:
ORA-00904: "TEST_PK"."WHO": invalid identifier

Example Program for Package Specification

Snippet shows a Package specification for Procedure. findsal
ROSE>create or replace package pkgsal as
Procedure findsal(e_id emp.eid%type) ;
end pkgsal;
/
Package created.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Snippet shows the package body declaration for pkgsal
ROSE> create or replace package body pkgsal as
Procedure findsal(e_id emp.eid%type)
IS
e_sal emp.esalary%type;
BEGIN
select esalary into e_sal from emp where eid=e_id;
DBMS_OUTPUT.PUT_LINE(e_sal);
End findsal;
end pkgsal;
/
Package body created.

PACKAGE ELEMENTS
SQL> PACKAGE_NAME.ELEMENT_NAME
SQL> PKGSAL.FINDSAL

Program uses the find_sal procedure of the pkgsal package:
ROSE>DECLARE
v_id emp.eid%type := &eid;
BEGIN
pkgsal.findsal(v_id);
END;
/
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
*****************************************************************************
Enter value for eid: 1
old 2: v_id emp.eid%type := &eid;
new 2: v_id emp.eid%type := 1;
12000

AS i said , Packages can be compiled and stored in an Oracle database.

SQL> CREATE OR REPLACE PACKAGE pack1 IS
V1 NUMBER:=1;
Procedure proc1;
End pack1;
/
Package created.
SCOTT>CREATE OR REPLACE PACKAGE BODY PACK1 IS
v2 number:=2;
procedure proc1 is
v3 number :=3;
BEGIN
v1:=v1+1;
v2:=v2+2;
v3:=v3+3;
DBMS_OUTPUT.PUT_LINE(v1);
DBMS_OUTPUT.PUT_LINE(v2);
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu
DBMS_OUTPUT.PUT_LINE(v3);
End proc1;
End pack1;
/
Package body created.
SQL> Execute pack1.proc 1; << do it 3 times >>
1
st
2
nd
3
rd

V1 2 3 4
V2 4 6 8
V3 6 6 6
So when we call a packaged subprogram for the first time, the whole
package is loaded into memory.
RELATED VIEWS
dba_procedures user_procedures all_procedures
dba_source user_source user_objects

REMOVING PACKAGES
REMOVING PACKAGE SPECIFICATION and BODY ;
SQL > DROP PACKAGE PACKAGE_NAME
SQL > DROP PACKAGE PACK1;

TO REMOVE PACKAGE BODY
SQL > DROP PACKAGE BODY PACKAGE_NAME ;
SQL > DROP PACKAGE BODY PACK1 ;
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

REMOVING PACKAGES
REMOVING PACKAGE SPECIFICATION and BODY ;
ROSE> select object_name , procedure_name from user_procedures;
OBJECT_NAME PROCEDURE_NAME
PACK1 PROC1
PKGSAL FINDSAL

PLSQL - POINTS TO REMEMBER :

Three parts to a PL/SQL program:
the declaration area, the execution area, and the exception handler.

PL/SQL Block Types: (Anonymous blocks Vs Named blocks )


Anonymous Block : It s unnamed blocks that cannot be stored in database
and executed only once. Named Blocks : A PL/SQL block with a name.

How do we Identify named block ?

In oracle ,users can find any information regarding 'named objects'
(procedures, functions, packages, tables, views, triggers, constraints, indexes
etc., etc., etc.) . Lets see how to find named block.

SYS>select OWNER, OBJECT_NAME, OBJECT_TYPE, CREATED, STATUS from
dba_objects where OBJECT_NAME='PKGSAL';

OWNER OBJECT_NAME OBJECT_TYPE CREATED STATUS

ROSE PKGSAL PACKAGE 10-AUG-13 VALID
ROSE PKGSAL PACKAGE BODY 10-AUG-13 VALID

INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

Query to check what code is in the Package
SQL> select text from user_source where name = PKGSAL;
Both specification and package body will be shown.

Please visit following link. - (Developing Stored Sub-Programs)

http://docs.oracle.com/cd/E11882_01/appdev.112/e10766/tdddg_subprograms.htm#CIHDFDJG


PL/SQL SUPPLIED PACKAGES
Oracle supplies many PL/SQL packages with the oracle server to extend
database functionality and provide PL/SQL access to SQL features.
Oracle provides built-in DBMS Packages. During installation of oracle several
built in DBMS packages are included (to extend database functionality).

The built-in packages are installed by the scripts catproc.sql and
catalog.sql located in the directory $ORACLE_HOME/rdbms/admin.
Most of the packages are created by running catproc.sql.

SOME SUPPLIED PL/SQL PACKAGES

DBMS_ALERT
Supports asynchronous notification of db events.
DBMS_JOB
Schedules and manages jobs in the job queue.
DBMS_METADATA
Extracts db object definitions from the dictionary.
DBMS_OUTPUT
Prints output from PL/SQL program to buffer.
DBMS_PIPE
which enables messages to be sent between sessions.
DBMS_REDEFINITION
performs an online reorganization of tables.
DBMS_SCHEDULER Scheduling functions are callable from PL/SQL program.
UTL_FILE
Enables users PL/SQL programs to read and write OS files.
INTRODUCTION TO PL/SQL BASICS

Exploring the Oracle DBA Technology by Gunasekaran ,Thiyagu

POINTS TO NOTE :
DBMS_JOB package is replaced by the DBMS_SCHEDULER package.
DBMS_JOB package should not be used any more, because is could not
exist in a future version of Oracle.
Oracle Supplied PL/SQL Packages List

http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/intro.htm#BABGEDBH

Introduction to Oracle Supplied Packages

http://docs.oracle.com/cd/E11882_01/appdev.112/e25788/intro.htm#i1017863

You might also like