Vous êtes sur la page 1sur 86

HTTP 5105 Database Design and

Development
Lecture 6 How to Write PL/SQL Code

HTTP 504 Database Design and Development 1 November 2, 2014


Objectives

Write anonymous PL/SQL code


Including:
Show output
Declare and use variables
Code IF statements
Code CASE statements
Code loops
How to use a cursor

HTTP 504 Database Design and Development 2 November 2, 2014


Syntax of an Anonymous PL/SQL Block

DECLARE
declaration_statement_1;
[declaration_statement_2;]...
BEGIN
body_statement_1;
[body_statement_2;]...
EXCEPTION
WHEN OTHERS THEN
exception_handling_statement_1;
[exception_handling_statement_2;]...
END;
/

HTTP 504 Database Design and Development 3 November 2, 2014


PL/SQL Variables and Data Types

Like SQL, PL/SQL variables must begin with a letter and cannot
contain more than 30 characters
Variables can contain letters, numbers, and the symbols _, $, and
#
Hyphens and blanks are not permitted
You may use no reserve words and they cannot be the same as
any table name
Should be descriptive as possible
Usually are expressed in a combination of upper and lowercase
letters
HTTP 504 Database Design and Development 4 November 2, 2014
PL/SQL Variables and Data Types

Item Type Capitalization Example

Reserved Words Uppercase BEGIN, DECLARE

Built-in Functions Uppercase COUNT, TO_DATE

Predefined Data Uppercase VARCHAR2, NUMBER


Types
SQL Commands Uppercase SELECT, INSERT

Database Objects Lowercase student, fid

Variable Names Mixed Case StudentFName

November 2, 2014 HTTP 504 Database Design and Development 5


PL/SQL Data Types VARCHAR2

Holds variable-length string data


PL/SQL VARCHAR2 data type holds up to 32,767
characters, different from the database counterpart
that only holds 4,000 characters
When declared must also specify the maximum field
width
StudentName VARCHAR2(30);

HTTP 504 Database Design and Development 6 November 2, 2014


PL/SQL Data Types - CHAR

The CHAR data type holds fixed-length character


strings
PL/SQL CHAR data type holds up to 32,767 characters
When you declare a CHAR if you do not specify a size
it will default to a size of 1
If the entire field is not filled by characters the rest is
padded with spaces
StudentGender CHAR(1) or StudentGender CHAR;

HTTP 504 Database Design and Development 7 November 2, 2014


PL/SQL Data Types - NUMBER

The NUMBER data type is identical to Oracle database


NUMBER type
The general format NUMBER (<precision>, <scale>);
Precision is the total length of the number including the
decimal places and scale specifies the number of decimal
places
Specify only precision for integers, and for floating-point
specify both precision and scale
CurrentPrice NUMBER(5,2);
HTTP 504 Database Design and Development 8 November 2, 2014
PL/SQL Data Types BINARY INTEGER

BINARY_INTEGER data type can also be used to


represent integer values
Data are stored in binary format which takes slightly
less storage space compared to NUMBER
Calculations can be performed on BINARY_INTEGER
quicker than on NUMBER data type
CustID BINARY_INTEGER

HTTP 504 Database Design and Development 9 November 2, 2014


PL/SQL Data Types - DATE

The DATE data type is the same as the Oracle


database counterpart
Stores both date and time values
TodaysDate DATE;

HTTP 504 Database Design and Development 10 November 2, 2014


PL/SQL Data Types - BOOLEAN

The BOOLEAN data type is used to store True/False


values and is usually used as a flag
When a BOOLEAN data type is declared it has a value
of NULL until it is assigned a value of TRUE or FALSE
OrderFlag BOOLEAN;

HTTP 504 Database Design and Development 11 November 2, 2014


PL/SQL Data Types - %TYPE

The PL/SQL data type %TYPE is a reference data type


It is used to give a variable the same data type as a
column from the database
<variable name> <table name>.<field name>%TYPE
LNAME FACULTY.FLNAME%TYPE
This would create a variable with the same data type as
the column from the table FACULTY, which could be a
VARCHAR2(30)
CustAddress customer.cadd%TYPE
HTTP 504 Database Design and Development 12 November 2, 2014
PL/SQL Data Types - %ROWTYPE

