PL SQL

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

PL SQL

What is ANONYMOUS BLOCK / PL SQL BLOCK?


A block without a name is an anonymous block. Anonymous blocks is not saved in
the oracle database server. It is just for one time use. Anonymous blocks can be useful for
testing purpose.
PL/SQL block structure:
DECLARE (OPTIONAL)

BEGIN (MANDATORY)

EXECEPTION (OPTIONAL)

END (MANDATORY)

How to display the output?


Set server output on
PL/SQL COMMENTS: PL/SQL Supports Single line and Multi-line Comments.
Comments are ignored by the PL/SQL compiler.
SINGLE LINE COMMENTS: - Start with the delimiter ( _ _ ) (double typhon)
MULTI-LINE COMMENTS: - Enclosed /* and */
PL/SQL Data Types
It stores only one value
1. NUMBER DATA TYPE
2. BOOLEAN DATA TYPE
3. CHARACTER DATA TYPE
4. DATE DATA TYPE
5. LOB – (Large Object Data Type).

1) NUMBER DATA TYPE:


NUMBER
PLS_INTEGER
BINARY_INTEGER

2) BOOLEAN DATA TYPE:


TRUE
FALSE
NULL
3) CHARACTER DATA TYPE:
CHAR (Size Minimum Length is 1 Byte Maximum Length is 32767 bytes)
VARCHAR2 (Size Minimum Length is 1 Byte Maximum Length is 32767
bytes)
LONG
LONG RAW
ROW ID
RAW
4) DATE DATA TYPE:
Format – DD-MM-YY
Maximum bytes 7 bytes
5) Lob (large object data type)
Large object (LOB) data type refers to large data items such as Text, Graphic,
Images, Video Clips and Sound Wave forms.

Data Type Size


B FILE 4 GB
B LOB 8 GB TO 128 TB
CLOB 8 GB TO 128 TB
NCLOB (National character large 8 GB TO 128 TB
objects)

CONTROL STATEMENT
1) CONDITIONAL CONTROL:

Syntax: If <condition> Then <Action>


Elseif <condition> Then <Action>
Else <action>
End if;
2) CASE STATEMENT:

Syntax: CASE [Expression]


When Condition1 Then Result1
When Condition2 Then Result2
-------------------------------------
-------------------------------------
When condition N Then Result N
Else Result;
End;

TYPES OF PL/SQL LOOPS


Loops are used to repeat the Execution of one or more Statement for
Specified/ more number of times.
There are four types of loops are there
1) SIMPLE LOOP
2) WHILE LOOP
3) FOR LOOP
4) CURSER FOR LOOP
1) SIMPLE LOOP: Basic loop structure encloses sequence of statement in between the
loop and end loop.
Syntax: Loop
Statement;
End loop;
2) WHILE LOOP: Here body of the loop statement are executed repeatedly until
condition is False. In “While loop” When ever condition is true then only loop body is
executed.
Syntax: While [Condition]
Loop
Statement;
End Loop;
3) FOR LOOP: In oracle, the for loop allows you to Execute code Repeatedly for a
fixed Number of times.
Syntax: For variable IN Initial value . . Final value
Loop
Statement;
End loop;

Initial Value: Start Integer Value


Final Value: End integer Value
4) FOR LOOP REVERS:
Syntax: For variable IN REVERS Initial value . . Final value
Loop
Statement;
End loop;
GOTO STATEMENT

The GOTO statement transfers control to a labelled block or statement. If


a GOTO statement exits a cursor FOR LOOP statement prematurely, the cursor closes.

Syntax: Goto Label_Name

-----------------------
-----------------------
<< Label_Name>>
Statement;

PL/SQL VARIABLES
If needs to declare the variable the variable first in the declaration section of a
PL/SQL Block before using it. By default, variable names are not case section a
reserved PL/SQL keyboard cannot be used as a Variable Name.
Syntax: Variable_Name [constant] Data type [Not Null]
: = [Default initial_value]

