SlideShare a Scribd company logo
1 of 75
Oracle PL/SQL
Course Presentation
Contents
• What is PL/SQL
• Overview of PL/SQL
– Understanding the Main Features of PL/SQL
– PL/SQL Architecture
– Advantages of PL/SQL
• Fundamentals of PL/SQL
– Character Set
– Lexical Units
– Literals
– Declarations
– PL/SQL Naming Conventions
– Scope and Visibility of PL/SQL
– Identifiers Variable Assignment
– PL/SQL Expressions and Comparisons
Contents
• PL/SQL Datatypes
– Predefined Datatypes
– User-Defined Subtypes
– Datatype Conversion
• PL/SQL Control Structures
– Overview of PL/SQL Control Structures
– Conditional Control: IF and CASE Statements
– Iterative Control: LOOP and EXIT Statements
– Sequential Control: GOTO and NULL Statements
• PL/SQL Collections and Records
– What Is a Collection?
– Choosing Which PL/SQL Collection Types to Use
– What Is a Record?
Contents
• Interaction Between PL/SQL and Oracle
– Overview of SQL Support in PL/SQL
– Managing Cursors
– Using Cursor FOR Loops
– Defining REF CURSOR Types
– Using Cursor Attributes
– Using Cursor Expressions
– Parameterized Cursors
– FOR UPDATE , WHERE CURRENT OF
• Overview of Transaction Processing in
PL/SQL
Contents
• Handling PL/SQL Errors
– Overview of PL/SQL Error Handling
– Advantages of PL/SQL Exceptions
– Predefined PL/SQL Exceptions
– Defining Your Own PL/SQL Exceptions
– How PL/SQL Exceptions Are Raised
– Handling Raised PL/SQL Exceptions
– How PL/SQL Exceptions Propagate
Contents
• PL/SQL Subprograms
– What Are Subprograms?
– Declaring PL/SQL Subprograms
– Understanding PL/SQL Procedures
– Understanding PL/SQL Functions
– Actual Versus Formal Subprogram Parameters
– Positional Versus Named Notation for
Subprogram Parameters
– Specifying Subprogram Parameter Modes
– Understanding and Using Recursion
Contents
• PL/SQL Packages
– What Is a PL/SQL Package?
– Advantages of PL/SQL Packages
– Understanding The Package Spec
– Understanding The Package Body
– Private Versus Public Items in Packages
– How Package STANDARD Defines the PL/SQL
Environment
– Overview of Product-Specific Packages
Contents
• PL/SQL Object Types
– Object Oriented Features
– The Role of Abstraction
– What Is an Object Type?
– Why Use Object Types?
– Structure of an Object Type
– Components of an Object Type
– Defining Object Types
– Declaring and Initializing Objects
– Manipulating Objects
Contents
• Native Dynamic SQL
– Using the EXECUTE IMMEDIATE Statement
– Using the OPEN-FOR, FETCH, and CLOSE
Statements
What is PL/SQL
• PL/SQL is an imperative 3GL that was
designed specifically for the seamless
processing of SQL commands. It provides
specific syntax for this purpose and supports
exactly the same datatypes as SQL. Server-
side PL/SQL is stored and compiled in Oracle
Database and runs within the Oracle
executable. It automatically inherits the
robustness, security, and portability of Oracle
Database
Overview of PL/SQL
• Main Features Of PL/SQL
– Error Handling
– Blocks
– Variables and Constants
– Subprograms
– Packages
– Triggers
– Input and Output
– Data Abstraction
– Control Statements
– Conditional Compilation
– Processing a Query Result Set One Row at a Time
Sample PL/SQL Program
PL/SQL Block Structure
PL/SQL Architecture
Advantages Of PL/SQL
• PL/SQL has these advantages:
– Tight Integration with SQL
– High Performance
– High Productivity
– Portability
– Scalability
– Manageability
– Support for Object-Oriented Programming
– Support for Developing Web Applications
– Support for Developing Server Pages
Fundamentals Of PL/SQL
(Character Set)
• The PL/SQL character set includes
– the upper- and lower-case letters A .. Z and a .. Z
– the numerals 0 .. 9
– the symbols ( ) + -
* / < > = ! ~ ^ ; : . ' @ % , " # $ & _ | { } ? [ ]
– tabs, spaces, and carriage returns
• PL/SQL is not case sensitive, so lower-case
letters are equivalent to corresponding
upper-case letters except within string and
character literals.
Fundamentals Of PL/SQL
(Lexical Units)
• A line of PL/SQL text contains groups of
characters known as lexical units, which
can be classified as follows:
– delimiters (simple and compound symbols)
– identifiers, which include reserved words
– Literals
– comments
Fundamentals Of PL/SQL
(Literal)
• Literals
– Numeric Literals
• Integer Literals(030 , 6,-14,0,+2767)
• Real Literals(6,7 0.0 ,-12.0,3.14159)
– Character Literals ('6.66Z' '%' '7' ' ' 'z' '(‘) )
– String Literals(‘He said “Life is like licking honey
from a thorn.“’)
– Boolean Literals (TRUE, FALSE, NULL)
– Datetime Literals
– DECLARE d1 DATE := DATE '1998-12-25';
– t1 TIMESTAMP := TIMESTAMP '1997-10-22 13:01:01';
t2 TIMESTAMP WITH TIME ZONE := TIMESTAMP '1997-01-31
09:26:56.66 +02:00';
Fundamentals Of PL/SQL
(Declarations)
• Your program stores values in variables and
constants. As the program executes, the values of
variables can change, but the values of constants
cannot.
• You can declare variables and constants in the
declarative part of any PL/SQL block, subprogram,
or package. Declarations allocate storage space for
a value, specify its datatype, and name the storage
location so that you can reference it.
• Using DEFALUT (hours_worked INTEGER DEFAULT 40;)
• Using NOT NULL (acct_id INTEGER(4) NOT NULL := 9999;)
Fundamentals Of PL/SQL
(Naming Conventions)
• The same naming conventions apply to all
PL/SQL program items and units including
constants, variables, cursors, cursor
variables, exceptions, procedures, functions,
and packages. Names can be simple,
qualified, remote, or both qualified and
remote. For example, you might use the
procedure name raise_salary in any of the
following ways:
– raise_salary(...); -- simple
– emp_actions.raise_salary(...); -- qualified
raise_salary@newyork(...); -- remote
emp_actions.raise_salary@newyork(...); -- qualified and remote
Fundamentals Of PL/SQL
(Scope/Visibility)
Fundamentals Of PL/SQL
(Variable Assignment)
• Variables and constants are initialized
every time a block or subprogram is
entered. By default, variables are
initialized to NULL. Unless you expressly
initialize a variable, its value is undefined:
DECLARE
count INTEGER;
BEGIN
-- COUNT began with a value of NULL.
-- Thus the expression 'COUNT + 1' is also null.
-- So after this assignment, COUNT is still NULL.
count := count + 1;
Fundamentals Of PL/SQL
(PL/SQL Expressions and Comparisons)
• Expressions are constructed using operands and
operators. An operand is a variable, constant,
literal, or function call that contributes a value to
an expression
• The simplest expressions consist of a single
variable, which yields a value directly.
PL/SQL evaluates (finds the current value of) an
expression by combining the values of the
operands in ways specified by the operators. This
always yields a single value and datatype.
• PL/SQL determines the datatype by examining the
expression and the context in which it appears.
Fundamentals Of PL/SQL
(PL/SQL Expressions and Comparisons)
• Operator precedence
Fundamentals Of PL/SQL
(PL/SQL Expressions and Comparisons)
• Logical Truth Table
Fundamentals Of PL/SQL
(PL/SQL Expressions and Comparisons)
• Relational Operators
• IS NULL
• BETWEEN
• IN
• NOT IN
PL/SQL Data Types
• Every constant, variable, and parameter has a datatype (or type),
which specifies a storage format, constraints, and valid range of
values. PL/SQL provides a variety of predefined datatypes. For
instance, you can choose from integer, floating point, character,
Boolean, date, collection, reference, and LOB types. In addition,
PL/SQL lets you define your own subtypes. This chapter covers the
basic types used frequently in PL/SQL programs
– Predefined Datatypes
– User-Defined Subtypes
– Datatype Conversion
PL/SQL Data Types
• A scalar type has no internal components.
• A composite type has internal components
that can be manipulated individually.
• A reference type holds values,
called pointers, that designate other program
items.
• A LOB type holds values, called lob locators,
that specify the location of large objects
(graphic images for example) stored out-of-
line.
PL/SQL Data Types
• Built-in data types
PL/SQL Data Types
• Different Maximum Sizes
PL/SQL Data Types
• Different Maximum Sizes for NUMBER Types
• BINARY_INTEGER datatype to store signed integers. Its magnitude range is
-2**31 .. 2**31
• NUMBER datatype to store fixed-point or floating-point numbers. Its
magnitude range is 1E-130 .. 10E125
• PLS_INTEGER datatype to store signed integers. Its magnitude range is -
2**31 .. 2**31
PL/SQL Data Types
• The LOB (large object) datatypes BFILE, BLOB, CLOB, and NCLOB let you
store blocks of unstructured data (such as text, graphic images, video clips,
and sound waveforms) up to four gigabytes in size.
• Fundamental to working with LOBs is the concept of a LOB locator. A LOB
locator is a pointer to large object data in a database.
• LOB types store lob locators, which point to large objects stored in an
external file, in-line (inside the row) or out-of-line (outside the row).
Database columns of type BLOB, CLOB, NCLOB, or BFILE store the
locators.
• BLOB, CLOB, and NCLOB data is stored in the database, in or outside the
row.
• BFILE data is stored in operating system files outside the database.
PL/SQL LOB Types
PL/SQL Data Types
• User-Defined Subtypes
– Each PL/SQL base type specifies a set of values and a set of operations
applicable to items of that type. Subtypes specify the same set of
operations as their base type but only a subset of its values. Thus, a
subtype does not introduce a new type; it merely places an optional
constraint on its base type.
– Subtypes can increase reliability, provide compatibility with ANSI/ISO
types, and improve readability by indicating the intended use of
constants and variables. PL/SQL predefines several subtypes in
package STANDARD.
– Examples:
• SUBTYPE CHARACTER IS CHAR;
• SUBTYPE INTEGER IS NUMBER(38,0);
PL/SQL Data Types – NUMBER
Subtypes
• BINARY_INTEGER subtypes:
– NATURAL - Only non-negative or positive values
– NATURALN – prevents assigning of nulls to an integer variable
– POSITIVE - Only non-negative or positive values
– POSITIVEN - prevents assigning of nulls to an integer variable
– SIGNTYPE- restrict an integer variable to the values -1, 0, and 1
• NUMBER subtypes:
– DEC - fixed-point numbers with a maximum precision of 38 decimal digit
– DECIMAL - fixed-point numbers with a maximum precision of 38 decimal digit
– DOUBLE PRECISION - floating-point numbers with a maximum precision of 126 binary digits
– FLOAT - floating-point numbers with a maximum precision of 126 binary digits
– INTEGER - to declare integers with a maximum precision of 38 decimal digits
– INT - to declare integers with a maximum precision of 38 decimal digits
– NUMERIC - fixed-point numbers with a maximum precision of 38 decimal digit
– REAL - floating-point numbers with a maximum precision of 63 binary digits
– SMALLINT - to declare integers with a maximum precision of 38 decimal digits
PL/SQL Data Types
• Defining Subtypes
• You can define your own subtypes in the declarative part
of any PL/SQL block, subprogram, or package using the
syntax
– SUBTYPE subtype_name IS base_type[(constraint)] [NOT NULL];
• Some more examples
PL/SQL Data Types
• Datatype Conversion
– Explicit Conversion
• To convert values from one datatype to another, you use built-in functions.
For example, to convert a CHAR value to a DATE or NUMBER value, you
use the function TO_DATE or TO_NUMBER, respectively. Conversely, to
convert a DATE or NUMBER value to a CHAR value, you use the
function TO_CHAR.
– Implicit Conversion
• When it makes sense, PL/SQL can convert the datatype of a value implicitly
PL/SQL Data Types
• Datatype Conversion
PL/SQL Data Types
• Implicit Conversion table
PL/SQL Control Structures
PL/SQL Control Structures
• Conditional Control:
– IF and CASE Statements
PL/SQL Control Structures
• CASE Expression
– A CASE expression selects a result from one or more alternatives, and returns the
result. The CASE expression uses a selector, an expression whose value
determines which alternative to return
PL/SQL Control Structures
• A searched CASE expression has no selector. Each WHEN clause contains a search
condition that yields a Boolean value, which lets you test different variables or
multiple conditions in a single WHEN clause
PL/SQL Control Structures
• Iterative Control: LOOP and EXIT Statements
PL/SQL Control Structures
• Iterative Control: WHILE-LOOP, FOR-LOOP
PL/SQL Control Structures
• Sequential Control: GOTO and NULL Statements
PL/SQL Collections and Records
• Many programming techniques use collection types such
as arrays, bags, lists, nested tables, sets, and trees. To
support these techniques in database applications,
PL/SQL provides the datatypes TABLE and VARRAY,
which allow you to declare index-by tables, nested tables
and variable-size arrays.
PL/SQL Collections and Records
• What is a Collection ?
– 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
– 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.
• Although collections can have only one dimension, you can model
multi-dimensional arrays by creating collections whose elements are
also collections.
PL/SQL Collections and Records
PL/SQL Collections and Records
• Understanding Associative
Arrays (Index-By Tables)
– An associative array (also called
an index-by table) is a set of key-
value pairs. Each key is unique,
and is used to locate the
corresponding value. The key can
be either an integer or a string.
– Using a key-value pair for the first
time adds that pair to the
associative array. Using the same
key with a different value changes
the value.
PL/SQL Collections and Records
• Understanding Nested Tables
– Conceptually, a nested table is like a one-dimensional array with an arbitrary number of
elements.
– Within the database, a nested table is a column type that holds a set of values. The database
stores the rows of a nested table in no particular order. When you retrieve a nested table
from the database into a PL/SQL variable, the rows are given consecutive subscripts starting
at 1. These subscripts give you array-like access to individual rows.
– A nested table differs from an array in these important ways:
– An array has a declared number of elements, but a nested table does not. The size of a nested
table can increase dynamically (however, a maximum limit is imposed
– An array is always dense (that is, it always has consecutive subcripts). A nested array is
dense initially, but it can become sparse, because you can delete elements from it.
PL/SQL Collections and Records
• Understanding Variable-Size Arrays
(Varrays)
– A variable-size array (varray) is an item of the data type VARRAY. A varray has a maximum
size, which you specify in its type definition. A varray can contain a varying number of
elements, from zero (when empty) to the maximum size.
– A varray index has a fixed lower bound of 1 and an extensible upper bound. To access an
element of a varray, you standard subscripting syntax.
PL/SQL Collections and Records
Declaring
Collection Types
PL/SQL Collections and Records
• Initializing and Referencing Collections
– Until you initialize it, a nested table or varray is atomically null:
the collection itself is null, not its elements.
– To initialize a nested table or varray, you use a constructor, a
system-defined function with the same name as the collection
type. This function "constructs" collections from the elements
passed to it.
PL/SQL Collections and Records
• Example: Constructor for a Nested Table
– In the following example, you pass multiple elements to the
constructor CourseList(), which returns a nested table containing those
elements:
DECLARE
TYPE CourseList IS TABLE OF VARCHAR2(16);
my_courses CourseList;
BEGIN
my_courses := CourseList('Econ 2010', 'Acct 3401', 'Mgmt 3100');
END;
PL/SQL Collections and Records
• Example: Constructor for a Varray
– In the next example, you pass three objects to constructor ProjectList(), which
returns a varray containing those objects:
DECLARE
TYPE ProjectList IS VARRAY(50) OF VARCHAR2(16);
accounting_projects ProjectList;
BEGIN
accounting_projects := ProjectList('Expense Report', 'Outsourcing', 'Auditing');
END;
PL/SQL Collections and Records
• Example: Combining Collection Declaration and
Constructor
– You can initialize a collection in its declaration, which is a good programming
practice:
DECLARE
TYPE CourseList IS TABLE OF VARCHAR2(16);
my_courses CourseList := CourseList('Art 1111', 'Hist 3100', 'Engl 2005');
BEGIN
NULL;
END;
PL/SQL Collections and Records
• Example: Nested Table Constructor Within a SQL
Statement
– In this example, you insert several scalar values and a CourseList nested table
into the SOPHOMORES table.
BEGIN
INSERT INTO sophomores
VALUES (5035, 'Janet Alvarez', '122 Broad St', 'FT',
CourseList('Econ 2010', 'Acct 3401', 'Mgmt 3100')
);
PL/SQL Collections and Records
• Referencing Collection Elements
– Every reference to an element includes a collection name and a subscript
enclosed in parentheses. The subscript determines which element is processed.
To reference an element, you specify its subscript using the syntax
Syntax : collection_name(subscript)
where subscript is an expression that yields an integer in most cases, or
a VARCHAR2 for associative arrays declared with strings as keys.
• The allowed subscript ranges are:
– For nested tables, 1 .. 2**31.
– For varrays, 1 .. size_limit, where you specify the limit in the declaration.
– For associative arrays with a numeric key, -2**31 .. 2**31.
– For associative arrays with a string key, the length of the key and number of
possible values depends on the VARCHAR2 length limit in the type declaration,
and the database character set.
PL/SQL Collections and Records
• Example: Referencing a Nested Table Element By
Subscript
– This example shows how to reference an element in the nested table NAMES:
DECLARE
TYPE Roster IS TABLE OF VARCHAR2(15);
names Roster := Roster('J Hamil', 'D Caruso', 'R Singh');
BEGIN
FOR i IN names.FIRST .. names.LAST
LOOP IF names(i) = 'J Hamil'
THEN
NULL;
END IF;
END LOOP;
END;
PL/SQL Collections and Records
• Assigning Collections
– One collection can be assigned to another by an INSERT, UPDATE, FETCH,
or SELECT statement, an assignment statement, or a subprogram call.
– You can assign the value of an expression to a specific element in a collection
using the syntax:
Syntax : collection_name(subscript) := expression;
• Example: Datatype Compatibility
DECLARE
TYPE Clientele IS VARRAY(100) OF Customer;
TYPE Vips IS VARRAY(100) OF Customer;
-- These first two variables have the same datatype.
group1 Clientele := Clientele(...);
group2 Clientele := Clientele(...);
-- This third variable has a similar declaration,
-- but is not the same type.
group3 Vips := Vips(...);
BEGIN
-- Allowed because they have the same datatype
group2 := group1;
-- Not allowed because they have different datatypes
group3 := group2;
END;
PL/SQL Collections and Records
• Example: Specifying Collection Element Types
with %TYPE and %ROWTYPE
– To specify the element type, you can use %TYPE,
which provides the datatype of a variable or
database column. Also, you can use %ROWTYPE,
which provides the rowtype of a cursor or
database table.
DECLARE
TYPE EmpList IS TABLE OF emp.ename%TYPE ; -- based on column
CURSOR c1 IS SELECT * FROM dept; TYPE DeptFile IS VARRAY(20) OF
c1%ROWTYPE; -- based on cursor
PL/SQL Collections and Records
• What Is a Record?
– A record is a group of related data items stored in fields, each with its own name and
datatype.
– Suppose you have various data about an employee such as name, salary, and hire date. These
items are logically related but dissimilar in type. A record containing a field for each item lets
you treat the data as a logical unit. Thus, records make it easier to organize and represent
information.
• Defining and Declaring Records
– To create records, you define a RECORD type, then declare records of that type. You can
define RECORD types in the declarative part of any PL/SQL block, subprogram, or package
using the syntax
Syntax : TYPE type_name IS RECORD (field_declaration[,field_declaration]...);
Note: Unlike VARRAY and (nested) TABLE types, RECORD types cannot be CREATEd and
stored in the database.
PL/SQL Collections and Records
• Example :
DECLARE
TYPE TimeRec IS RECORD (
seconds SMALLINT,
minutes SMALLINT,
hours SMALLINT);
TYPE FlightRec IS RECORD (
flight_no INTEGER,
plane_id VARCHAR2(10),
captain Employee, -- declare object
passengers PassengerList, -- declare varray
depart_time TimeRec, -- declare nested record
airport_code VARCHAR2(10));
BEGIN
NULL;
END;
PL/SQL Collections and Records
• Initializing Records
– The example below shows that you can initialize a record in its type definition. When you
declare a record of type TimeRec, its three fields assume an initial value of zero.
DECLARE TYPE
TimeRec IS RECORD ( secs SMALLINT := 0,
mins SMALLINT := 0,
hrs SMALLINT := 0);
BEGIN
...
END;
– Referencing Records
Unlike elements in a collection, which are accessed using subscripts, fields in a record are
accessed by name. To reference an individual field, use dot notation and the following syntax:
Syntax : record_name.field_name
For example, you reference field hire_date in record emp_info as follows:
emp_info.hire_date
BUILT-IN EXCEPTIONS
access_into_null ORA-06530
case_not_found ORA-06592
collection_is_null ORA-06531
cursor_already_open ORA-06511
dup_val_on_index ORA-00001
invalid_cursor ORA-01001
invalid_number ORA-01722
login_denied ORA-01017
no_data_found ORA-01403
not_logged_on ORA-01012
program_error ORA-06501
rowtype_mismatch ORA-06504
self_is_null ORA-30625
storage_error ORA-06500
subscript_beyond_count ORA-06533
subscript_outside_limit ORA-06532
sys_invalid_rowid ORA-01410
timeout_on_resource ORA-00051
too_many_rows ORA-01422
value_error ORA-06502
zero_divide ORA-01476
Subprograms
• Subprograms are named PL/SQL blocks that can take parameters
and be invoked. PL/SQL has two types of subprograms
called procedures and functions. Generally, you use a procedure to
perform an action and a function to compute a value.
• Like unnamed or anonymous PL/SQL blocks, subprograms have a
declarative part, an executable part, and an optional exception-
handling part.
• Subprograms provide extensibility; that is, they let you tailor the
PL/SQL language to suit your needs
• Subprograms also provide modularity; that is, they let you break a
program down into manageable, well-defined modules
• subprograms promote reusability and maintainability
• subprograms aid abstraction, the mental process of deriving a
universal from particulars
• You can also declare PL/SQL subprograms in anonymous blocks
• PL/SQL subprograms are procedures and functions
Subprograms - Procedures
• Also called as stored procedures
• A procedure has two parts: the specification (spec for short)
and the body.
• The procedure spec begins with the
keyword PROCEDURE and ends with the procedure name or
a parameter list. Parameter declarations are optional.
Procedures that take no parameters are written without
parentheses.
• The procedure body begins with the keyword IS (or AS) and
ends with the keyword END followed by an optional
procedure name. The procedure body has three parts: a
declarative part, an executable part, and an optional
exception-handling part.
Subprograms - Functions
• Also called as stored functions
• Like a procedure, a function has two parts: the spec
and the body. The function spec begins with the
keyword FUNCTION and ends with
the RETURN clause, which specifies the datatype of
the return value. Parameter declarations are optional.
Functions that take no parameters are written without
parentheses.
• The function body begins with the keyword IS (or AS)
and ends with the keyword END followed by an
optional function name. The function body has three
parts: a declarative part, an executable part, and an
optional exception-handling part.
Subprograms - Parameters
• Subprograms pass information
using parameters
• The variables or expressions referenced in the
parameter list of a subprogram call
are actual parameters
• The variables declared in a subprogram spec
and referenced in the subprogram body
are formal parameters
• A good programming practice is to use
different names for actual and formal
parameters
Subprograms - Parameters
• When calling a subprogram, you can write
the actual parameters using either
positional or named notation
• You use parameter modes to define the
behavior of formal parameters. The three
parameter modes, IN (the default), OUT,
and IN OUT, can be used with any
subprogram
Subprograms - Recursion
• Recursion is a powerful technique for simplifying the
design of algorithms.
• Basically, recursion means self-reference. In a
recursive mathematical sequence, each term is derived
by applying a formula to preceding terms.
• A recursive subprogram is one that calls itself. Think of
a recursive call as a call to some other subprogram that
does the same task as your subprogram. Each
recursive call creates a new instance of any items
declared in the subprogram, including parameters,
variables, cursors, and exceptions. Likewise, new
instances of SQL statements are created at each level
in the recursive descent.
Subprograms - Recursion
FUNCTION factorial (n POSITIVE)
RETURN INTEGER
IS -- returns n!
BEGIN
IF n = 1 THEN -- terminating condition
RETURN 1;
ELSE
RETURN n * factorial (n - 1); -- recursive call
END IF;
END factorial ;
Subprograms – Recursion vs
Iteration
-- recursive version
FUNCTION fib (n POSITIVE)
RETURN INTEGER
IS
BEGIN
IF (n = 1) OR (n = 2) THEN
RETURN 1;
ELSE
RETURN fib(n - 1) + fib(n - 2);
END IF;
END fib;
Subprograms – Recursion vs
Iteration
-- iterative version
FUNCTION fib (n POSITIVE)
RETURN INTEGER
IS
pos1 INTEGER := 1;
pos2 INTEGER := 0;
accumulator INTEGER;
BEGIN IF (n = 1) OR (n = 2) THEN
RETURN 1;
ELSE accumulator := pos1 + pos2;
FOR i IN 3..n LOOP
pos2 := pos1;
pos1 := accumulator;
accumulator := pos1 + pos2;
END LOOP;
RETURN accumulator;
END IF;
END fib;

More Related Content

What's hot

Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsqlArun Sial
 
Oracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideOracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideSrinimf-Slides
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...rehaniltifat
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSmohdoracle
 
PL/SQL - CURSORS
PL/SQL - CURSORSPL/SQL - CURSORS
PL/SQL - CURSORSIshaRana14
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sqlÑirmal Tatiwal
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaEdureka!
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadatarehaniltifat
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexingMahabubur Rahaman
 
All of the Performance Tuning Features in Oracle SQL Developer
All of the Performance Tuning Features in Oracle SQL DeveloperAll of the Performance Tuning Features in Oracle SQL Developer
All of the Performance Tuning Features in Oracle SQL DeveloperJeff Smith
 
Displaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseDisplaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseSalman Memon
 

What's hot (20)

Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
 
Oracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideOracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step Guide
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Cursors.ppt
Cursors.pptCursors.ppt
Cursors.ppt
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
 
Cursores.ppt
Cursores.pptCursores.ppt
Cursores.ppt
 
PL/SQL - CURSORS
PL/SQL - CURSORSPL/SQL - CURSORS
PL/SQL - CURSORS
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 
All of the Performance Tuning Features in Oracle SQL Developer
All of the Performance Tuning Features in Oracle SQL DeveloperAll of the Performance Tuning Features in Oracle SQL Developer
All of the Performance Tuning Features in Oracle SQL Developer
 
Displaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseDisplaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data Base
 
Oracle Database Trigger
Oracle Database TriggerOracle Database Trigger
Oracle Database Trigger
 
Sql oracle
Sql oracleSql oracle
Sql oracle
 

Viewers also liked

PL SQL Quiz | PL SQL Examples
PL SQL Quiz |  PL SQL ExamplesPL SQL Quiz |  PL SQL Examples
PL SQL Quiz | PL SQL ExamplesShubham Dwivedi
 
Migrating to a New DBMS
Migrating to a New DBMSMigrating to a New DBMS
Migrating to a New DBMSStephen Conant
 
10g plsql slide
10g plsql slide10g plsql slide
10g plsql slideTanu_Manu
 
R - Software Estatistico
R - Software EstatisticoR - Software Estatistico
R - Software EstatisticoIvan Ricarte
 
Plsql quick guide
Plsql quick guidePlsql quick guide
Plsql quick guide1bi08me024
 
ORACLE, SQL, PL/SQL Made very very Easy Happy Learning....
ORACLE, SQL, PL/SQL Made very very Easy Happy Learning....ORACLE, SQL, PL/SQL Made very very Easy Happy Learning....
ORACLE, SQL, PL/SQL Made very very Easy Happy Learning....Racharla Rohit Varma
 
Advantages of pl sql
Advantages of pl sqlAdvantages of pl sql
Advantages of pl sqlIntellipaat
 
Oracle - Program with PL/SQL - Lession 12
Oracle - Program with PL/SQL - Lession 12Oracle - Program with PL/SQL - Lession 12
Oracle - Program with PL/SQL - Lession 12Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 14
Oracle - Program with PL/SQL - Lession 14Oracle - Program with PL/SQL - Lession 14
Oracle - Program with PL/SQL - Lession 14Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 13
Oracle - Program with PL/SQL - Lession 13Oracle - Program with PL/SQL - Lession 13
Oracle - Program with PL/SQL - Lession 13Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 15
Oracle - Program with PL/SQL - Lession 15Oracle - Program with PL/SQL - Lession 15
Oracle - Program with PL/SQL - Lession 15Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Thuan Nguyen
 
Oracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guideOracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guidebupbechanhgmail
 
Oracle - Program with PL/SQL - Lession 08
Oracle - Program with PL/SQL - Lession 08Oracle - Program with PL/SQL - Lession 08
Oracle - Program with PL/SQL - Lession 08Thuan Nguyen
 

Viewers also liked (20)

PL SQL Quiz | PL SQL Examples
PL SQL Quiz |  PL SQL ExamplesPL SQL Quiz |  PL SQL Examples
PL SQL Quiz | PL SQL Examples
 
Chapter8 pl sql
Chapter8 pl sqlChapter8 pl sql
Chapter8 pl sql
 
Migrating to a New DBMS
Migrating to a New DBMSMigrating to a New DBMS
Migrating to a New DBMS
 
10g plsql slide
10g plsql slide10g plsql slide
10g plsql slide
 
R - Software Estatistico
R - Software EstatisticoR - Software Estatistico
R - Software Estatistico
 
Plsql quick guide
Plsql quick guidePlsql quick guide
Plsql quick guide
 
Exercise 6
Exercise 6Exercise 6
Exercise 6
 
Sql pl
Sql plSql pl
Sql pl
 
ORACLE, SQL, PL/SQL Made very very Easy Happy Learning....
ORACLE, SQL, PL/SQL Made very very Easy Happy Learning....ORACLE, SQL, PL/SQL Made very very Easy Happy Learning....
ORACLE, SQL, PL/SQL Made very very Easy Happy Learning....
 
Advantages of pl sql
Advantages of pl sqlAdvantages of pl sql
Advantages of pl sql
 
Oracle - Program with PL/SQL - Lession 12
Oracle - Program with PL/SQL - Lession 12Oracle - Program with PL/SQL - Lession 12
Oracle - Program with PL/SQL - Lession 12
 
Oracle - Program with PL/SQL - Lession 14
Oracle - Program with PL/SQL - Lession 14Oracle - Program with PL/SQL - Lession 14
Oracle - Program with PL/SQL - Lession 14
 
Oracle - Program with PL/SQL - Lession 13
Oracle - Program with PL/SQL - Lession 13Oracle - Program with PL/SQL - Lession 13
Oracle - Program with PL/SQL - Lession 13
 
Oracle - Program with PL/SQL - Lession 15
Oracle - Program with PL/SQL - Lession 15Oracle - Program with PL/SQL - Lession 15
Oracle - Program with PL/SQL - Lession 15
 
Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17
 
Oracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guideOracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guide
 
Oracle - Program with PL/SQL - Lession 08
Oracle - Program with PL/SQL - Lession 08Oracle - Program with PL/SQL - Lession 08
Oracle - Program with PL/SQL - Lession 08
 

Similar to pl/sql online Training|sql online Training | iTeknowledge

Querying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptxQuerying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptxQuyVo27
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_materialgayaramesh
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusChhom Karath
 
2008 2086 Gangler
2008 2086 Gangler2008 2086 Gangler
2008 2086 GanglerSecure-24
 
Oracle Fundamental and PL-SQL.docx
Oracle Fundamental and PL-SQL.docxOracle Fundamental and PL-SQL.docx
Oracle Fundamental and PL-SQL.docxChandan Kumar
 
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxshivanikaale214
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5Pranab Dasgupta
 
Oracle Database Interview Questions -PART 1 | sql, plsql, dbms, scenario base...
Oracle Database Interview Questions -PART 1 | sql, plsql, dbms, scenario base...Oracle Database Interview Questions -PART 1 | sql, plsql, dbms, scenario base...
Oracle Database Interview Questions -PART 1 | sql, plsql, dbms, scenario base...PrabhatKumar591
 
PLSQL Notes.pptx
PLSQL Notes.pptxPLSQL Notes.pptx
PLSQL Notes.pptxSHRISANJAY4
 

Similar to pl/sql online Training|sql online Training | iTeknowledge (20)

Querying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptxQuerying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptx
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_material
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*Plus
 
Unit 4 plsql
Unit 4  plsqlUnit 4  plsql
Unit 4 plsql
 
2008 2086 Gangler
2008 2086 Gangler2008 2086 Gangler
2008 2086 Gangler
 
Oracle Fundamental and PL-SQL.docx
Oracle Fundamental and PL-SQL.docxOracle Fundamental and PL-SQL.docx
Oracle Fundamental and PL-SQL.docx
 
PHP - Introduction to Advanced SQL
PHP - Introduction to Advanced SQLPHP - Introduction to Advanced SQL
PHP - Introduction to Advanced SQL
 
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5
 
Resume_of_sayeed
Resume_of_sayeedResume_of_sayeed
Resume_of_sayeed
 
Database part2-
Database part2-Database part2-
Database part2-
 
DBMS UNIT 3
DBMS UNIT 3DBMS UNIT 3
DBMS UNIT 3
 
Oracle Database Interview Questions -PART 1 | sql, plsql, dbms, scenario base...
Oracle Database Interview Questions -PART 1 | sql, plsql, dbms, scenario base...Oracle Database Interview Questions -PART 1 | sql, plsql, dbms, scenario base...
Oracle Database Interview Questions -PART 1 | sql, plsql, dbms, scenario base...
 
sql-commands.pdf
sql-commands.pdfsql-commands.pdf
sql-commands.pdf
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql commands
Sql commandsSql commands
Sql commands
 
Oracle 11g sql plsql training
Oracle 11g sql plsql trainingOracle 11g sql plsql training
Oracle 11g sql plsql training
 
PLSQL Notes.pptx
PLSQL Notes.pptxPLSQL Notes.pptx
PLSQL Notes.pptx
 
Pl sql content
Pl sql contentPl sql content
Pl sql content
 
DB2 on Mainframe
DB2 on MainframeDB2 on Mainframe
DB2 on Mainframe
 

Recently uploaded

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 

Recently uploaded (20)

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 

pl/sql online Training|sql online Training | iTeknowledge

  • 2. Contents • What is PL/SQL • Overview of PL/SQL – Understanding the Main Features of PL/SQL – PL/SQL Architecture – Advantages of PL/SQL • Fundamentals of PL/SQL – Character Set – Lexical Units – Literals – Declarations – PL/SQL Naming Conventions – Scope and Visibility of PL/SQL – Identifiers Variable Assignment – PL/SQL Expressions and Comparisons
  • 3. Contents • PL/SQL Datatypes – Predefined Datatypes – User-Defined Subtypes – Datatype Conversion • PL/SQL Control Structures – Overview of PL/SQL Control Structures – Conditional Control: IF and CASE Statements – Iterative Control: LOOP and EXIT Statements – Sequential Control: GOTO and NULL Statements • PL/SQL Collections and Records – What Is a Collection? – Choosing Which PL/SQL Collection Types to Use – What Is a Record?
  • 4. Contents • Interaction Between PL/SQL and Oracle – Overview of SQL Support in PL/SQL – Managing Cursors – Using Cursor FOR Loops – Defining REF CURSOR Types – Using Cursor Attributes – Using Cursor Expressions – Parameterized Cursors – FOR UPDATE , WHERE CURRENT OF • Overview of Transaction Processing in PL/SQL
  • 5. Contents • Handling PL/SQL Errors – Overview of PL/SQL Error Handling – Advantages of PL/SQL Exceptions – Predefined PL/SQL Exceptions – Defining Your Own PL/SQL Exceptions – How PL/SQL Exceptions Are Raised – Handling Raised PL/SQL Exceptions – How PL/SQL Exceptions Propagate
  • 6. Contents • PL/SQL Subprograms – What Are Subprograms? – Declaring PL/SQL Subprograms – Understanding PL/SQL Procedures – Understanding PL/SQL Functions – Actual Versus Formal Subprogram Parameters – Positional Versus Named Notation for Subprogram Parameters – Specifying Subprogram Parameter Modes – Understanding and Using Recursion
  • 7. Contents • PL/SQL Packages – What Is a PL/SQL Package? – Advantages of PL/SQL Packages – Understanding The Package Spec – Understanding The Package Body – Private Versus Public Items in Packages – How Package STANDARD Defines the PL/SQL Environment – Overview of Product-Specific Packages
  • 8. Contents • PL/SQL Object Types – Object Oriented Features – The Role of Abstraction – What Is an Object Type? – Why Use Object Types? – Structure of an Object Type – Components of an Object Type – Defining Object Types – Declaring and Initializing Objects – Manipulating Objects
  • 9. Contents • Native Dynamic SQL – Using the EXECUTE IMMEDIATE Statement – Using the OPEN-FOR, FETCH, and CLOSE Statements
  • 10. What is PL/SQL • PL/SQL is an imperative 3GL that was designed specifically for the seamless processing of SQL commands. It provides specific syntax for this purpose and supports exactly the same datatypes as SQL. Server- side PL/SQL is stored and compiled in Oracle Database and runs within the Oracle executable. It automatically inherits the robustness, security, and portability of Oracle Database
  • 11. Overview of PL/SQL • Main Features Of PL/SQL – Error Handling – Blocks – Variables and Constants – Subprograms – Packages – Triggers – Input and Output – Data Abstraction – Control Statements – Conditional Compilation – Processing a Query Result Set One Row at a Time
  • 15. Advantages Of PL/SQL • PL/SQL has these advantages: – Tight Integration with SQL – High Performance – High Productivity – Portability – Scalability – Manageability – Support for Object-Oriented Programming – Support for Developing Web Applications – Support for Developing Server Pages
  • 16. Fundamentals Of PL/SQL (Character Set) • The PL/SQL character set includes – the upper- and lower-case letters A .. Z and a .. Z – the numerals 0 .. 9 – the symbols ( ) + - * / < > = ! ~ ^ ; : . ' @ % , " # $ & _ | { } ? [ ] – tabs, spaces, and carriage returns • PL/SQL is not case sensitive, so lower-case letters are equivalent to corresponding upper-case letters except within string and character literals.
  • 17. Fundamentals Of PL/SQL (Lexical Units) • A line of PL/SQL text contains groups of characters known as lexical units, which can be classified as follows: – delimiters (simple and compound symbols) – identifiers, which include reserved words – Literals – comments
  • 18. Fundamentals Of PL/SQL (Literal) • Literals – Numeric Literals • Integer Literals(030 , 6,-14,0,+2767) • Real Literals(6,7 0.0 ,-12.0,3.14159) – Character Literals ('6.66Z' '%' '7' ' ' 'z' '(‘) ) – String Literals(‘He said “Life is like licking honey from a thorn.“’) – Boolean Literals (TRUE, FALSE, NULL) – Datetime Literals – DECLARE d1 DATE := DATE '1998-12-25'; – t1 TIMESTAMP := TIMESTAMP '1997-10-22 13:01:01'; t2 TIMESTAMP WITH TIME ZONE := TIMESTAMP '1997-01-31 09:26:56.66 +02:00';
  • 19. Fundamentals Of PL/SQL (Declarations) • Your program stores values in variables and constants. As the program executes, the values of variables can change, but the values of constants cannot. • You can declare variables and constants in the declarative part of any PL/SQL block, subprogram, or package. Declarations allocate storage space for a value, specify its datatype, and name the storage location so that you can reference it. • Using DEFALUT (hours_worked INTEGER DEFAULT 40;) • Using NOT NULL (acct_id INTEGER(4) NOT NULL := 9999;)
  • 20. Fundamentals Of PL/SQL (Naming Conventions) • The same naming conventions apply to all PL/SQL program items and units including constants, variables, cursors, cursor variables, exceptions, procedures, functions, and packages. Names can be simple, qualified, remote, or both qualified and remote. For example, you might use the procedure name raise_salary in any of the following ways: – raise_salary(...); -- simple – emp_actions.raise_salary(...); -- qualified raise_salary@newyork(...); -- remote emp_actions.raise_salary@newyork(...); -- qualified and remote
  • 22. Fundamentals Of PL/SQL (Variable Assignment) • Variables and constants are initialized every time a block or subprogram is entered. By default, variables are initialized to NULL. Unless you expressly initialize a variable, its value is undefined: DECLARE count INTEGER; BEGIN -- COUNT began with a value of NULL. -- Thus the expression 'COUNT + 1' is also null. -- So after this assignment, COUNT is still NULL. count := count + 1;
  • 23. Fundamentals Of PL/SQL (PL/SQL Expressions and Comparisons) • Expressions are constructed using operands and operators. An operand is a variable, constant, literal, or function call that contributes a value to an expression • The simplest expressions consist of a single variable, which yields a value directly. PL/SQL evaluates (finds the current value of) an expression by combining the values of the operands in ways specified by the operators. This always yields a single value and datatype. • PL/SQL determines the datatype by examining the expression and the context in which it appears.
  • 24. Fundamentals Of PL/SQL (PL/SQL Expressions and Comparisons) • Operator precedence
  • 25. Fundamentals Of PL/SQL (PL/SQL Expressions and Comparisons) • Logical Truth Table
  • 26. Fundamentals Of PL/SQL (PL/SQL Expressions and Comparisons) • Relational Operators • IS NULL • BETWEEN • IN • NOT IN
  • 27. PL/SQL Data Types • Every constant, variable, and parameter has a datatype (or type), which specifies a storage format, constraints, and valid range of values. PL/SQL provides a variety of predefined datatypes. For instance, you can choose from integer, floating point, character, Boolean, date, collection, reference, and LOB types. In addition, PL/SQL lets you define your own subtypes. This chapter covers the basic types used frequently in PL/SQL programs – Predefined Datatypes – User-Defined Subtypes – Datatype Conversion
  • 28. PL/SQL Data Types • A scalar type has no internal components. • A composite type has internal components that can be manipulated individually. • A reference type holds values, called pointers, that designate other program items. • A LOB type holds values, called lob locators, that specify the location of large objects (graphic images for example) stored out-of- line.
  • 29. PL/SQL Data Types • Built-in data types
  • 30. PL/SQL Data Types • Different Maximum Sizes
  • 31. PL/SQL Data Types • Different Maximum Sizes for NUMBER Types • BINARY_INTEGER datatype to store signed integers. Its magnitude range is -2**31 .. 2**31 • NUMBER datatype to store fixed-point or floating-point numbers. Its magnitude range is 1E-130 .. 10E125 • PLS_INTEGER datatype to store signed integers. Its magnitude range is - 2**31 .. 2**31
  • 32. PL/SQL Data Types • The LOB (large object) datatypes BFILE, BLOB, CLOB, and NCLOB let you store blocks of unstructured data (such as text, graphic images, video clips, and sound waveforms) up to four gigabytes in size. • Fundamental to working with LOBs is the concept of a LOB locator. A LOB locator is a pointer to large object data in a database. • LOB types store lob locators, which point to large objects stored in an external file, in-line (inside the row) or out-of-line (outside the row). Database columns of type BLOB, CLOB, NCLOB, or BFILE store the locators. • BLOB, CLOB, and NCLOB data is stored in the database, in or outside the row. • BFILE data is stored in operating system files outside the database.
  • 34. PL/SQL Data Types • User-Defined Subtypes – Each PL/SQL base type specifies a set of values and a set of operations applicable to items of that type. Subtypes specify the same set of operations as their base type but only a subset of its values. Thus, a subtype does not introduce a new type; it merely places an optional constraint on its base type. – Subtypes can increase reliability, provide compatibility with ANSI/ISO types, and improve readability by indicating the intended use of constants and variables. PL/SQL predefines several subtypes in package STANDARD. – Examples: • SUBTYPE CHARACTER IS CHAR; • SUBTYPE INTEGER IS NUMBER(38,0);
  • 35. PL/SQL Data Types – NUMBER Subtypes • BINARY_INTEGER subtypes: – NATURAL - Only non-negative or positive values – NATURALN – prevents assigning of nulls to an integer variable – POSITIVE - Only non-negative or positive values – POSITIVEN - prevents assigning of nulls to an integer variable – SIGNTYPE- restrict an integer variable to the values -1, 0, and 1 • NUMBER subtypes: – DEC - fixed-point numbers with a maximum precision of 38 decimal digit – DECIMAL - fixed-point numbers with a maximum precision of 38 decimal digit – DOUBLE PRECISION - floating-point numbers with a maximum precision of 126 binary digits – FLOAT - floating-point numbers with a maximum precision of 126 binary digits – INTEGER - to declare integers with a maximum precision of 38 decimal digits – INT - to declare integers with a maximum precision of 38 decimal digits – NUMERIC - fixed-point numbers with a maximum precision of 38 decimal digit – REAL - floating-point numbers with a maximum precision of 63 binary digits – SMALLINT - to declare integers with a maximum precision of 38 decimal digits
  • 36. PL/SQL Data Types • Defining Subtypes • You can define your own subtypes in the declarative part of any PL/SQL block, subprogram, or package using the syntax – SUBTYPE subtype_name IS base_type[(constraint)] [NOT NULL]; • Some more examples
  • 37. PL/SQL Data Types • Datatype Conversion – Explicit Conversion • To convert values from one datatype to another, you use built-in functions. For example, to convert a CHAR value to a DATE or NUMBER value, you use the function TO_DATE or TO_NUMBER, respectively. Conversely, to convert a DATE or NUMBER value to a CHAR value, you use the function TO_CHAR. – Implicit Conversion • When it makes sense, PL/SQL can convert the datatype of a value implicitly
  • 38. PL/SQL Data Types • Datatype Conversion
  • 39. PL/SQL Data Types • Implicit Conversion table
  • 41. PL/SQL Control Structures • Conditional Control: – IF and CASE Statements
  • 42. PL/SQL Control Structures • CASE Expression – A CASE expression selects a result from one or more alternatives, and returns the result. The CASE expression uses a selector, an expression whose value determines which alternative to return
  • 43. PL/SQL Control Structures • A searched CASE expression has no selector. Each WHEN clause contains a search condition that yields a Boolean value, which lets you test different variables or multiple conditions in a single WHEN clause
  • 44. PL/SQL Control Structures • Iterative Control: LOOP and EXIT Statements
  • 45. PL/SQL Control Structures • Iterative Control: WHILE-LOOP, FOR-LOOP
  • 46. PL/SQL Control Structures • Sequential Control: GOTO and NULL Statements
  • 47. PL/SQL Collections and Records • Many programming techniques use collection types such as arrays, bags, lists, nested tables, sets, and trees. To support these techniques in database applications, PL/SQL provides the datatypes TABLE and VARRAY, which allow you to declare index-by tables, nested tables and variable-size arrays.
  • 48. PL/SQL Collections and Records • What is a Collection ? – 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 – 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. • Although collections can have only one dimension, you can model multi-dimensional arrays by creating collections whose elements are also collections.
  • 50. PL/SQL Collections and Records • Understanding Associative Arrays (Index-By Tables) – An associative array (also called an index-by table) is a set of key- value pairs. Each key is unique, and is used to locate the corresponding value. The key can be either an integer or a string. – Using a key-value pair for the first time adds that pair to the associative array. Using the same key with a different value changes the value.
  • 51. PL/SQL Collections and Records • Understanding Nested Tables – Conceptually, a nested table is like a one-dimensional array with an arbitrary number of elements. – Within the database, a nested table is a column type that holds a set of values. The database stores the rows of a nested table in no particular order. When you retrieve a nested table from the database into a PL/SQL variable, the rows are given consecutive subscripts starting at 1. These subscripts give you array-like access to individual rows. – A nested table differs from an array in these important ways: – An array has a declared number of elements, but a nested table does not. The size of a nested table can increase dynamically (however, a maximum limit is imposed – An array is always dense (that is, it always has consecutive subcripts). A nested array is dense initially, but it can become sparse, because you can delete elements from it.
  • 52. PL/SQL Collections and Records • Understanding Variable-Size Arrays (Varrays) – A variable-size array (varray) is an item of the data type VARRAY. A varray has a maximum size, which you specify in its type definition. A varray can contain a varying number of elements, from zero (when empty) to the maximum size. – A varray index has a fixed lower bound of 1 and an extensible upper bound. To access an element of a varray, you standard subscripting syntax.
  • 53. PL/SQL Collections and Records Declaring Collection Types
  • 54. PL/SQL Collections and Records • Initializing and Referencing Collections – Until you initialize it, a nested table or varray is atomically null: the collection itself is null, not its elements. – To initialize a nested table or varray, you use a constructor, a system-defined function with the same name as the collection type. This function "constructs" collections from the elements passed to it.
  • 55. PL/SQL Collections and Records • Example: Constructor for a Nested Table – In the following example, you pass multiple elements to the constructor CourseList(), which returns a nested table containing those elements: DECLARE TYPE CourseList IS TABLE OF VARCHAR2(16); my_courses CourseList; BEGIN my_courses := CourseList('Econ 2010', 'Acct 3401', 'Mgmt 3100'); END;
  • 56. PL/SQL Collections and Records • Example: Constructor for a Varray – In the next example, you pass three objects to constructor ProjectList(), which returns a varray containing those objects: DECLARE TYPE ProjectList IS VARRAY(50) OF VARCHAR2(16); accounting_projects ProjectList; BEGIN accounting_projects := ProjectList('Expense Report', 'Outsourcing', 'Auditing'); END;
  • 57. PL/SQL Collections and Records • Example: Combining Collection Declaration and Constructor – You can initialize a collection in its declaration, which is a good programming practice: DECLARE TYPE CourseList IS TABLE OF VARCHAR2(16); my_courses CourseList := CourseList('Art 1111', 'Hist 3100', 'Engl 2005'); BEGIN NULL; END;
  • 58. PL/SQL Collections and Records • Example: Nested Table Constructor Within a SQL Statement – In this example, you insert several scalar values and a CourseList nested table into the SOPHOMORES table. BEGIN INSERT INTO sophomores VALUES (5035, 'Janet Alvarez', '122 Broad St', 'FT', CourseList('Econ 2010', 'Acct 3401', 'Mgmt 3100') );
  • 59. PL/SQL Collections and Records • Referencing Collection Elements – Every reference to an element includes a collection name and a subscript enclosed in parentheses. The subscript determines which element is processed. To reference an element, you specify its subscript using the syntax Syntax : collection_name(subscript) where subscript is an expression that yields an integer in most cases, or a VARCHAR2 for associative arrays declared with strings as keys. • The allowed subscript ranges are: – For nested tables, 1 .. 2**31. – For varrays, 1 .. size_limit, where you specify the limit in the declaration. – For associative arrays with a numeric key, -2**31 .. 2**31. – For associative arrays with a string key, the length of the key and number of possible values depends on the VARCHAR2 length limit in the type declaration, and the database character set.
  • 60. PL/SQL Collections and Records • Example: Referencing a Nested Table Element By Subscript – This example shows how to reference an element in the nested table NAMES: DECLARE TYPE Roster IS TABLE OF VARCHAR2(15); names Roster := Roster('J Hamil', 'D Caruso', 'R Singh'); BEGIN FOR i IN names.FIRST .. names.LAST LOOP IF names(i) = 'J Hamil' THEN NULL; END IF; END LOOP; END;
  • 61. PL/SQL Collections and Records • Assigning Collections – One collection can be assigned to another by an INSERT, UPDATE, FETCH, or SELECT statement, an assignment statement, or a subprogram call. – You can assign the value of an expression to a specific element in a collection using the syntax: Syntax : collection_name(subscript) := expression; • Example: Datatype Compatibility DECLARE TYPE Clientele IS VARRAY(100) OF Customer; TYPE Vips IS VARRAY(100) OF Customer; -- These first two variables have the same datatype. group1 Clientele := Clientele(...); group2 Clientele := Clientele(...); -- This third variable has a similar declaration, -- but is not the same type. group3 Vips := Vips(...); BEGIN -- Allowed because they have the same datatype group2 := group1; -- Not allowed because they have different datatypes group3 := group2; END;
  • 62. PL/SQL Collections and Records • Example: Specifying Collection Element Types with %TYPE and %ROWTYPE – To specify the element type, you can use %TYPE, which provides the datatype of a variable or database column. Also, you can use %ROWTYPE, which provides the rowtype of a cursor or database table. DECLARE TYPE EmpList IS TABLE OF emp.ename%TYPE ; -- based on column CURSOR c1 IS SELECT * FROM dept; TYPE DeptFile IS VARRAY(20) OF c1%ROWTYPE; -- based on cursor
  • 63. PL/SQL Collections and Records • What Is a Record? – A record is a group of related data items stored in fields, each with its own name and datatype. – Suppose you have various data about an employee such as name, salary, and hire date. These items are logically related but dissimilar in type. A record containing a field for each item lets you treat the data as a logical unit. Thus, records make it easier to organize and represent information. • Defining and Declaring Records – To create records, you define a RECORD type, then declare records of that type. You can define RECORD types in the declarative part of any PL/SQL block, subprogram, or package using the syntax Syntax : TYPE type_name IS RECORD (field_declaration[,field_declaration]...); Note: Unlike VARRAY and (nested) TABLE types, RECORD types cannot be CREATEd and stored in the database.
  • 64. PL/SQL Collections and Records • Example : DECLARE TYPE TimeRec IS RECORD ( seconds SMALLINT, minutes SMALLINT, hours SMALLINT); TYPE FlightRec IS RECORD ( flight_no INTEGER, plane_id VARCHAR2(10), captain Employee, -- declare object passengers PassengerList, -- declare varray depart_time TimeRec, -- declare nested record airport_code VARCHAR2(10)); BEGIN NULL; END;
  • 65. PL/SQL Collections and Records • Initializing Records – The example below shows that you can initialize a record in its type definition. When you declare a record of type TimeRec, its three fields assume an initial value of zero. DECLARE TYPE TimeRec IS RECORD ( secs SMALLINT := 0, mins SMALLINT := 0, hrs SMALLINT := 0); BEGIN ... END; – Referencing Records Unlike elements in a collection, which are accessed using subscripts, fields in a record are accessed by name. To reference an individual field, use dot notation and the following syntax: Syntax : record_name.field_name For example, you reference field hire_date in record emp_info as follows: emp_info.hire_date
  • 66. BUILT-IN EXCEPTIONS access_into_null ORA-06530 case_not_found ORA-06592 collection_is_null ORA-06531 cursor_already_open ORA-06511 dup_val_on_index ORA-00001 invalid_cursor ORA-01001 invalid_number ORA-01722 login_denied ORA-01017 no_data_found ORA-01403 not_logged_on ORA-01012 program_error ORA-06501 rowtype_mismatch ORA-06504 self_is_null ORA-30625 storage_error ORA-06500 subscript_beyond_count ORA-06533 subscript_outside_limit ORA-06532 sys_invalid_rowid ORA-01410 timeout_on_resource ORA-00051 too_many_rows ORA-01422 value_error ORA-06502 zero_divide ORA-01476
  • 67. Subprograms • Subprograms are named PL/SQL blocks that can take parameters and be invoked. PL/SQL has two types of subprograms called procedures and functions. Generally, you use a procedure to perform an action and a function to compute a value. • Like unnamed or anonymous PL/SQL blocks, subprograms have a declarative part, an executable part, and an optional exception- handling part. • Subprograms provide extensibility; that is, they let you tailor the PL/SQL language to suit your needs • Subprograms also provide modularity; that is, they let you break a program down into manageable, well-defined modules • subprograms promote reusability and maintainability • subprograms aid abstraction, the mental process of deriving a universal from particulars • You can also declare PL/SQL subprograms in anonymous blocks • PL/SQL subprograms are procedures and functions
  • 68. Subprograms - Procedures • Also called as stored procedures • A procedure has two parts: the specification (spec for short) and the body. • The procedure spec begins with the keyword PROCEDURE and ends with the procedure name or a parameter list. Parameter declarations are optional. Procedures that take no parameters are written without parentheses. • The procedure body begins with the keyword IS (or AS) and ends with the keyword END followed by an optional procedure name. The procedure body has three parts: a declarative part, an executable part, and an optional exception-handling part.
  • 69. Subprograms - Functions • Also called as stored functions • Like a procedure, a function has two parts: the spec and the body. The function spec begins with the keyword FUNCTION and ends with the RETURN clause, which specifies the datatype of the return value. Parameter declarations are optional. Functions that take no parameters are written without parentheses. • The function body begins with the keyword IS (or AS) and ends with the keyword END followed by an optional function name. The function body has three parts: a declarative part, an executable part, and an optional exception-handling part.
  • 70. Subprograms - Parameters • Subprograms pass information using parameters • The variables or expressions referenced in the parameter list of a subprogram call are actual parameters • The variables declared in a subprogram spec and referenced in the subprogram body are formal parameters • A good programming practice is to use different names for actual and formal parameters
  • 71. Subprograms - Parameters • When calling a subprogram, you can write the actual parameters using either positional or named notation • You use parameter modes to define the behavior of formal parameters. The three parameter modes, IN (the default), OUT, and IN OUT, can be used with any subprogram
  • 72. Subprograms - Recursion • Recursion is a powerful technique for simplifying the design of algorithms. • Basically, recursion means self-reference. In a recursive mathematical sequence, each term is derived by applying a formula to preceding terms. • A recursive subprogram is one that calls itself. Think of a recursive call as a call to some other subprogram that does the same task as your subprogram. Each recursive call creates a new instance of any items declared in the subprogram, including parameters, variables, cursors, and exceptions. Likewise, new instances of SQL statements are created at each level in the recursive descent.
  • 73. Subprograms - Recursion FUNCTION factorial (n POSITIVE) RETURN INTEGER IS -- returns n! BEGIN IF n = 1 THEN -- terminating condition RETURN 1; ELSE RETURN n * factorial (n - 1); -- recursive call END IF; END factorial ;
  • 74. Subprograms – Recursion vs Iteration -- recursive version FUNCTION fib (n POSITIVE) RETURN INTEGER IS BEGIN IF (n = 1) OR (n = 2) THEN RETURN 1; ELSE RETURN fib(n - 1) + fib(n - 2); END IF; END fib;
  • 75. Subprograms – Recursion vs Iteration -- iterative version FUNCTION fib (n POSITIVE) RETURN INTEGER IS pos1 INTEGER := 1; pos2 INTEGER := 0; accumulator INTEGER; BEGIN IF (n = 1) OR (n = 2) THEN RETURN 1; ELSE accumulator := pos1 + pos2; FOR i IN 3..n LOOP pos2 := pos1; pos1 := accumulator; accumulator := pos1 + pos2; END LOOP; RETURN accumulator; END IF; END fib;