This data type is useful when you want to declare a


variable to hold an entire row of data
<row variable name> <table name>%ROWTYPE
FacRow faculty%ROWType
This variable would consist of all eight fields from the
FACULTY table, and each would have the same data
type as the associated database field

HTTP 504 Database Design and Development 13 November 2, 2014


PL/SQL Program Blocks

This is the structure for a PL/SQL program, there are various areas in an Anonymous
PL/SQL Program or Block
Notice the / on line 9 needed to execute code

HTTP 504 Database Design and Development 14 November 2, 2014


PL/SQL Program Blocks

PL/SQL is a strongly typed language, this means that


all variables must be declared before they are used
Also means that PL/SQL program variables
assignments and comparisons can only be done
between variables of the same data type
Declared in the programs DECLARE section or block,
the format is:
<variable name <data type>;
StudentID NUMBER;
HTTP 504 Database Design and Development 15 November 2, 2014
PL/SQL Program Blocks - Comments

A block of comments is
done by using a /* at the
beginning of the block and
a */ at the end of the block

Two hyphens (--) are used


to declare a comment at
the beginning of a line
HTTP 504 Database Design and Development 16 November 2, 2014
PL/SQL Program Blocks - Body

The body of a PL/SQL program consists of program


statements, these can be:
Assignments
Conditional statements
Looping statements
Etc.
These lie between the BEGIN and EXCEPTION
statements
Each PL/SQL statement must end in a semicolon
HTTP 504 Database Design and Development 17 November 2, 2014
PL/SQL Arithmetic Statements

Operator Meaning Example Result

** Exponentiation 2**3 8

* Multiplication 2*3 6

/ Division 9/2 4.5

+ Addition 3+2 5

- Subtraction 32 1

- Negation -5 Negative 5

HTTP 504 Database Design and Development


18 November 2, 2014
PL/SQL Assignment Operator

An assignment statement assigns a value to a variable


The assignment operator is:
:=
The variable that is being assigned is placed on the
left of the assignment operator, and the new value is
placed on the right of the assignment operator
SName := John;
SName := CurrentStudentName;

HTTP 504 Database Design and Development 19 November 2, 2014


PL/SQL Interactive Output

In the SQL Developer environment you can use the


DBMS_OUTPUT.PUT_LINE function to display output
within a PL/SQL program
When you start a new SQL*Plus session you must first
issue the command SET SERVEROUTPUT ON, this sets
up an internal buffer to store values for input and
output
Without this set nothing is displayed
Good for a maximum length of 255 characters
HTTP 504 Database Design and Development 20 November 2, 2014
A Script with an Anonymous PL/SQL
Block

HTTP 504 Database Design and Development 21 November 2, 2014


Description

A script is a series of SQL statements that you can store


in a file
PL/SQL (Procedural Language / SQL) is Oracles
extension to standard SQL that allows you to write
procedural code such as IF statements and loops
An anonymous PL/SQL block is a block of PL/SQL that is
coded within a script
To execute a PL/SQL block you must code a front slash (/)
after the END keyword on its own line by itself
HTTP 504 Database Design and Development 22 November 2, 2014
PL/SQL Statements for Controlling the
Flow

IF...ELSIF...ELSE
CASE...WHEN...ELSE
FOR...IN...LOOP
WHILE...LOOP
LOOP...EXIT WHEN
CURSOR...IS
EXECUTE IMMEDIATE

HTTP 504 Database Design and Development 23 November 2, 2014


Commands for Working With Scripts

CONNECT
SET SERVEROUTPUT ON

HTTP 504 Database Design and Development 24 November 2, 2014


Procedures for Printing Output to the
Screen

DBMS_OUTPUT.PUT(string)
Prints the specified string without a line break
DBMS_OUTPUT.PUT_LINE(string)
Prints the specified string followed by a line break

HTTP 504 Database Design and Development 25 November 2, 2014


How to Print Data to an Output
Window
Click the Run
Script button
You are
working with
a script not a
single
statement