CURSOR
Cursor is a Private SQL Area. A cursor is a pointer to the context area used by
the Oracle Engine for Executing SQL Statement.
In PL/SQL Database systems Having two types of Cursors.
1) IMPLICIT CURSOR
2) EXPLICIT CURSOR
1) IMPLICIT CURSORS: The cursors which is Automatically Created, Maintained
and Closed by the oracle engine While Execution of any DML Commands Like
‘Delete, Update, insert’ are called Implicit cursor. Implicit cursors ware controlled by
oracle sever.
Implicit Cursor Having 4 Attributes:
ATTRIBUTES DESCRIPTION
SQL % FOUND It returns values is true, if DML Statements
Like insert, update, delete effect at least one
row or more rows or select into statement
returned one rows otherwise it returns False
SQL % NOT FOUND It returns value is True. If DML statement
like insert, update, delete effect no rows of a
select into statement returns no rows
otherwise if returns false. if is just operate
of SQL % found
SQL % IS OPEN It always returns false for implicit cursor.
Because the SQL cursor is automatically
closed after existing it’s associates SQL
statement.
SQL % ROW COUNT It returns the No. of rows affected by DML
statement’s like insert, update, delete or
returned by a select in to statement.

2) EXPLICIT CURSOR: For SQL Statements returns multiple records is called


explicit cursor and also this is a record-by-record process. Explicit cursor memory
area is called also active set area.
Life Cycle of the Explicit Cursor:
Declaring cursor
Opening cursor
Fetching data from the cursor
Closing the cursor
Syntax: Declare
Cursor <cursor_name> IS <select statement>
<cursor_variable declaration>
Begin
Open <cursor_name>;
Fetch <cursor_name> INTO <cursor_variable>
--------------------------------------------------------
--------------------------------------------------------
Close <cursor_name>
End; /

Cursor Attributes:
CURSOR ATTRIBUTES DESCRIPTION
CURSOR NAME % FOUND It returns the ‘TRUE’. if fetched at least
one record successfully, else it will
return FALSE
CURSOR NAME % NOT FOUND It will return ‘TRUE’. If fetched
operations could not able to fetch any
record.
CURSOR NAME % IS OPEN It returns ‘TRUE’. If the given cursor is
already open, else it it returns FALSE
CURSOR NAME % ROW COUNT It returns the number of records Fetched
from the cursor.

CURSOR FOR LOOP


The cursor variable, opening of cursor, fetching and closing of the cursor will
be done implicitly by for loop.
Syntax: Declare
Cursor <cursor_name> IS <select statement>;
Begin
For Variable_Name IN <cursor_name>
Loop
---------------------
---------------------
End Loop;
End;

REF CURSOR/ CURSOR VARIABLE/ DYNAMIC CURSOR

Ref cursor are used to execute No.of select statement dynamically for a single
active set area ref cursor.
(or)
This is a user defined type which is used to process multiple records and also
this is a record-by-record process.
Types of Refcursor: 1) Strong Refcursor
2)Weak Refcursor
1) STRONG REFCURSOR: This is a Refcursor which have return type, where as
weak Refcursor has no return type.
Syntax: (strong ref cursor)
Type TypeName is Refcursor return record type data type;
Variable columnname TypeName;
Strong ref cursor variable name
Syntax: (weak ref cursor)
Type TypeName is Refcursor;
Variable name TypeName;
Weak Refcursor variable name

SYS_REFCURSOR

Sys-Refcursor is a weak Refcursor type.


Syntax: Refcursor variable name Sys-Refcursor;

EXCEPTIONS

Exception is an Error Occurred in runtime.


Types of exceptions:
1) PRE-DEFINED EXCEPTION
2) USER DEFINED EXCEPTION
3) UNNAMED EXCEPTION

1) PRE-DEFINED EXCEPTION: Whenever the runtime error is occurred use


