0% found this document useful (0 votes)
253 views

Basic PL-SQL

The document provides an overview of PL/SQL programming fundamentals including: - PL/SQL allows programming at the database level and uses block structures for code execution. - Key advantages are tight integration with SQL, better performance, full portability, and tight security. - The document discusses PL/SQL datatypes, variables, control structures like IF/CASE statements and loops, cursors, and stored procedures/functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
253 views

Basic PL-SQL

The document provides an overview of PL/SQL programming fundamentals including: - PL/SQL allows programming at the database level and uses block structures for code execution. - Key advantages are tight integration with SQL, better performance, full portability, and tight security. - The document discusses PL/SQL datatypes, variables, control structures like IF/CASE statements and loops, cursors, and stored procedures/functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 47

Basic PL/SQL Programming

Agenda
 Introduction to PL/SQL
 Advantages of PL/SQL
 PL/SQL programming Fundamentals
 Basic usage of Toad Tool
 PL/SQL usage in LIMS
What is PL/SQL?

 Procedure Language/Structured Query Language


 Executed at the database server side.
 4th generation Programming Language
 Execution is through block structure
 2 types of blocks
 Anonymous Block
 Named Block( stored procedure/function)
Understanding PL/SQL Block Structure
 a PL/SQL block has three basic parts: a
declarative part (DECLARE), an executable part
(BEGIN .. END), and an exception-handling
(EXCEPTION) part that handles error conditions
 The declaration section defines all variables,
cursors, subprograms, and other elements to be
used in the code.
 The declaration section is optional.
 The executable section contains the main body of
the routine.
 The executable section starts with the begin
keyword and ends with the exception keyword or
the end keyword if you have no exception section.
 The executable section is the only mandatory part
of the code.
 You must have at least one line of executable
code in the executable section.
 You can use the NULL command to indicate that
nothing should be executed.
 The exception section is also optional.
 The exception section allows the program to
intercept and process exceptions
Advantages of PL/SQL
 Tight Integration with SQL
 Better Performance
 Full Portability
 Tight Security
 Access to Pre-defined Packages
PL/SQL Programming Fundamentals
 Data Types
 Variables and Constants
 Declaration
 Assigning Values to Variables
 Variables Scope
 Control Structure
 Cursor basics and usage in PL/SQL
 Stored Procedures and Functions
 Packages
 Collections and Records
 Exception Handling
PL/SQL Datatypes

 Predefined PL/SQL Datatypes


 A composite type has internal components that can be
manipulated individually, such as the elements of an
array, record, or table.
 A LOB type holds values, called lob locators, that specify
the location of large objects, such as text blocks or
graphic images, that are stored separately from other
database data.
 A reference type holds values, called pointers, that
designate other program items. These types include REF
CURSORS and Refernces to object types.
PL/SQL Datatypes
 A scalar type has no internal components. It holds a single
value, such as a number or character string. They are
divided into 4 categories.
 PL/SQL Number Types
- Eg: NUMBER,FLOAT,INT…etc
 PL/SQL Character and String Types
- Eg: CHAR, VARCHAR2…etc
 PL/SQL Boolean Type
- Eg: BOOLEAN
 PL/SQL Date, Time, and Interval Types
- Eg: DATE, TIMESTAMP…etc
 PL/SQL SUBTYPES
 Subtypes specify the same set of operations as their base
type, but only a subset of its values.
 A subtype does not introduce a new type; rather, it places an
optional constraint on its base type.
Variables and Constants
 Declaring Variables
 Declaration
 Using -%TYPE attribute
 The %TYPE attribute provides the datatype of a variable or database
column
DECLARE
ln_service_id service.service_id%TYPE ;
 Using -%ROWTYPE attribute
 The %ROWTYPE attribute provides a record type that represents a row
in a table or view.
DECLARE
lr_service_record service%ROWTYPE ;

 Assigning Values to a Variable


 Assigning Values to Variables With the Assignment Operator (:=)
 Assigning Values to Variables by SELECTing INTO
 Assigning Values to Variables as Parameters of a Subprogram
Declaring Datatypes for PL/SQL Variables :
NUMBER(precision, scale)/integer
Count integer;
Salary number(10,2);
seconds_per_day constant number(12) := 60*60*24;
Char/Varchar2
First_name varchar2(30) Not null :=‘ENAME’;
Last_name char;
Company_name constant varchar2(12):=‘QWEST’;
DATE
Joining_date date;
Log_off_time timestamp;
Next_training_date date not null :=’10-MAR-10’;
Boolean
Flag boolean not null := false;
Available boolean;
Bind Variables
 These are variables used in SQL query.
 You can save parsing overhead.
 Oracle can reuse these SQL statement each time the same code