HTTP 504 Database Design and Development 26 November 2, 2014


The Syntax for Declaring a Variable

variable_name_1 DATA TYPE;


VariableName1Var DATA TYPE;

Sometime to use the VAR suffix to inform that it is a


variable value
Either of the above works it is nice to differentiate the
difference between variable and database values

HTTP 504 Database Design and Development 27 November 2, 2014


Syntax for Declaring a Variable with the
Same Data Type as a Column

variable_name_1 table_name.column_name%TYPE

max_invoice_total invoices.invoice_total%TYPE

Sets the variable max_invoice_total to be the same data


type as the invoice_total column in the invoices table
This way to will always take on the settings of the
corresponding table and column of the table in the event
they are ever changed, code does not have to be modified
HTTP 504 Database Design and Development 28 November 2, 2014
Syntax for Setting a Variable to a
Selected Value

SELECT column_1 [, column_2]


INTO variable_1 [, variable_2] Database column names

DECLARE
max_invoice_total invoices.invoice_total%TYPE;
min_invoice_total invoices.invoice_total%TYPE;
percent_difference NUMBER;
count_invoice_id NUMBER;
vendor_id_var NUMBER := 95;

BEGIN
SELECT MAX(invoice_total), MIN(invoice_total), COUNT(invoice_id)
INTO max_invoice_total, min_invoice_total, count_invoice_id)
Variable names that were declared
HTTP 504 Database Design and Development 29 November 2, 2014
Syntax fro Setting a Variable to a Literal
Value or an Expression

variable_name := literal_value_or_expression

vendor_id_var NUMBER := 95;

Assigns the value of 95 to the variable vendor_id_var

HTTP 504 Database Design and Development 30 November 2, 2014


Script That Uses Variables
This is an anonymous
PL/QL program that uses
the various constructs we
just defined

HTTP 504 Database Design and Development 31 November 2, 2014


How to Code IF Statements

An IF statement is a statement is used to execute one


or more statements that based on a value thats
returned by a Boolean expression
A Boolean expression is an expression that returns a
true value or a false value
In the IF statement a test is used to test the value of a
variable to determine whether it is true or false

HTTP 504 Database Design and Development 32 November 2, 2014


Syntax of an IF Statement

IF boolean_expression THEN
statement_1;
[statement_2;]...
[ELSIF boolean_expression THEN
statement_1;
[statement_2;]...]...
[ELSE
statement_1;
[statement_2;]...]
END IF;

HTTP 504 Database Design and Development 33 November 2, 2014


Script That Uses an IF Statement

HTTP 504 Database Design and Development 34 November 2, 2014


PL/SQL IF/THEN ELSE Structure

HTTP 504 Database Design and Development 35 November 2, 2014


PL/SQL IF/THEN ELSE Structure

HTTP 504 Database Design and Development 36 November 2, 2014


Nesting IF/THEN ELSE Statements

HTTP 504 Database Design and Development 37 November 2, 2014


The IF/THEN ELSIF Structure

HTTP 504 Database Design and Development 38 November 2, 2014


The CASE Statement

You can use a simple CASE statement or a searched


CASE statement to execute one or more statements
depending on the value that is returned by an
expression

HTTP 504 Database Design and Development 39 November 2, 2014


Syntax of a CASE Statement

CASE expression
WHEN expression_value_1 THEN
statement_1;
[statement_2;]...
[WHEN expression_value_2 THEN
statement_1;
[statement_2;]...]...
[ELSE
statement_1;
[statement_2;]...]
END CASE;

HTTP 504 Database Design and Development 40 November 2, 2014


Script That Uses a Simple CASE
Statement

HTTP 504 Database Design and Development 41 November 2, 2014


The Syntax of the Searched CASE
Statement

CASE
WHEN boolean_expression THEN
statement_1;
[statement_2;]...
[WHEN boolean_expression THEN
statement_1;
[statement_2;]...]...
[ELSE
statement_1;
[statement_2;]...]
END CASE;

HTTP 504 Database Design and Development 42 November 2, 2014


LOOP Structures

Five different types of loops in PL/SQL