corresponding pre-defined exception in exception selection of PL/SQL Block.
Syntax: When pre-defined exception name1 then
Statement:
When pre-defined exception name2 then
Statement:
-------------------------------------------------
-------------------------------------------------
When others then
Statement;
PRE-DEFIND EXCEPTION NAMES:
I. NO_DATA_FOUND
II. TOO_MANY_ROWS
III. ZERO_DIVIDE
IV. DUP-VAL_ON_INDEX(DUP-> DUPLICATE)
V. INVALID _CURSOR
VI. CURSOR_ALREADY_OPEN
VII. INVALID_NUMBER
VIII. VALUE_ERROR
IX. OTHERS
2) USER DEFIND EXCEPTION: In oracle we can also create our own exception
name and raised when even necessary those exception explicitly this type of exception
are also called as User Defined Exception.
In all database if we want to raise exception based on client business rule
then only, we are using user defined exception.
Handling user defined exception in oracle:
Step1: declare
Syntax: user defined exception name;
Step2: Raise
Syntax: raise user defined exception name;
Step3: Handling user defined exception
Syntax: When user defined exception name1 then
statement;
When user defined exception name2 then
statement;
--------------------------------------------------------------
--------------------------------------------------------------
When others then
statement;

3) UNNAMED EXCEPTION: In this method we are creating our own exception name
and they associate this exception name with appropriate error number by using
exception _INIT function this function accepts two parameters.
Syntax: Pragma Exception_INIT (User define Exception name, Error number);

RISE_APPLICATION_ERROR (): Raise_Application_Error is a Pre-defined


Procedure available in DBMS_Standard package.
In oracle if we want to display user defined exception message in more
descriptive from then only, we are using this procedure i.e., if we want to display
user-defined exception message as same as oracle error display format then we must
use Raise_Application_Error procedure.
This procedure accepts two parameters.
Syntax: Raise_Application_Error (error number, message);
(-20000 to 20999 , up to 512 character)

ERROR TRAPPING FUNCTION: Oracle having two pre_defind error


trapping functions which is used to return error number and error message.
Those are:
1. SQLCODE
2. SQLERRM

SUB-PROGRAMS

Sub-programs are named PL/SQL block.


a) PROCEDURE [mayor may not return value]
b) FUNCTION [must return a value]
a) PROCEDURE: Procedure is a named PL/SQL block which is used to solve
particular task, and procedure may or may not return value. Generally, procedures are
used to improves performance of the application because procedures internally having
one time compilation.
In oracle when ever we are using create or replace keyword in front of the
procedure, then those procedures are automatically permanently stored in data base
that’s why these procedures are called as “Store Procedure”.

Syntax: Create or Replace Procedures procedurename [formal parameter]


IS/AS
Variable declarations, cursors, user defined exceptions
Begin
==========
==========
[Exception]
==========
End;
Executing a procedure:
Method 1:
Procedure parameter:
Autonomous transaction:
b) FUNCTION:
Syntax:
Executing a function:

Deference between PROCEDURE AND FUNCTION


PROCEDURE FUNCTION
Procedure performs specific task Function performs the calculations
Procedure may OR may not return the Function must return the value
value
Procedure cannot be executed in Select Function can Executed or Call using
Statement. We can be Executed in select statement but it must not contain
anonymous block (or) Exec commend. Out OR Inout parameter
It does not contain return clause in It must contain return clause in header
header section. section.

PACKAGES
Package is a database objects, which encapsulates procedures, function, cursor, global
variables, constants types into single unit.
Packages also having two parts:
1) Package Specification
2) Package Body

1) PACKAGE SPECIFICATION: In package specification we are declaring Global


variable, Constant, Types, Cursor, Procedures, Functions.
Syntax: create or replace package package_name
Is/As
Global variable declarations, Constant declaration, Cursor Declaration, Types
Declaration, Procedure Declaration, Function Declaration
End;
2) PACKAGE BODY: In package body are we are implementing procedures and
functions.
Syntax: create or replace package body package_name
Is/As
Procedure Implementation;
Function Implementation;
End[package_name];

