Oracle_PLSQL
Oracle_PLSQL
INTRODUCTION
PL/SQL, or Procedural Language/Structured Query Language,
is a powerful extension of SQL (Structured Query Language)
used for database programming in Oracle.
Increased productivity:
Same techniques can be used with most Oracle products
Portability
Works on any Oracle platform
DIFFERECE B/W SQL AND
PL/SQL
TOPICS IN PL/SQL:
conditional statements
loops
exceptions
triggers
functions
procedures
cursors
BLOCKS
PL/SQL Block Structure
Declare section:
starts with DECLARE keyword in which variables, constants,
records as cursors can be declared which stores data
temporarily.
Execution section :
Starts with BEGIN and ends with END keyword.This is a
mandatory section and here the program logic is written to
perform any task like loops and conditional statements
Exception handling section:
Starts with the EXCEPTION keyword. The exception section is
the place that you put the code to handle exceptions. You can
either catch or handle exceptions in the exception section.
Notice that the single forward slash (/) is a signal to instruct
SQL*Plus to execute the PL/SQL block.
PL/SQL Placeholders
Placeholders are temporary storage area.
Placeholders can be any of Variables, Constants and
Records. Oracle defines placeholders to store data
temporarily, which are used to manipulate
data during the execution of a PL SQL block.
VARIABLE
A variable is a meaningful name which
facilitates a programmer to store data
temporarily during the execution of
code. It helps you to manipulate data
in PL/SQL programs. It is nothing
except a name given to a storage area.
Naming rules for PL/SQL
variables
The variable in PL/SQL must follow some naming rules
like other programming languages.
When a variable is specified as NOT NULL, you must initialize the variable
when it is declared.
For example: The below example declares two variables, one of which is a
not null.
DECLARE
salary number(4);
dept varchar2(10) NOT NULL := “HR Dept”;
Common PL/SQL Data Types
• CHAR ( max_length )
• VARCHAR2 ( max_length )
• NUMBER ( precision, scale )
• BINARY_INTEGER – more efficient than number
• RAW ( max_length )
• DATE
• BOOLEAN (true, false, null)
• Also LONG, LONG RAW and LOB types but the
capacity is usually less in PL/SQL than SQL
The value of a variable can change in the execution or exception
section of the PL/SQL Block. We can assign values to variables in the
two ways given below.
1) We can directly assign values to variables. The General Syntax is:
variable_name:= value;
2) We can assign values to variables directly from the database columns by using a
SELECT.. INTO statement. The General Syntax is:
SELECT column_name
INTO variable_name
FROM table_name
[WHERE condition];
EXAMPLE
DECLARE
var_salary number(6);
var_emp_id number(6) := 101;
BEGIN
SELECT salary
INTO var_salary
FROM employee
WHERE eno = var_emp_id;
dbms_output.put_line(var_salary);
dbms_output.put_line('The employee '
|| var_emp_id || ' has salary ' || var_salary);
END;
/
Variable Scope in PL/SQL:
PL/SQL allows nesting of blocks. A program block
can contain another inner block. If you declare a
variable within an inner block, it is not accessible to
an outer block. There are two types of variable
scope:
END;
/
OUTPUT
OUTPUT
CONTROL STATEMENTS
PL/SQL If
END IF;
END;
/
set serveroutput on;
DECLARE
a int;
b int;
BEGIN
a := &a;
b := &b;
if(a>b) then
dbms_output.put_line(‘a is greater than b’);
elsif(b>a) then
dbms_output.put_line(‘b is greater than a’);
else
dbms_output.put_line(‘Both a and b are equal’);
end if;
LOOPS
● The PL/SQL loops are used to repeat the
execution of one or more statements for
specified number of times.
● These are also known as iterative control
statements.
TYPES OF LOOPS:
❖ Basic/exit loop
❖ while loop
❖ for loop
❖ cursor for loop
EXIT LOOP
SYNTAX:
FOR LOOP
SYNTAX:
WHILE LOOP
SYNTAX:
STORED PROCEDURES
END;
Explicit cursor
■The explicit cursors are defined by the
programmers to gain more control over
the context area.
■These cursors should be defined in the
declaration section of the PL/SQL block.
SYNTAX:
CURSOR cursor_name IS
select_statement;
STEPS
■Declare the cursor to initialize in the
memory.
■Open the cursor to allocate memory.
■Fetch the cursor to retrieve data.
■Close the cursor to release allocated
memory.
Declare the cursor
SYNTAX:
CURSOR cursor name IS
SELECT statement;
example:
Open the cursor
It is used to allocate memory for the
cursor and make it easy to fetch the
rows returned by the SQL statements
into it.
SYNTAX:
OPEN cursor_name;
Fetch the cursor
It is used to access one row at a time.
SYNTAX:
SYNTAX:
CLOSE cursor_name;
General form of using an explicit
cursor is
DECLARE
variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
What are Explicit Cursor Attributes?
a
Triggers
■Associated with a particular table
■Automatically executed when a
particular event occurs
• Insert
• Update
• Delete
• Others
Triggers vs. Procedures
■Procedures are explicitly executed by
a user or application
■Triggers are implicitly executed
(fired) when the triggering event
occurs
■Triggers should not be used as a lazy
way to invoke a procedure as they
are fired every time the event occurs
Triggers
Triggers
■The trigger specification names the
trigger and indicates when it will fire
■The trigger body contains the PL/SQL
code to accomplish whatever task(s)
need to be performed
Triggers
Triggers Timing
■A triggers timing has to be specified
first
• Before (most common)
■Trigger should be fired before the operation
• i.e. before an insert
• After
■Trigger should be fired after the operation
• i.e. after a delete is performed
Trigger Events
■Three types of events are available
• DML events
• DDL events
• Database events
DML Events
■Changes to data in a table
• Insert
• Update
• Delete
DDL Events
■Changes to the definition of objects
• Tables
• Indexes
• Procedures
• Functions
• Others
■Include CREATE, ALTER and DROP
statements on these objects
Database Events
■Server Errors
■Users Log On or Off
■Database Started or Stopped
Trigger DML Events
■Can specify one or more events in
the specification
• i.e. INSERT OR UPDATE OR DELETE
■Can specify one or more columns to
be associated with a type of event
• i.e. BEFORE UPDATE OF SID OR SNAME
Table Name
■The next item in the trigger is the
name of the table to be affected
Trigger Level
■Two levels for Triggers
• Row-level trigger
■Requires FOR EACH ROW clause
• If operation affects multiple rows, trigger fires
once for each row affected
• Statement-level trigger
• DML triggers should be row-level
• DDL and Database triggers should not
be row-level
Event Examples
Triggers
■Conditions Available So Multiple
Operations Can Be Dealt With In
Same Trigger
• Inserting, Updating, Deleting
■Column Prefixes Allow Identification
Of Value Changes
• New, Old
Triggers Exceptions
■EXCEPTION Data Type Allows Custom
Exceptions
■RAISE Allows An Exception To Be
Manually Occur
■RAISE_APPLICATION_ERROR Allows
Termination Using A Custom Error
Message
• Must Be Between -20000 and -20999
• Message Can Be Up to 512 Bytes