is executed.
Eg: Without Using Bind variables:
DELETE FROM service WHERE service_id = 123456;

Eg: Using Bind variables:


DECLARE
my_id NUMBER(12);
BEGIN
my_id := 123456;
EXECUTE IMMEDIATE ‘DELETE FROM service WHERE service_id = :abc’
USING my_id ;
END;
Variable Scope
DECLARE
a CHAR;
b REAL;
BEGIN
-- identifiers available here: a (CHAR), b
DECLARE
a INTEGER;
c REAL;
BEGIN
NULL; -- identifiers available here: a (INTEGER), b, c
END;

DECLARE
d REAL;
BEGIN
NULL; -- identifiers available here: a (CHAR), b, d
END;
-- identifiers available here: a (CHAR), b
END;
/
PL/SQL Control Structures

 Conditional control:
 IF Statements
 -IF-THEN-ELSE
 -IF-THEN-ELSIF
 CASE Statements
 Simple CASE
 Searched CASE
-> IF condition THEN
statement1;
ELSE
statement2;
END IF;

-> IF condition1 THEN


statement1;
ELSIF condition2 THEN
statement2;
ELSE
statement3;
END IF;

-> CASE selector


WHEN value1 THEN satement1;
WHEN value2 THEN satement2;
ELSE satement3;
END CASE;

-> CASE
WHEN expression1 THEN satement1;
WHEN expression2 THEN satement2;
ELSE satement3;
END CASE;
Controlling Loop Iterations
 Loops repeat a statement or sequence of
statements multiple times.
 There are three loop types:
 Basic loop :
 FOR loop
 WHILE loop
Syntaxes:
Basic loop:
LOOP
statement1;
. . .
EXIT [WHEN condition];
END LOOP;
FOR Loop:
FOR counter IN lower_bound..upper_bound
LOOP
statement1;
statement2;
. . .
END LOOP;
 Do not declare the counter; it is declared implicitly.
 'lower_bound .. upper_bound' is required syntax.

While loop:
WHILE condition
LOOP
statement1;
statement2;
. . .
END LOOP;

 Use the WHILE loop to repeat statements while a condition is


TRUE.
Controlling Loop Iterations

 Use the basic loop when the statements inside the loop must
execute at least once.
 Use the WHILE loop if the condition has to be evaluated at the start
of each iteration.
 Use a FOR loop if the number of iterations is known.
Cursor basics and usage in PL/SQL

 Cursor is a pointer to an area used for holding SQL query


results.
 Every SQL statement executed by the Oracle Server has
an individual cursor associated with it:
 Implicit cursors: Declared for all DML
 Explicit cursors: Declared and named by the programmer

Declare(create a named SQL area)


Open (identify the result set)
fetch (loading the current record into the variable)
Close (release the result set)
Syntax for declaring a cursor:
CURSOR cursor_name IS
select_statement;

Cursor Attributes:
Attribute Type Description
%ISOPEN Boolean Evaluates to TRUE if the cursor
is open
%NOTFOUND Boolean Evaluates to TRUE if the most
recent fetch does not return a row
%FOUND Boolean Evaluates to TRUE if the most
recent fetch returns a row;
complement of %NOTFOUND
%ROWCOUNT Number Evaluates to the total number of
rows returned so far
Declare
CURSOR my_cursor IS
SELECT service_id FROM service
where record_type_cd = 'DIGITAL VOIP SERVICE'
and service_id=1938135 and service_version_no=1;
service_id NUMBER(12);
Begin
OPEN my_cursor;
LOOP
FETCH my_cursor INTO service_id;
IF my_cursor%NOTFOUND
THEN
EXIT;
ELSE
Dbms_output.put_line ('service id is' || service_id);
END IF;
END LOOP;
End;
Stored Procedures and Functions

 Also called Subprograms


 Stored in complied form in the database
 Can call other procedures
 Collection of SQL and PL/SQL statements
 Can be called from all client environments
 Procedures and function are the same, except
a function returns a value and a procedure
does not.
A subprogram
 Is a named PL/SQL block that can accept parameters
and be invoked from a calling environment.
 Is of two types:
 Procedure - that performs an action

 Function - that returns a value

 Is based on standard PL/SQL block structure


Syntax for function creation or update:
CREATE [OR REPLACE] FUNCTION function_name
[(parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,
. . .)]
RETURN datatype
IS|AS
declarations ;
Begin
Statements;
End;
Syntax for procedure creation or update:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,
. . .)]
IS|AS
declarations ;
Begin
Statements;
End;
Modes of parameters to subprograms

 3 Types of modes
 IN
 Read only
 Pass By value
 OUT
 Write Only
 Pass by reference
 IN OUT
 Read Write
 Pass by reference