Executing package Sub-Programs:


1) CALLING PACKAGE PROCEDURE:
Method 1: (Using Select Statement)
Syntax: Exec
Package_name.Procedure_name(Actual parameters);
Method 2: (Using Anonymous Block)
Syntax: Begin
Package_name.Procedure_name(Actual parameters);
End;

2) CALLING PACKAGE FUNCTION:


Method 1: (Using Select Statement)
Syntax: Select Package_name. Function_name(Actual parameters) from dual;
Method 2: (Using Anonymous Block)
Syntax: Declare
Var_name Data type
Begin
Var_name:= Package_name.Functional_name(Actual parameters);
End;

COLLECTIONS
Collections are most useful, when a large data of the same data type need to be
processed.
Types of Collections:
1) INDEX BY TABLE (OR) PL/SQL TABLE (OR) ASSOCIATIVE ARRAY
Syntax: Type type_name is table of data_type(size) index by Binary Integer ;
(OR)
Type type_name is table of data_type index by varchar2(10);
Variable name type_name;
2) NESTED TABLE
Syntax: Type type_name is table of datatype
Variable name type_name: = type_name ()

3) VARRAY
Syntax: Type Varray_type_name VARRY(N) of (element type);
Variable name type_name: = type_name ()

Difference between INDEX BY TABLE, NESTED TABLE, VARRAY;

INDEX BY TABLE NESTED TABLE VARRAY


Index by table is an unbounded It is unbounded table Varray is a bounded tale which
table having key-value pairs stores 2GB data
Index by table is not allowed to Nested tables are allowed to store We can also store Varray
store permanently in oracle data permanently in oracle data base permanently into database by
base. by using SQL SQL
We cannot add (or) remove We can add(or) remove index by We can add (or) remove indexes
indexes using extended Trim Collection by using extend Trim collection
method methods
Here indexes are either integer (or) Here always indexes are integer Here always indexes are integer
characters and also +ve, -ve starts with 1 starts with 1
numbers
Index by table having exists first, Nested tables having exists first, Varray having exists, Limit
last, prior, count, delete (index), last, prior, next, extends count, extend Trim, first, last prior next,
delete (one index, another index) delete (index), delete (one index, count, Delete collection Method
delete collection method. another index) delete collection
method.

Collection methods: PL/SQL provides the built-in collection method that make collection
easier to use.
1) EXISTS(N): - Syntax: <collection name> exists (element .Position)
2) COUNT: - Syntax: <collection name> .Count
3) LIMIT: - Syntax: <collection name> .Limit
4) FIRST: - Syntax: <collection name> .First
5) LAST: - Syntax: <collection name> .Last
6) PRIOR(N): - Syntax: <collection name> .Prior(n)
7) NEXT(N): - Syntax: <collection name> .Next(n)
8) EXTEND: - Syntax: <collection name> .Extend(n)
9) EXTEND(N): - Syntax: <collection name> .Extend(n)
10) EXTEND (N, I): - Syntax: <collection name> .Extend(n, i)
11) TRIM: - Syntax: <collection name> .Trim
12) TRIM(N): - Syntax: <collection name> .Trim(n)
13) DELETE: - Syntax: <collection name> .Delete
14) DELETE(N): - Syntax: <collection name> .Delete(n)
15) DELECTE (M, N): - Syntax: <collection name> .Delete(m,n)

TRIGGERS
Triggers is a named PL/SQL data base object. It will automatically be invoked
whenever DML operation performed against table (or) views.
Types Triggers.
1) STATEMENT LEVEL TRIGGER: In STATEMENT level trigger body is executed
only once for DML statement.

Before Statement Level After Statement Level


Before Update After Update
Before Insert After Insert
Before Delete After Delete

2) ROW LEVEL TRIGGER: In ROW level trigger, trigger body is executed by each
row for DML statement.

