Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Oracle_PLSQL

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Oracle_PLSQL

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Oracle PL/SQL

INTRODUCTION
PL/SQL, or Procedural Language/Structured Query Language,
is a powerful extension of SQL (Structured Query Language)
used for database programming in Oracle.

The programs of PL/SQL are logical blocks that can contain


any number of nested sub-blocks

It is an extension to sql with design of programming language


(procedural and object oriented)
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).
Why PL/SQL OVER SQL
Complex Business Logic: When your application requires
complex business logic, such as conditional processing,
looping, or error handling, PL/SQL provides the necessary
procedural constructs to implement such logic effectively.

Error Handling: PL/SQL's robust exception handling


mechanisms enable developers to detect and handle errors
gracefully. This is particularly important in applications where
data integrity and reliability are critical.
Modularity and Reusability: procedures and functions
facilitates modularity and reusability. This can lead to more
maintainable and scalable codebases compared to writing
SQL statements inline within application code.
PL/SQL can execute a number of queries in one block using
single command.

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.

The variable_name should not exceed 30 characters.


Variable name should not be the same as the table
table's column of that block.
The name of the variable must begin with ASCII letter.
The PL/SQL is not case sensitive so it could be either
lowercase or uppercase. For example: v_data and
V_DATA refer to the same variables.
You should make your variable easy to read and
understand, after the first character, it may be any
number, underscore (_) or dollar sign ($).
NOT NULL is an optional specification on the variable.
SYNTAX OF VARIABLE
DECLARATION
The General Syntax to declare a
variable is:
variable_name datatype [NOT
NULL := value ];

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:

Local Variable: Local variables are the inner block


variables which are not accessible to outer blocks.
Global Variable: Global variables are declared in
outermost block.
DECLARE
2> var_num1 number;
3> var_num2 number;
4> BEGIN
5> var_num1 := 100;
6> var_num2 := 200;
7> DECLARE
8> var_mult number;
9> BEGIN
10> var_mult := var_num1 * var_num2;
11> END;
12> END;
13> /
PL/SQL Constants

As the name implies a constant is a value used in a PL/SQL


Block that remains unchanged throughout the program. A
constant is a user-defined literal value. You can declare a
constant and use it instead of actual value.

The General Syntax to declare a constant is:

constant_name CONSTANT datatype := VALUE;


Variable Attributes:
PL/SQL provides the facility to declare a
variable without having to specify a
particular data type using %TYPE and
%ROWTYPE attributes. These two
attributes allow us to specify a variable
and have that variable data type be
defined by a table/view column or a
PL/SQL package variable
%Type
The %TYPE attribute is used to declare variables
according to the already declared variable or database
column
This declaration will declare a variable that has the
same data type as column of the table.
EXAMPLE
%ROWTYPE
The %ROWTYPE attribute is used to declare a record type that
represents a row in a table. The record can store an entire row
or some specific data selected from the table. A column in a
row and corresponding fields in a record have the same name
and data types.
Example
PL/SQL Records

Records are another type of datatypes which oracle allows to be


defined as a placeholder. Records are composite datatypes, which
means it is a combination of different scalar datatypes like char,
varchar, number etc. Each scalar data types in the record holds a
value. A record can be visualized as a row of data. It can contain
all the contents of a row.
SYNTAX
EXAMPLE
DECLARE
TYPE DeliveryRecordType IS RECORD (
Supplier1 SUPPLIER.city%TYPE,
Article1 DELIVERY.qty%TYPE
);
delivery_record DeliveryRecordType;
BEGIN
SELECT d1.city, d2.qty
INTO delivery_record
FROM SUPPLIER d1
JOIN DELIVERY d2 ON d1.Snr = d2.Snr
WHERE d1.SNR = 'S001' AND d2.Anr='A01';
DBMS_OUTPUT.PUT_LINE('Supplier city: ' || delivery_record.Supplier1);
DBMS_OUTPUT.PUT_LINE('Article Quantity: ' || delivery_record.Article1);

END;
/
OUTPUT
OUTPUT
CONTROL STATEMENTS
PL/SQL If

PL/SQL supports the