Example:
 Creation
CREATE PROCEDURE raise_sal(
p_id IN NUMBER,
p_amount IN NUMBER )
IS
BEGIN
null;
END raise_sal;
 Invocation Example:
Begin
raise_sal(100, 2000);
End;
Package
 A package is a unit which encapsulates functions, procedure and
collections.
 Once created, can be used as a user defined Library.
 Has 2 parts
 Specification – Declaration visible through component selecter.
 Body – Definition – This is Hidden.
 Both can contain TYPEs, variables, procedures and functions.
CREATE [OR REPLACE] PACKAGE package_name IS
declarations ;
END package_name ;

CREATE [OR REPLACE] PACKAGE BODY package_name IS


definitions ;
END package_name ;
Collections and Records
A collection is an ordered group of elements, all of the same type. It is a
general concept that encompasses lists, arrays, and other familiar datatypes.
Each element has a unique subscript that determines its position in the
collection.
PL/SQL offers these collection types:
Index-by tables, also known as associative arrays, let you look up elements
using arbitrary numbers and strings for subscript values. (They are similar to
hash tables in other programming languages.)

Nested tables hold an arbitrary number of elements. They use sequential


numbers as subscripts. You can define equivalent SQL types, allowing nested
tables to be stored in database tables and manipulated through SQL.

Varrays (short for variable-size arrays) hold a fixed number of elements


(although you can change the number of elements at runtime). They use
sequential numbers as subscripts. You can define equivalent SQL types, allowing
varrays to be stored in database tables. They can be stored and retrieved
through SQL, but with less flexibility than nested tables.
Index-by tables/ associative arrays

 Unbounded, practically speaking.


 Index can range from -2,147,483,647 to
2,147,483,647.
 This range allows you to employ the index value
as an intelligent key, such as the primary key or
unique index value
 They are Sparse : Data does not have to be stored
in consecutive rows, as is required in traditional
3GL arrays and VARRAYs.
 Index values can be integers or strings (Oracle9i
R2 and above).
Associative arrays examples
DECLARE
-- a. Declare a local associative array of numbers indexed by INTEGER.
TYPE numbers_aat IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;

-- b. Declare a variable based on that type.


my_numbers numbers_aat;

-- c. Fill up the first 100 elements (starting from index 1) with numbers of your choice.
BEGIN
FOR indx IN 1 .. 100
LOOP
my_numbers ( indx ) := indx * 2;
dbms_output.put_line(indx);
dbms_output.put_line(my_numbers(indx));
END LOOP;
END;
/
Nested tables

 No pre-defined limit on a nested table.


 Index starts from 1.
 You can think of them as one-dimensional arrays
with no declared number of elements.
 Requires initialization.
 Is always dense initially, but can become sparse
after deletes.
DECLARE
-- a. Declare a local nested table of numbers.
TYPE numbers_ntt IS TABLE OF NUMBER;

-- b. Declare a variable based on that type.


my_numbers numbers_ntt := numbers_ntt ( );
-- c. Fill up the first 100 elements (starting from index 1) with numbers of your choice.
BEGIN
FOR indx IN 1 .. 100
LOOP
my_numbers.EXTEND;
my_numbers ( indx ) := indx * 1958;
END LOOP;
END;
/
Varray

 A varray has a maximum size, which you


specify in its type definition.
 Index starts from 1.
 Requires initialization.
 Is always dense; you can only remove
elements from the end of a varray with
TRIM.
DECLARE
-- a. Declare a local varray table of numbers.
TYPE numbers_ntt IS VARRAY(5) OF INTEGER;

-- b. Declare a variable based on that type.


my_numbers numbers_ntt := numbers_ntt ( );
-- c. Fill up the first 5 elements (starting from index 1) with numbers of your choice.
BEGIN
FOR indx IN 1 .. 5
LOOP
my_numbers.EXTEND;
my_numbers ( indx ) := indx * 1958;
dbms_output.put_line(my_numbers(indx));
END LOOP;
END;
/
Collection methods
 COUNT
returns number of rows currently defined in collection.
 EXISTS
returns TRUE if the specified row is defined.
 FIRST/LAST
return lowest/highest numbers of defined rows.
 NEXT/PRIOR
return the closest defined row after/before the specified row.
 EXTEND
Appends one null element to a collection.
 TRIM
Removes one element from the end of a collection.
Records
 Records are composed of a group of fields,
similar to the columns in a row in a table.
Declare
TYPE my_record IS RECORD (
my_data1 VARCHAR2,
my_data2 NUMBER,
my_data3 NUMBER
);
TYPE my_table1 IS TABLE OF my_record;
my_tab_rec1 my_table1 := my_table1();

TYPE my_table2 IS TABLE OF SERVICE%ROWTYPE ;