Before Row Level After Row Level


Before Update After Update
Before Insert After Insert
Before Delete After Delete

3) INSTEAD OF TIGGER
4) COMPOUND TRIGGER: In oracle 11G The concept of compound trigger was
introduced A compound trigger is a single trigger on a table that enable you to specify
actions for each of four timing points.
1) Before that firing statement
2) Before each row that the firing statement affects
3) After each row that the firing statement affects
4) After the firing statement
With the compound trigger both the statement level and row level action can be put
up in single trigger.
Syntax: create or replace trigger compound_trigger_name for insert/update/delete of column
on table compound trigger.
5) MUTATING ERROR: Mutating trigger error occurred when trigger referees the
table that owns the trigger resulting in the ORA-04091-Table-Mutating
Syntax: create or replace trigger trigger_name before/after/insert/update/delete on
table_name
For each row

When condition
Declare
Begin
Exception
End;/

Trigger Executing Order


1) Before Statement Level
2) Before Row Level
3) After Row Level
4) After Statement Level

UTL_FILE PACKAGE

This package is used to right data into the flat file and also read data from flat file. If
we want to wright data into file then we using “PUTF” (procedure). If you want to read data
from the file the we are using, Get_Line procedure.
Create Directory: Before we are using UTL_FILE Package we must create directory.
Syntax: create or replace directory directory_name as ‘path’;
Grant create any directory to scott;
Grant Read, right on directory directory_name : to user name;
Writing Data in to flat file:
Step 1: Before we are opening the file, we must create a file pointer variable by using
‘File_Type’ from “UTL_FIlE” Package in Declare section of the PL/SQL Block.
Syntax: File_pointer_Variable name Utl_file.file type;
Step2: Before we are writing data into a file then we must open the file by using “FOPEN”
function from “UTL_FILE” package this function accepts 3 paraments.
Syntax: File_point_Varriable name := UTL_FILE.FOPEN(‘Directory name’, ‘File name’,
‘MOD’ );
MOD: Three types (W_write R_right A_appended)
Step3: If we want to right data into file then we are using “PUTF” procedure from “UTL
_FILE” package.
Syntax: Utl_File.putf (file pointer variable name, ‘content’);
Step4: After writing data into file then must close the file by using “FCLOSE” procedure
from “UTL_FILE” package.
Syntax: UTL_FILE.FCLOSE(file pointer variable name);
Read Data from Flat File: If we want to read data from flat files then we must used
Get_Line procedure from “UTL_FILE” package.
Syntax: UTL_FIlE.Get_Line(file pointer variable, Buffer variables);

DYNAMIC SQL
In dynamic SQL, SQL Statement are executed at run time. Generally, in
PL/SQL we are not allowed to use DDL, DCL statement. If we want to use those statements
in PL/SQL then we are using Dynamic SQL. In dynamic SQL SQL statements must be
specified with in single quotes and also those statement is executed by using “execute
immediate” clause. This clause must be used in executable section of begin the PL/SQL
Block.
Syntax: begin
Execute immediate “SQL Statement”;
End;

LOB[LARGE OBJECT]
All database systems having 2 types of Large Objects.
1) INTERNAL LARGE OBJECTS
2) EXTERNAL LARGE OBJECTS
1)INTERNAL LARGE OBJECT:
 Internal large objects are stored with in data base.
 oracle having 2 types of internal large object
1) C Lob [character large object]
2) B Lob [binary large object]
Syntax: column_name CLob [column_name datatype]
Column_name Blob [column_name datatype]
2)EXTERNAL LARGE OBJECT:
 External large object are store in out said of the database.
 These objects are stored in operating system files.
 This in an Bfile data type.
Syntax: column_name bfile [column_name datatype]
Difference between Long and Lob
LONG LOB
Can store up to 2GB data Can store up to 4GB data
A table contain only 1 long column A table contain more than 1 lob column

You might also like