LOOP EXIT
LOOP EXIT WHEN
WHILE LOOP
Numeric FOR Loops
Cursor FOR Loops (look at later in chapter)

HTTP 504 Database Design and Development 43 November 2, 2014


The LOOP EXIT Loop

The basic format of the command:


LOOP
<program statements for posttest loop>
IF <condition> THEN
EXIT;
END IF;
<program statements for pretest loop>
END LOOP;
Loop can either be a pretest or a posttest loop where the condition
is tested either before or after the program statements are executed

HTTP 504 Database Design and Development 44 November 2, 2014


The LOOP EXIT Loop

If the program statements might never be executed


use the pretest loop
If the program statements are always executed at
least once use the posttest loop

HTTP 504 Database Design and Development 45 November 2, 2014


Table to Test LOOP Statements

The following table is created to test the various loop structures

HTTP 504 Database Design and Development 46 November 2, 2014


The LOOP EXIT Loop

HTTP 504 Database Design and Development 47 November 2, 2014


The LOOP EXIT WHEN Loop

The basic format of the command:


LOOP
<program statements>
EXIT WHEN <condition>;
END LOOP;
This loop executes the program statements then tests for
the condition
This is a posttest loop the program statements are always
executed at least once
HTTP 504 Database Design and Development 48 November 2, 2014
The LOOP EXIT WHEN Loop
The test with the EXIT WHEN is done after
the INSERT has already taken place
This is a post test loop, since the INSERT is
done at least once prior to the test to see
if you were finished is accomplished

HTTP 504 Database Design and Development 49 November 2, 2014


The WHILE LOOP Loop

The basic format of the command:


WHILE <condition>
LOOP
<program statements>
END LOOP;
This a pretest loop, the condition is evaluated before
any program statements are executed

HTTP 504 Database Design and Development 50 November 2, 2014


The WHILE LOOP Loop
This is a pretest loop
The condition is check before any SQL
statements are executed
If the condition was met initially the INSERT
would never take place since it is done after
the test is done

HTTP 504 Database Design and Development 51 November 2, 2014


The Numeric FOR LOOP

The basic format for the command is:


FOR <counter variable> IN <start value> .. <end value>
LOOP
<program statements>
END LOOP;
Start and End values must be integers
Do not have to declare a counter and increment manually
Counter is defined in a series of numbers and automatically
incremented
HTTP 504 Database Design and Development 52 November 2, 2014
The Numeric FOR LOOP
Notice no counter is declared for this
loop type
Do not have to increment the counter to
the next value

HTTP 504 Database Design and Development 53 November 2, 2014


Syntax for a WHILE LOOP

WHILE boolean_expression LOOP


statement_1;
[statement_2;]...
END LOOP;
A WHILE loop
i := 1;
WHILE i < 4 LOOP
DBMS_OUTPUT.PUT_LINE('i: ' || i);
i := i + 1;
END LOOP;

HTTP 504 Database Design and Development 54 November 2, 2014


The Syntax for the FOR Loop

FOR counter_var IN [REVERSE]


counter_start..counter_end LOOP
statement_1;
[statement_2;]...
END LOOP
A FOR loop
FOR i IN 1..3 LOOP
DBMS_OUTPUT.PUT_LINE('i: ' || i);
END LOOP;

HTTP 504 Database Design and Development 55 November 2, 2014


How to Use a Cursor

By default SQL statements work with an entire result


set rather than individual rows
However there are times when you need to be able ot
work with the data in a result set one row at a time
To do that you can use a CURSOR
The DECLARE section of the script begins by declaring
a CURSOR
It will contain columns from table(s)

HTTP 504 Database Design and Development 56 November 2, 2014


The Syntax for Declaring a CURSOR

CURSOR cursor_name IS select_statement;


The DECLARE section of the script begins by declaring a
CURSOR named INVOICES_CURSOR that contains two
columns from the invoices table and all the rows that
have a balance due
The script then declares a variable named INVOICE_ROW
This declaration uses the %ROWTYPE attribute to
indicate that the invoice_row can store the same data
types as a row in the invoices table
HTTP 504 Database Design and Development 57 November 2, 2014
A Script Using a CURSOR