my_tab_rec2 my_table2 := my_table2();
Other Features
 Parameter Passing to Explicit CURSORs
 BULK COLLECT INTO
 Cursor FOR LOOP
FOR <name> IN <cursor> [ OR SELECT statement]
LOOP
….;
END LOOP;
 REF CURSORs
 Cursor Variables - to pass query result set between subprograms
TYPE my_cursor IS REF CURSOR ;
 SYS_REFCURSOR
 Dynamic Queries
Exception Handling
 In PL/SQL error are called exceptions
 When an exception is raised, processing jumps to the

exception handlers
 An exception handler is a sequence of statements to be
processed when a certain exception occurs
 When an exception handler is complete processing of

the block terminates


Types of Exceptions
1. PREDEFINED INTERNAL EXCEPTIONS
2. USER-DEFINED EXCEPTIONS
Predefined Internal Exceptions
Any ORACLE error “raises” an exception automatically;
Some of the more common ones have names.

 TOO_MANY_ROWS ORA-(01427)
- a single row SELECT returned more than one row
 NO_DATA_FOUND ORA-(01403)
- a single row SELECT returned no data
 INVALID_CURSOR ORA-(01001)
- invalid cursor was specified
 VALUE_ERROR ORA-(06502)
- arithmetic ,numeric, string , conversion, or constraint error occurred.
 ZERO_DIVIDE ORA-(01476)
- attempted to divide by zero
 DUP_VAL_ON_INDEX ORA-(00001)
- attempted to insert a duplicate value into a column that has a unique
index specified.
Syntax
WHEN <exception_name [OR <exception_name…]>
THEN <sequence of statements>
OR
WHEN OTHERS
THEN -- if used , must be last handler
<sequence of statements>
Eg:
DECLARE
employee_num emp.empno%TYPE;
BEGIN
SELECT empno INTO employee_num FROM emp
WHERE ename= ‘BLAKE’;
INSERT INTO temp VALUES(NULL, empno,Blake's employee_num’);
DELETE FROM emp WHERE ename =‘BLAKE’;
EXCEPTION
WHEN TOO_MANY_ROWS OR NO_DATA_FOUND THEN
ROLLBACK;
INSERT INTO temp VALUES (NULL,’Blake not found, or more than one Blake’);
COMMIT;

WHEN OTHERS THEN


ROLLBACK;
END;
User defined Exceptions
 must be defined and explicitly raised by the user.

E.g.
DECLARE
x NUMBER;
my_exception EXCEPTION; -- a new object type.

Raise your_exception;
RAISE my_exception;

Notes -RAISE <exception_name>


1. Once an exception is RAISED manually, it is treated exactly the
same as if it were a predefined internal exception.
2. Declared exceptions are scoped just like variables.
3. A user-defined exception is checked for manually and then RAISED ,
if appropriate.
E.g.
DECLARE
my_ename emp.ename%TYPE :=‘BLAKE’;
assigned_projects NUMBER;
too_few_projects EXCEPTION
BEGIN ---- get no of projects assigned to BLAKE
IF assigned_project < 3 THEN
RAISE too_few_projects;
END IF;
EXCEPTION --begin the exception handlers
WHEN too_few_projects THEN
INSERT INTO temp
VALUES(my_ename,assigned_projects,’LESS THAN 3
PROJECTS!’)
COMMIT;
END;
When an exception occurs in an innermost nested
block.
 Step- 1 The current block is searched for a handler. If not found,
go to step 2.
 Step- 2 If an enclosing block is found, it is searched for it handler.
 Step- 3 Step #1 and#2 are repeated until either there are no
more enclosing blocks, or a handler is found .
 If there are no more enclosing blocks, the exception is passed
back to the calling environment (SQL *Plus,SQL *Forms, a
precompiled program,etc.)
 If the handler is found ,it is executed .when done the block in
which the handler was found is terminated, and control is passed to
the enclosing block (if one exists), or to environment (if there is no
enclosing block)
notes
 1. Only one handler per block may be active at a time
 2. If an exception is raised in a handler, the search for a handler for
the new exception begins in the enclosing block of the current block
Exception Propagation

DECLARE
A EXCEPTION;
B EXCEPTION;
C EXCEPTION;
x NUMBER;
BEGIN

BEGIN
IF X=1 THEN RAISE A;
ELSEIF X=2 THEN RAISE B;
ELSE RAISE C;

EXCEPTION
WHEN A THEN
...
END;

EXCEPTION
WHEN B THEN
...
END;
PL/SQL usage in LIMS
Useful Documents and links

 Data Types 

 Oracle PL/SQL User's Guide and Reference


http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/overview.htm
Question?
Thank you

You might also like