programming language features like
conditional statements and iterative
statements. Its programming
constructs are similar to how you use
in programming languages like Java
and C++.
SYNTAX
This syntax is used when you want to
execute statements only when condition is
TRUE
set serveroutput on;
DECLARE
x int:=10;
y int:=80;
BEGIN
if(y>x) then
dbms_output.put_line('Result: ' ||y|| ' is greater
than ' ||x);
end if;
END;
This syntax is used when you want to execute one set of
statements when condition is TRUE or a different set of
statements when condition is FALSE.
set serveroutput on;
DECLARE
x int;
BEGIN
x := &x;
if mod(x,2) = 0 then
dbms_output.put_line('Even Number');
else
dbms_output.put_line('Odd Number');
end if;
END;
This syntax is used when you want to execute one set of
statements when condition1 is TRUE or a different set of
statements when condition2 is TRUE.
DECLARE
x NUMBER := 10;
BEGIN
-- Check if x is positive, negative, or zero
IF x > 0 THEN
DBMS_OUTPUT.PUT_LINE('x is positive');
ELSIF x < 0 THEN
DBMS_OUTPUT.PUT_LINE('x is negative');

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

● The PL/SQL stored procedure or simply a


procedure is a PL/SQL block which performs one or
more specific tasks

● The procedure contains a header and a body


STORED PROCEDURES

Header: The header contains the name of


the procedure and the parameters or variables
passed to the procedure.

Body: The body contains a declaration


section, execution section and exception section
similar to a general PL/SQL block.
STORED PROCEDURES
●Run a procedure with the PL/SQL
EXECUTE command

●Parameters are enclosed in


parentheses

●Procedures may or may not return a


value
PARAMETERS
1. IN parameters: The IN parameter can be referenced by the
procedure or function. The value of the parameter cannot be
overwritten by the procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by
the procedure or function, but the value of the parameter can be
overwritten by the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced b
the procedure or function and the value of the parameter can be
overwritten by the procedure or function.
GENERAL SYNTAX
DROP PROCEDURE
SYNTAX:
Predefined Exceptions
■INVALID_NUMBER (ORA-01722)
• Attempted to store non-numeric data in a
variable with a numeric data type
■NO_DATA_FOUND (ORA-01403)
• Query resulted in no rows being found
■NOT_LOGGED_ON (ORA-01012)
• Not currently connected to an Oracle
database
■TOO_MANY_ROWS (ORA-01422)
• A SELECT INTO statement returned more
than one row
Predefined Exceptions (cont.)
■DUP_VALUE_ON_INDEX (ORA-00001)
• Value inserted for a primary key is not
unique
■VALUE_ERROR (ORA-06502)
• The value being placed in a variable is the
wrong length or data type
■ZERO_DIVIDE (ORA-01476)
• An attempt was made to divide a number
by zero
Structure of Exception Section
Stored Functions
■Like a procedure except they return
a single value
PL/SQL CURSORS
What is PL/SQL Cursors?

■ When a SQL statement is processed,oracle


creates a memory space known as context area.

■ A cursor is a pointer to this context area.

■ A cursor contains all the information on a select


statement and the rows of data accessed by it.
Types of Cursors
Implicit Cursor
■ The implicit cursor are created by
default to process the statements
when the DML statements like
insert,update and delete etc., are
executed.
■ oracle provides some of the known
attributes like
■ %FOUND
■ %NOT FOUND
■ %ROWCOUNT
Attribute Description

%FOUND Its return values is True if the DML


statements affect atleast one or more
rows or a select into statement returns
one or more rows. otherwise it returns
false.

%NOT FOUND Its return values is True if the DML


statements affect no rows or a select
into statement returns no rows.
otherwise it returns false.

%ROWCOUNT It returns the number of rows affected by


the DML operations like
INSERT,DELETE,UPDATE,SELECT.
Example
Table employee:
DECLARE var_rows number(5);
BEGIN
UPDATE employee
SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where
updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows ||
'employees are updated');
END IF;

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:

FETCH cursor_name INTO variable_list;


Close the cursor
It is used to release the allocated
memory.

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?

Oracle provides some attributes known as


Explicit Cursor Attributes to control the data
processing while using cursors. We use these
attributes to avoid errors while accessing
cursors through OPEN, FETCH and CLOSE
Statements.
When does an error occur while accessing
an explicit cursor?

a) When we try to open a cursor which is


not closed in the previous operation.
b) When we try to fetch a cursor after the
last operation.

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

You might also like