HTTP 504 Database Design and Development 58 November 2, 2014


Syntax for Declaring a Variable for a
Row

row_variable_name table_name%ROWTYPE;

HTTP 504 Database Design and Development 59 November 2, 2014


Syntax for Getting a Column Value from
a Row Variable

row_variable_name.column_name

HTTP 504 Database Design and Development 60 November 2, 2014


CURSORS

When Oracle processes a SQL command it allocates a


memory location in the database servers memory
know as the context area
This memory location contains information about the
command, such as the number of rows processed by
the statement, a parsed representation of the
statement
In the case of a query that returns data, the active set
is the set of data rows returned by the query
HTTP 504 Database Design and Development 61 November 2, 2014
CURSORS

A cursor is a pointer, which is a variable that contains


the address of the memory location that contains the
SQL commands context area
There are two kinds of cursors, implicit and explicit
The implicit cursor is created automatically within the
Oracle environment, and does not need to be declared
in the DECLARE section
Oracle creates an implicit cursor every time you issue an
INSERT, UPDATE or a DELETE command
HTTP 504 Database Design and Development 62 November 2, 2014
CURSORS

You can use an implicit cursor when you want to


assign the output of a SELECT query to a PL/SQL
variable
You must be sure that the query will return one and
only one record
If more than one or no records are returned an error
message is generated

HTTP 504 Database Design and Development 63 November 2, 2014


CURSORS

The implicit cursor has the following format:


SELECT <data field(s)>
INTO <declared variable name(s)>
FROM <table name(s)>
WHERE <search condition that will return a single
record>;
The receiving variables in the INTO section must be of
the same data types as the returned fields

HTTP 504 Database Design and Development 64 November 2, 2014


CURSORS

HTTP 504 Database Design and Development 65 November 2, 2014


Implicit CURSORS

HTTP 504 Database Design and Development 66 November 2, 2014


Implicit CURSORS
The WHERE clause was removed so
the query now retrieved more than
the one row
An implicit cursor is only capable of
returning a single row, otherwise you
receive an error as show

HTTP 504 Database Design and Development 67 November 2, 2014


Implicit CURSOR
An implicit CURSOR must return a single row
If no row is returned an error message is given
This is shown here

HTTP 504 Database Design and Development 68 November 2, 2014


Explicit CURSORS

Explicit Cursors must be used with SELECT statements that


might retrieve a variable number of records or no records
Declared in the DECLARE section and processed in the
program body
The steps are as follows:
Declare the cursor
Open the cursor
Fetch the cursor results into PL/SQL variables
Close the cursor
HTTP 504 Database Design and Development 69 November 2, 2014
Declaring an Explicit CURSOR

Declaring the explicit cursor names the cursor and


defines the query associated with the cursor
The general format is:
CURSOR <cursor name> IS <SELECT statement>;
The cursor name can be any valid PL/SQL variable name
The SELECT statement is any legal SQL SELECT
statement with the exception of UNION or MINUS
which cannot be used

HTTP 504 Database Design and Development 70 November 2, 2014


Declaring an Explicit CURSOR

Example of a declaration for a cursor:


DECLARE
CurrentBldgCode VARCHAR2(5);
CURSOR LocationCursor IS
SELECT locid, room, capacity
FROM location
WHERE bldg_code = CurrentBldgCode;
You declare a variable then the cursor

HTTP 504 Database Design and Development 71 November 2, 2014


Opening an Explicit CURSOR

Opening the cursor allows the SQL compiler to parse the


SQL query
At this point the individual components are checked for
syntax errors
The parsed query is then stored in the context area and the
active set is defined
The general format to open an explicit cursor is:
OPEN <cursor name>;
OPEN LocationCursor;
HTTP 504 Database Design and Development 72 November 2, 2014
Fetching Data Into an Explicit CURSOR

The FETCH command retrieves the query data from the


database into the active set one row at a time
Since the query can return many rows the FETCH is usually
placed into a loop
The general format is as follows:
FETCH <cursor name> INTO <record variable(s)>;
The record variable is either a single variable or a list of
variables that will receive data
Usually this variable is declared using one of the reference
types that are declared using either %TYPE or %ROWTYPE
HTTP 504 Database Design and Development 73 November 2, 2014
Fetching Data Into an Explicit CURSOR

