Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć2Schedule: Timing Topic 60 minutes Lecture 30 minutes Practice 90 minutes Total... Introduction to Oracle: SQL and PL/SQ
Trang 1Developing a Simple PL/SQL
Block
21
Trang 2Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć2
Schedule: Timing Topic
60 minutes Lecture
30 minutes Practice
90 minutes Total
Trang 3In this lesson, you create a simple PL/SQL block after learning the various elements that compose a block.
At the end of this lesson, you should be able to
D Declare and use variables and constants in PL/SQL
D Assign new values to variables within the executable section
D Create and execute a named PL/SQL subprogram in Procedure Builder
Trang 4Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć4
Trang 5A PL/SQL block is comprised of up to three sections: declarative (optional),
executable (required), and exception handling (optional) Only BEGIN and ENDkeywords are required Each subprogram contains an additional section, the header(required)
You can store and change values within a PL/SQL block by declaring and referencingvariables and other identifiers
Handling Variables
D Declare and initialize variables within the declaration section
D Assign new values to variables within the executable section
D Pass values into PL/SQL blocks through parameters
D View the results from a PL/SQL block through output variables
Note: The END keyword can be optionally followed by the name of the subprogram
for clarity
Class Management Note:
PowerPoint: The bottom slide contains the build feature
Trang 6Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć6
Trang 7Declaring PL/SQL Variables and Constants
You need to declare all identifiers within the declaration section before referencing
them within the PL/SQL block
Syntax
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];
where: identifier is the name of the identifier
CONSTANT constrains the identifier so that its value cannot
change; constants must be initialized
datatype is a scalar or composite datatype
NOT NULL constrains the variable so that it must contain a
value; NOT NULL variables must be initialized
expr is any PL/SQL expression that can be a literal,
another variable, or an expression involvingoperators and functions
Guidelines
D Name the identifier according to the same rules used for SQL objects
D You can use naming conventions, for example v_name to represent a variable, and
c_name to represent a constant.
D You have the option of assigning an initial value to variables, unless they areNOT NULL
D Initialize the variable to an expression with the assignment operator (:=), or,equivalently, with the DEFAULT reserved word; otherwise, variables are
initialized to NULL by default.
D Declare at most one identifier per line
For more information, see
PL/SQL User’s Guide and Reference, Release 2.3, “Datatypes.”
Technical Note:
Trang 8Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć8
Class Management Note:
Mention that the NUMBER, CHAR, and VARCHAR2 datatypes havesubtypes Additional base types are RAW, ROWID, and MLSLABEL(Trusted Oracle)
Trang 9Declaring Scalar Variables
PL/SQL supports three datatypes—scalar, composite, and reference—that you canuse for declaring variables, constants, and pointers
Scalar Datatypes
A scalar datatype holds a single value and has no internal components Scalar
datatypes can be classified into four categories: number, character, date and time, orBoolean Character and number datatypes have subtypes that associate a base type to
a constraint For example, INTEGER and POSITIVE are subtypes of the NUMBERbase type
BINARY_INTEGER Base type for integers between –2147483647
and 2147483647
NUMBER [(precision,scale)] Base type for fixed and floating point numbers
CHAR [(maximum_length)] Base type for fixed length character data up to
32767 bytes If you do not specify a
maximum_length, the default length is set to 1.
LONG Base type for variable length character data up
to 32760 bytes
LONG RAW Base type for binary data up to 32760 bytes
VARCHAR2(maximum_length) Base type for variable length character data up
to 32767 bytes
DATE Base type for dates and times
BOOLEAN Base type that stores one of three possible
values used for logical calculations: TRUE,FALSE, or NULL
Note: The above list is abridged For the complete list, see the PL/SQL User’s Guide
and Reference, Release 2.3, “Datatypes.”
Trang 10Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć10
Class Management Note:
Trang 11Declaring Scalar Variables continued
Declare a constant for the tax rate, which never changes throughout the PL/SQLblock
Declare a flag to indicate whether a piece of data is valid or invalid, and initialize thevariable to TRUE
Trang 12Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć12
Trang 13Declaring Scalar Variables continued
The %TYPE Attribute
When you declare PL/SQL variables to hold column values, you must ensure that thevariable is of the correct datatype and precision If it is not, then a PL/SQL error willoccur during execution
Rather than hard-coding the datatype and precision of a variable, you can declare avariable according to another previously-declared variable or database column You
do this using the %TYPE attribute To use the attribute in place of the datatype
required in the variable declaration, prefix it with the database table and columnnames If referring to a previously-declared variable, prefix the variable name to theattribute
PL/SQL determines the datatype and size of the variable when the block is compiled,
so the variable is always compatible with the database column or identifier used topopulate the variable
Advantages of Using the %TYPE Attribute
D The datatype of the underlying database column may be unknown
D The datatype of the underlying database column may change at runtime
Trang 14Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć14
Trang 15Declaring Composite Datatypes
A composite datatype contains internal components and is reusable Two types of
composite datatypes are available in PL/SQL: TABLE and RECORD
PL/SQL Table
D A PL/SQL TABLE datatype is not the same as a database table
D A PL/SQL TABLE is similar to a one-dimensional array
D A PL/SQL TABLE must contain two components:
D A primary key of datatype BINARY_INTEGER that indexes the PL/SQLTABLE
D A column of a scalar datatype, which stores the PL/SQL TABLE elements
D A PL/SQL TABLE can increase dynamically because it is unconstrained
Trang 16Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć16
Trang 17Declaring Composite Datatypes continued
Declaring PL/SQL Tables
1. Declare a TABLE datatype
2. Declare a variable of that datatype
Syntax
TYPE type_name IS TABLE OF scalar_datatype [NOT NULL]
INDEX BY BINARY_INTEGER;
where: type_name is the name of the TABLE type
scalar_datatype is the datatype of the PL/SQL TABLE elements
You can use the %TYPE attribute
identifier is the name of the identifier
The NOT NULL constraint prevents nulls from being assigned to the PL/SQL
TABLE of that type Do not initialize the PL/SQL TABLE
Class Management Note:
PowerPoint: The top slide uses the build feature
Trang 18Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć18
Trang 19Declaring Composite Datatypes continued
PL/SQL RECORD
D A PL/SQL RECORD datatype is not the same as a row in a database table
D A PL/SQL RECORD is similar in structure to a record in a 3GL
D A PL/SQL RECORD must contain one or more components of any scalar,
RECORD, or PL/SQL TABLE datatype called fields These uniquely namedfields can have different datatypes
D The PL/SQL RECORD allows you to treat this collection of fields as one logicalunit
D PL/SQL RECORDS are convenient for fetching a row of data from a table forprocessing in a PL/SQL block
Trang 20Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć20
Trang 21Declaring Composite Datatypes continued
Declaring PL/SQL Records
1. Declare a RECORD datatype
2. Declare a variable of that datatype
where: type_name is the name of the RECORD type
field_name is the name of the field
field_type is the datatype of the field You can use the
%TYPE and %ROWTYPE attribute
expr is any PL/SQL expression that can be a literal,
another variable, or an expression involvingoperators and functions
identifier is the name of the identifier
Trang 22Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć22
Trang 23Declaring Composite Datatypes continued
Declaring Records withthe %ROWTYPE Attribute
Declare a record based upon a collection of columns in a database table or view byusing the %ROWTYPE attribute The fields within the record take their names anddatatypes from the columns of the table or view
Advantages of Using the %ROWTYPE Attribute
D The number and datatypes of the underlying database columns may be unknown
D The number and datatypes of the underlying database columns may change atruntime
D Useful when retrieving a row with the SELECT statement
Class Management Note:
Draw on the board the structure of DEPT_RECORD
Trang 24Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć24
Trang 25PL/SQL Block Syntax Rules
Because PL/SQL is an extension of SQL, the general syntax rules that apply to SQLare also applicable to the PL/SQL language
D Statements can be split across lines, but keywords must not be split
D Lexical units (for example, identifiers or literals) can be separated by one or morespaces or other delimiters that cannot be confused as being part of the lexical unit
D Character and date literals must be enclosed within single quotation marks
D Numeric literals can be represented by either a simple value (for example, –32.5)
or by scientific notation (for example, 2E5, meaning 2x10 to the power of 5 =200000)
D Multiple line comments can be enclosed by /* and */ symbols A single linecomment begins with , and the end-of-line marks the comment’s end
For more information, see
PL/SQL User’s Guide and Reference, Release 2.3, “Appendix E” for a list of reserved
words
Trang 26Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć26
Trang 27PL/SQL Block Syntax Rules continued
Nested Blocks
One of the advantages PL/SQL has over SQL is the ability to nest statements Youcan nest blocks wherever an executable statement is allowed, thus making the nestedblock a statement Therefore, you can break down the executable part of a block intosmaller blocks The exception section can also contain nested blocks
Variable Scope
The scope of an object is the region of the program that can refer to the object You
can reference the declared variable within the executable section
An identifier is visible in the block in which it is declared and all nested sub-blocks,procedures, and functions If the block does not find the identifier declared locally, it
looks up to the declarative section of the enclosing (or parent) blocks The block never looks down to enclosed (or child) blocks or sideways to sibling blocks.
Scope applies to all declared objects, including variables, cursors, user-defined
exceptions, and constants
Class Management Note:
Qualify an identifier by using the block label prefix This topic is covered inthe lesson “Controlling Flow in PL/SQL Blocks.”
Trang 28Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć28
Trang 29Assigning Values to Variables
To assign or reassign a value to a variable, you write a PL/SQL assignment statement.You must explicitly name the variable to receive the new value to the left of theassignment operator (:=)
Syntax
identifier := expr;
plsql_table_name(primary_key_value) := expr;
plsql_record_name.field_name := expr;
where: identifier is the name of the identifier
plsql_table_name is the name of the PL/SQL TABLE
primary_key_value is the binary integer value that is the index of
the PL/SQL TABLE and could also be avariable
plsql_record_name is the name of the PL/SQL RECORD
field_name is the field from the PL/SQL RECORD
expr can be a variable, constant, literal, or function
call, but not a database column.
Trang 30Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć30
Trang 31Assigning Values to Variables continued
To assign a value into a variable from the database, use a SELECT or
FETCH statement These topics are covered in later lessons
Trang 32Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć32
Class Management Note:
This is an example of an anonymous block of code
Trang 33Assigning Values to Variables continued
Class Exercise
Evaluate the PL/SQL block on the opposite page Determine each of the followingvalues according to the rules of scoping
1. The value of V_WEIGHT within the sub-block
2. The value of V_NEW_LOCN within the sub-block
3. The value of V_WEIGHT within the main block
4. The value of V_MESSAGE within the main block
5. The value of V_NEW_LOCN within the main block
Class Management Note:
Answers:
1 V_WEIGHT = 2 (a number datatype)
2 V_NEW_LOCN = ‘Western Europe’ (a character string)
3 V_WEIGHT = 601 (a number datatype)
4 V_MESSAGE = ‘Product 10012 is in stock’ (a character string)
5 V_NEW_LOCN is illegal since it is not visible outside the sub-block
Trang 34Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć34
Trang 35Assigning Values to Variables continued
Validate an employee number if it contains a value
Class Management Note:
Note for page 21-36
Additionally, PL/SQL provides two further functions for error reportingcalled SQLCODE and SQLERRM, which will be covered in later lesson
Trang 36Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć36
Trang 37Assigning Values to Variables continued
Functions
Most of the functions available in SQL are also valid in PL/SQL expressions:
D Single-row number functions
D Single-row character functions
D Datatype conversion functions
D Date functions
D Miscellaneous functions
Functions not available in procedural statements:
D GREATEST and LEAST
D Group functions: AVG, MIN, MAX, COUNT, SUM, STDDEV, and VARIANCEGroup functions apply to groups of rows in a table, and are therefore available onlywithin SQL statements in a PL/SQL block
Examples
Build the mailing address for a company
CHR(10)||v_country||CHR(10)||v_zip_code;
Convert the name to uppercase
Compute the sum of all numbers stored in the NUMBER_TABLE PL/SQL table
This example produces a compile error.
Trang 38Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć38
Trang 39Assigning Values to Variables continued
Datatype Conversion
Within an expression, you should make sure that datatypes are the same If mixeddatatypes occur in the same expression, you should use the appropriate conversionfunction from the list below to convert the data
Syntax
TO_CHAR (value, fm)
TO_DATE (value, fm)
TO_NUMBER (value, fm)
where: value is a character string, number, or date
fm is the format model used to convert value.
Examples
Store a value that is composed of the user name and today’s date This code causes a
syntax error.
To correct the error, convert SYSDATE to a character string with the TO_CHARconversion function
Trang 40Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 21Ć40
Trang 41Assigning Values to Variables continued
Referencing NonĆPL/SQL Variables
You can reference variables declared in the host or calling environment in PL/SQLstatements, unless the statement is within a procedure, function, or package Thisincludes host language variables declared in precompiler programs, screen fields in aDeveloper/2000 Forms application, and SQL*Plus bind variables
To reference host variables, you must prefix the references with a colon (:) to
distinguish them from declared PL/SQL variables
Example
Store the annual salary in a SQL*Plus global variable