Example one
DECLARE
CURSOR LocationCursor IS
SELECT capacity
FROM location;
RoomCapacity location.capacity%TYPE;
BEGIN
OPEN LocationCursor;
FETCH LocationCursor INTO RoomCapacity;
<additional processing statements>
END

HTTP 504 Database Design and Development 74 November 2, 2014


Fetching Data Into an Explicit CURSOR

Example two
DECLARE
CURSOR LocationCursor IS
SELECT bldg_code, room, capacity
FROM location;
LocationRow LocationCursor%ROWTYPE;
BEGIN
OPEN LocationCursor;
FETCH LocationCursor INTO LocationRow;
<additional processing statements>
END;

HTTP 504 Database Design and Development 75 November 2, 2014


Fetching Data Into an Explicit CURSOR

Recall that the %TYPE data type assumes the same data
type as a specific database table field and is declared using
the format:
<tablename>.<fieldname>%TYPE
If a cursor returns multiple fields the output is fetched
into a variable declared using the %ROWTYPE data type
The %ROWTYPE can also assume the same data types as
the data fields that a cursor returns when it is declared
using the format
<row variable name> <cursor name>%ROWTYPE
HTTP 504 Database Design and Development 76 November 2, 2014
Fetching Data Into an Explicit CURSOR

The individual fields ion a row variable can be


referenced using the format:
<row variable name>.<database field name>
For example to access the database field value
returned for bldg_code variable in the cursor you
would use the following:
LocationRow.bldg_code

HTTP 504 Database Design and Development 77 November 2, 2014


Closing a CURSOR

A cursor should be closed after processing is completed


This frees up memory area and resources so these can
be made available to the system for other tasks
The general format for the CLOSE command is:
CLOSE <cursor name>
In the event you forget to close the cursor it will
automatically close when the program where the cursor
is declared ends

HTTP 504 Database Design and Development 78 November 2, 2014


Processing an Explicit CURSOR

Explicit cursors can be processed using a loop that terminates when all rows
have been processed
Two different structures can be used the LOOP EXIT WHEN and the FOR
loop
Format for the LOOP EXIT WHEN
BEGIN
OPEN <cursor name>
LOOP
FETCH <cursor name> INTO <variables>;
<additional statements
END LOOP;
CLOSE <cursor name>;
END;

HTTP 504 Database Design and Development 79 November 2, 2014


Explicit CURSOR Using a LOOP EXIT
WHEN
Putting all this
together

HTTP 504 Database Design and Development 80 November 2, 2014


Explicit CURSOR Using the CURSOR
FOR LOOP

The cursor FOR loop provides an easier method to process explicit


cursors
You do not need to explicitly OPEN, FETCH the rows or CLOSE the
cursor
General format for the cursor FOR loop is:
BEGIN
FOR <cursor variables> IN <cursor name> LOOP
<additional statements>
END LOOP;
END;
HTTP 504 Database Design and Development 81 November 2, 2014
Explicit CURSOR Using the CURSOR
FOR LOOP

HTTP 504 Database Design and Development 82 November 2, 2014


Other Explicit CURSOR Attributes

Explicit cursors have attributes that describe the


cursors state
Is the cursor open?
Were records found or not?
How many records were fetched?

HTTP 504 Database Design and Development 83 November 2, 2014


Other Explicit CURSOR Attributes

Attribute Description

%NOTFOUND Evaluates as true when the cursor has no rows


left to fetch, false when there are rows

%FOUND True when the cursor has rows to fetch and


false when the cursor has no rows to fetch

%ROWCOUNT Returns the number of rows the cursor has


fetched so far

%ISOPEN Returns true if the cursor is open and false if the


cursor is closed

October 28, 2013 HTTP 504 Database Design and Development 84


Other Explicit CURSOR Attributes

November 2, 2014 HTTP 504 Database Design and Development 85


Other Explicit CURSOR Attributes

November 2, 2014 HTTP 504 Database Design and Development 86

Vous aimerez peut-être aussi