You are on page 1of 67

PL/SQL and

Chapter 10
Selected Single-Row Functions
Jason C. H. Chen, Ph.D.
Professor of MIS
School of Business
Gonzaga University
Spokane, WA 99258 USA
chen@jepson.gonzaga.edu
Dr. Chen, Oracle Database System (Oracle)

Objectives
Use the UPPER, LOWER, and INITCAP functions to change the case
of field values and character strings
Manipulate character substrings with the SUBSTR and INSTR
functions
Nest functions inside other functions
Determine the length of a character string using the LENGTH function
Use the LPAD and RPAD functions to pad a string to a certain width
Use the LTRIM and RTRIM functions to remove specific characters
strings
Substitute character string values with the REPLACE and
TRANSLATE functions
Round and truncate numeric data using the ROUND and TRUNC
functions
Return the remainder only of a division operation using the MOD function
Use the ABS function to set numeric values as positive
Dr. Chen, Oracle Database System (Oracle)

Objectives (continued)
Use the POWER function to raise a number to a specified power
Calculate the number of months between two dates using the
MONTHS_BETWEEN function
Manipulate date data using the ADD_MONTHS, NEXT_DAY,
LAST_DAY, and TO_DATE functions
Differentiate between CURRENT_DATE and SYSDATE values
Extend pattern matching capabilities with regular expressions
Identify and correct problems associated with calculations involving
NULL values using the NVL function
Display dates and numbers in a specific format with the TO_CHAR
function
Perform condition processing similar to an IF statement with the
DECODE function
Use the SOUNDEX function to identify character phonetics
Convert string values to numeric with the TO_NUMBER function
Use the DUAL table to test functions
Learn PL/SQL Procedure Language / SQL
Dr. Chen, Oracle Database System (Oracle)

Functions Must Study and Understand


The following functions are the minimum to study and
understand:
1. Case conversion functions
2. character manipulation functions
SUBSTR, INSTR, LENGTH, LTRIM, RTRIM,
REPLACE, CONCAT
3. ALL Number functions
4. DATE functions
MONTH_BETWEEN, ADD_MONTHS, TO_DATE, SYSDATE

5. Other functions
NVL, TO_CHAR, CASE, TO_NUMBER, DUAL table

Dr. Chen, Oracle Database System (Oracle)

Refresh the Database


1. Go to Blackboard and download (at least
three) data files from Oracle chapter10 and
save under c:\oradata\chapter10\
Please note that there is a PL/SQL data file of
Ch10 Queries for PL SQL.sql

2. Run the following script file


Start c:\oradata\chapter10\JLDB_Build_10.sql

Dr. Chen, Oracle Database System (Oracle)

Manipulating Character
Strings with PL/SQL
To change case, use UPPER, LOWER, INITCAP
INSTR function searches a string for a specific
substring and return the starting position
start_position := INSTR(original_string, substring,
starting_pos, occurrence#);
/* the first two arguments are required, the last two
arguments are optional */
SUBSTR function extracts a specific number of
characters from a character string, starting at a given
point:
extracted_string := SUBSTR(string_variable,
starting_point, number_of_characters);

Dr. Chen, Oracle Database System (Oracle)

Case Conversion Functions


Case conversion functions alter the case of
data stored in a column or character string
Used in a SELECT clause, they alter the
appearance of the data in the results
Used in a WHERE clause, they alter the value
for comparison

Dr. Chen, Oracle Database System (Oracle)

LOWER Function
Used to convert characters to lowercase letters

Figure 10-1 LOWER function in the WHERE clause


Dr. Chen, Oracle Database System (Oracle)

LOWER Function (cont.)


Used to convert characters to mixed case

Figure 10-2 LOWER function in the SELECT and WHERE clauses


Dr. Chen, Oracle Database System (Oracle)

UPPER Function
Used to convert characters to uppercase letters
It can be used in the same way as the LOWER
function
To affect the display of characters, it is used in
a SELECT clause
To modify the case of characters for a search
condition, it is used in a WHERE clause
The syntax for the UPPER function is UPPER(c)
Where c is the character string or field to be
converted into uppercase characters
Dr. Chen, Oracle Database System (Oracle)

10

UPPER Function manage user input


-- chapter 10, Figure 10-3; p.335
SELECT firstname, lastname
FROM customers
WHERE lastname = UPPER('&Custval');

Dr. Chen, Oracle Database System (Oracle)

Figure 10-3 Using UPPER function to manage user input

11

INITCAP Function
Used to convert character strings to mixed case,
which each word beginning with a capital letter.

Figure 10-4 INITCAP function in a SELECT clause modifies the display

Dr. Chen, Oracle Database System (Oracle)

12

Character Manipulation Functions


Character manipulation functions manipulate
data by extracting substrings, counting the
number of characters, replacing strings, etc.

Dr. Chen, Oracle Database System (Oracle)

13

SUBSTR Function
Used to return a substring, or portion of a string
SUBSTR (c, p, l)
Where
c: the character
string
p: the beginning
character position,
l: the length of
the string to
return in the
query result.
-p: backward p
position
Figure 10-6 Comparison of SUBSTR arguments
Dr. Chen, Oracle Database System (Oracle)

14

INSTR Function
start_position := INSTR(original_string, substring, starting_pos, occurrence#);
/* the first two arguments are required, the last two arguments are optional */

14

Figure 10-7 Comparison of INSTR arguments


Dr. Chen, Oracle Database System (Oracle)

Why?

15

What is PL/SQL?
Procedural programming Language
Uses detailed instructions
Processes statements sequentially

Combines SQL commands with


procedural instructions
Used to perform sequential
processing using an Oracle database

Dr. Chen, Oracle Database System (Oracle)

16

Why PL/SQL?
ORACLE
(programming language
components)

SQL
PL/SQL

D.B.

GUI
Components
(reports, forms,
graphics etc.)
Dr. Chen, Oracle Database System (Oracle)

17

Using SQL Commands in PL/SQL


Programs
Category

Purpose

Date Definition Create/change


Language (DDL) the database
structure

Examples of
Commands

Can Be Used
in PL/SQL

CREATE, ALTER,
DROP, GRANT,
REVOKE

No

Data
Manipulation
Language
(DML)

Query or change SELECT, INSERT,


UPDATE, DELETE
the data in the
database tables

Transaction
control
commands

Organize DML
commands into
logical
transactions

Dr. Chen, Oracle Database System (Oracle)

COMMIT,
ROLLBACK,
SAVEPOINT

Yes

Yes

18

Fundamentals of PL/SQL
Full-featured programming language
Execute using Oracle 11g utilities
SQL*Plus
Forms Builder

An interpreted language
Semicolon ends each command
Reserved words
Type in editor, execute in SQL*Plus

Dr. Chen, Oracle Database System (Oracle)

19

Table: PL/SQL command capitalization styles


Item Type

Capitalization

Example

Reserved Words

Uppercase

BEGIN, DECLARE

Built-in functions

Uppercase

COUNT, TO_DATE

Predefined data types

Uppercase

VARCHAR2, NUMBER

SQL commands

Uppercase

SELECT, INSERT

Database objects

Lowercase

student, fid

Variable names

Lowercase

s_first_name, faculty_id

Mixed case

Student_F_Name, Faculty_ID

Dr. Chen, Oracle Database System (Oracle)

20

Identifiers and Variables:


Rules for Names and Properties

From 1 to 30 characters
Only alphanumeric characters, and special
characters ($ _ #)
Must begin with a letter and can not contain
blank spaces or hyphens

And sure they cannot be reserved words


(e.g., BEGIN)
Dr. Chen, Oracle Database System (Oracle)

21

Variables and Data Types


Variables
Used to store numbers, character strings, dates,
and other data values
Avoid using keywords, table names and column
names as variable names
Must be declared with data type before use:
variable_name data_type_declaration;
e.g., current_s_id NUMBER(6);

Dr. Chen, Oracle Database System (Oracle)

22

Language Elements:
PL/SQL Data Types
(we will focus on this type)
References a single value

Scalar

Composite
References a data structure

Reference
References a specific database item (e.g., %TYPE,
%ROWTYPE)

LOB
References a large binary object (e.g., graphs, video)

Dr. Chen, Oracle Database System (Oracle)

23

Scalar Data Types


Represent a single value
Database scalar data types:

Dr. Chen, Oracle Database System (Oracle)

24

Scalar Data Types (cont.)


Represent a single value
Non-database scalar data types:

Dr. Chen, Oracle Database System (Oracle)

25

Tables: PL/SQL data types


Data Type

Usage

Sample Declaration

VARCHAR2

Variable-length character
strings

student_name
VARCHAR2(30);

CHAR

Fixed-length character
strings

student_gender CHAR(1);

NUMBER

Floating, fixed-point, or
integer number

current_price NUMBER(5,2);

LONG

Text, up to 32,760 bytes

evaluation_summary LONG;

DATE

Dates

todays_date DATE;

BOOLEAN

True/False values

order_flag BOOLEAN;

%TYPE

Assumes the data type of a


database field

c_address
customer.customer_address%; TYPE

%ROWTYPE

Assumes the data type of a


database record (row)

cust_order_record
cust_order% ROWTYPE;

Dr. Chen, Oracle Database System (Oracle)

26

Block Structure
PL/SQL is a block
structured language.
That just means everything
you do is done in terms of
blocks of code.

-- Figure 4-1; p.195


DECLARE /HEADER
<variable declarations>;
BEGIN
<body executable code>;

All PL/SQL blocks share


the same basic structure.

EXCEPTION

Comments:

<exception/error
handling code>;

Not executed by interpreter


Enclosed between /* and */
On one line beginning with -Dr. Chen, Oracle Database System (Oracle)

END;
27

Comment Statements
There are two types of comments in PL/SQL:
Single-line and multi-line.
Single Line:
x := 4; -- assign 4 to the variable x
Multi-line:
/* Assign 4 to
the variable x */
x := 4;
Dr. Chen, Oracle Database System (Oracle)

28

Assignment Statements

Assigns a value to a variable


variable_name := value;

Value can be a literal:


current_s_first_name := 'John';

Value can be another variable:


current_s_first_name := s_first_name;

Dr. Chen, Oracle Database System (Oracle)

29

Executing a PL/SQL Program in


SQL*Plus

Create program in text editor


-- PL/SQL #1: *** with syntax error ***
(using Notepad)
DECLARE
Paste into SQL*Plus
todays_date
DATE;
window
BEGIN
Press Enter, type / then enter
todays_date = SYSDATE;
to execute
DBMS_OUTPUT.PUT_LINE('Today''s date is ');
DBMS_OUTPUT.PUT_LINE(todays_date);
SET SERVEROUTPUT ON
END;
SIZE 4000
-- PL/SQL #2
SET SERVEROUTPUT ON
DECLARE
todays_date
DATE;
BEGIN
todays_date := SYSDATE;
DBMS_OUTPUT.PUT_LINE('Todays date is ');
DBMS_OUTPUT.PUT_LINE(todays_date);
END;
Dr. Chen, Oracle Database System (Oracle)

30

-- PL/SQL #3a (ok for this version)


--PL/SQL program to display the current date
DECLARE
todays_date DATE;
BEGIN
todays_date := SYSDATE;
DBMS_OUTPUT.PUT_LINE('Today''s date is ' || (todays_date));
END;
--PL/SQL#3b program to display the current date
-- CURRENT_DATE returns the current date and time from the user session (from
-- client software and it may be in a different location from the server database (p.355)
DECLARE
todays_date DATE;
BEGIN
todays_date := CURRENT_DATE;
DBMS_OUTPUT.PUT_LINE('Today''s date is ' || TO_CHAR(todays_date));
END;
Dr. Chen, Oracle Database System (Oracle)

31

Data Type Conversion Functions


Function
TO_DATE

Description
Converts a character string
to a date

TO_NUMBER Converts a character string


to a number
TO_CHAR
if today is:
Tuesday,
October 15,
2011

Example
TO_DATE(07/14/01,MM/DD/YY);
TO_NUMBER(2);

Converts either a number or TO_CHAR(2);


a date to a character string
TO_CHAR(SYSDATE);
return October
TO_CHAR(SYSDATE, MONTH);
return Tuesday
TO_CHAR(SYSDATE, DAY);
return 15
TO_CHAR(SYSDATE, DD);
return 11:30 AM
TO_CHAR(curr_time, HH:MI AM);

Dr. Chen, Oracle Database System (Oracle)

32

Debugging PL/SQL Programs


Syntax error:
Command does not follow the guidelines of the
programming language
Generates compiler or interpreter error
messages

Logic error:
Program runs but results in an incorrect result
Caused by mistake in program
RUN-TIME error
Dr. Chen, Oracle Database System (Oracle)

33

-- PL/SQL#5a Program with a logic error and debugging statements


DECLARE
Call ID department is: MIS
curr_call_id VARCHAR2(30) := 'MIS 101'; Original string value: MIS 101
blank_space NUMBER(2);
Start position: 4
curr_dept VARCHAR2(30);
Number of characters: 3
Course Number is: 10
curr_number VARCHAR2(30);
BEGIN
PL/SQL procedure successfully completed
blank_space := INSTR(curr_call_id,' ');
curr_dept := SUBSTR(curr_call_id, 1, (blank_space - 1));
DBMS_OUTPUT.PUT_LINE('Call ID department is: ' || curr_dept);
DBMS_OUTPUT.PUT_LINE('Original string value: ' || curr_call_id);
DBMS_OUTPUT.PUT_LINE('Start position: ' || blank_space);
DBMS_OUTPUT.PUT_LINE('Number of characters: ' ||
(LENGTH(curr_call_id) - blank_space));
curr_number := SUBSTR(curr_call_id, blank_space,
(LENGTH(curr_call_id) - blank_space));
DBMS_OUTPUT.PUT_LINE('Course Number is: ' || curr_number);
END;
Dr. Chen, Oracle Database System (Oracle)

34

-- PL/SQL#5b Program with a correct logic


Call ID department is: MIS
DECLARE
curr_call_id VARCHAR2(30) := 'MIS 101'; Original string value: MIS 101
Start position: 4
blank_space NUMBER(2);
Number of characters: 3
curr_dept VARCHAR2(30);
Course Number is: 101
curr_number VARCHAR2(30);
BEGIN
PL/SQL procedure successfully completed
blank_space := INSTR(curr_call_id,' ');
curr_dept := SUBSTR(curr_call_id, 1, (blank_space - 1));
DBMS_OUTPUT.PUT_LINE('Call ID department is: ' || curr_dept);
DBMS_OUTPUT.PUT_LINE('Original string value: ' || curr_call_id);
DBMS_OUTPUT.PUT_LINE('Start position: ' || blank_space);
DBMS_OUTPUT.PUT_LINE('Number of characters: ' ||
(LENGTH(curr_call_id) - blank_space));
curr_number := SUBSTR(curr_call_id, (blank_space+1),
(LENGTH(curr_call_id) - blank_space));
DBMS_OUTPUT.PUT_LINE('Course Number is: ' || curr_number);
END;
Dr. Chen, Oracle Database System (Oracle)

35

Terminology
Function predefined block of code that
accepts arguments
Single-row function returns one row of
results for each record processed
Multiple-row function returns one result
per group of data processed (covered in the
next chapter)

Dr. Chen, Oracle Database System (Oracle)

36

Types of Functions

Table 10-1

Functions Covered in This Chapter

Dr. Chen, Oracle Database System (Oracle)

37

Practice all the examples in the text.


A Script file is available on the Bb (file
name: Ch10Queries.sql)
After completing all examples, do the HW.

Dr. Chen, Oracle Database System (Oracle)

38

Homework - Hands-On Assignments


Email me with one attachment
(Oracle_ch10_Spool_Lname_Fname.) to:
chen@jepson.gonzaga.edu
with subject title of
bmis441_Oracle_ch10 or mbus699_Oracle_ch10
Read and Practice all examples on Chapters 10
1. Run the script files (in the folder
\oradata\chapter10\): JLDB_Build_10.sql and
download other data files
2. Read Oracle assignment and create a script file
Oracle_ch10_Lname_Fname.sql for questions
(#3,4,10; p.381) on Hands-on Assignments. Use
appropriate COLUMN statements to produce readable
outputs
3. Execute and test one problem at a time and make sure
they are all running successfully.
4. When you done, spool the script files (see next slide
for spooling instructions) and email the file
(Oracle_ch10_Spool_Lname_Fname.txt) to me by the
midnight before the next class.
Dr. Chen, Oracle Database System (Oracle)

39

How to Spool your Script and Output Files


After you tested the script file of Oracle_ch10_Lname_Fname.sql
successfully, follow the instructions below to spool both script and output
files:
Step 0. Run the following script file from SQL*Plus (since you have created
JLDB tables)
Start c:\oradata\chapter10\JLDB_Build_10.sql

1. type the following on SQL>


Spool c:\oradata\Oracle_ch10_Spool_Lname_Fname.txt (make sure your name is
entered)

2. open Oracle_ch10_Lname_Fname.sql that you already tested


3. copy and paste all the SQL commands (including all comments) to the
SQL*PLUS
4. type Spool Off on the SQL>
The output should contain your personal information, all SQL commands and
their solution on the .txt file and saved in C: drive (oradata\ folder)
Email me with the spooled file (.txt) with attachment to:
chen@jepson.gonzaga.edu
with subject title of
bmis441_Oracle_ch10
Dr. Chen, Oracle Database System (Oracle)

40

Your Turn
PART II
Study yourself
Learning to learn and learning to change

Dr. Chen, Oracle Database System (Oracle)

41

Nesting Functions

Figure 10-8 INSTR nested inside SUBSTR


Dr. Chen, Oracle Database System (Oracle)

42

LENGTH Function
Used to determine the number of characters in a string

Figure 10-10
Dr. Chen, Oracle Database System (Oracle)

Checking data width with the LENGTH function


43

LTRIM

and RTRIM Functions

Used to remove a specific string of characters

Figure 10-12
Dr. Chen, Oracle Database System (Oracle)

Using the LTRIM function


44

REPLACE Function

Substitutes a string with another specified string

Figure 10-13
Dr. Chen, Oracle Database System (Oracle)

Using the REPLACE function


45

TRANSLATE Function

Figure 10-14

Using TRANSLATE to substitute character values

Dr. Chen, Oracle Database System (Oracle)

46

CONCAT Function

Used to concatenate two character strings

Figure 10-15
Dr. Chen, Oracle Database System (Oracle)

Using the CONCAT function


47

Number Functions
Allow for manipulation of numeric data
ROUND
TRUNC
MOD
ABS

Dr. Chen, Oracle Database System (Oracle)

48

ROUND Function
Used to round numeric columns to a stated precision

Figure 10-16

Using the ROUND function to round numbers to various places

Dr. Chen, Oracle Database System (Oracle)

49

TRUNC Function
Used to truncate a numeric value to a specific position

Figure 10-17

Using the TRUNC function to truncate numbers at various places

Dr. Chen, Oracle Database System (Oracle)

50

MOD Function

Figure 10-18

Dr. Chen, Oracle Database System (Oracle)

Using the MOD functions to return the remainder

51

ABS Function

Figure 10-19

Dr. Chen, Oracle Database System (Oracle)

The effect of using the ABS function

52

Date Functions
Used to perform date calculations or format date values
Subtract date for number of days difference

Figure 10-20

A calculation with date columns

Dr. Chen, Oracle Database System (Oracle)

53

MONTHS_BETWEEN Function

Determines the number of months between two


dates

Figure 10-21
Dr. Chen, Oracle Database System (Oracle)

Using the MONTHS_BETWEEN function


54

ADD_MONTHS Function

Adds a specified number of months to a date

Figure 10-22
Dr. Chen, Oracle Database System (Oracle)

Using the ADD_MONTHS function


55

NEXT_DAY Function

Determines the next occurrence of a specified day


of the week after a given date

Figure 10-23
Dr. Chen, Oracle Database System (Oracle)

Using the NEXT_DAY function


56

TO_DATE Function

Converts various date formats to the internal


format (DD-MON-YY) used by Oracle 11g

Figure 10-25
Dr. Chen, Oracle Database System (Oracle)

Using the TO_DATE function


57

Format Model Elements - Dates

Table 10-2
Dr. Chen, Oracle Database System (Oracle)

Format Arguments for Dates


58

ROUND Function

Figure 10-26

Rounding dates by month and year

Dr. Chen, Oracle Database System (Oracle)

59

TRUNC Function

Figure 10-27

Using the TRUNC function on date calculation results

Dr. Chen, Oracle Database System (Oracle)

60

TO_CHAR Function
Converts dates and numbers to a formatted
character string

Figure 10-39
Dr. Chen, Oracle Database System (Oracle)

Formatting values for display with TO_CHAR


61

TO_NUMBER Function

Figure 10-43

Using the TO_NUMBER function to convert a string to a numeric datatype

Dr. Chen, Oracle Database System (Oracle)

62

DUAL Table
Dummy table
Consists of one column and one row
Can be used for table reference in the FROM
clause

Dr. Chen, Oracle Database System (Oracle)

63

Using DUAL

Figure 10-44

Dr. Chen, Oracle Database System (Oracle)

Practicing functions by using a DUAL table

64

Summary
Single-row functions return a result for each row or record
processed
Case conversion functions such as UPPER, LOWER, and
INITCAP can be used to alter the case of character strings
Character manipulation functions can be used to extract
substrings (portions of a string), identify the position of a
substring in a string, replace occurrences of a string with
another string, determine the length of a character string, and
trim spaces or characters from strings
Nesting one function within another allows multiple
operations to be performed on data

Dr. Chen, Oracle Database System (Oracle)

65

Summary (continued)
Simple number functions such as ROUND and TRUNC can
round or truncate a number on both the left and right side of a
decimal
The MOD function is used to return the remainder of a
division operation
Date functions can be used to perform calculations with dates
or to change the format of dates entered by a user
Regular expressions enable complex pattern matching
operations
The NVL, NVL2, and NULLIF functions are used to address
problems encountered with NULL values

Dr. Chen, Oracle Database System (Oracle)

66

Summary (continued)
The TO_CHAR function lets a user present numeric data and
dates in a specific format
The DECODE function allows an action to be taken to be
determined by a specific value
The searched CASE expression enables you to evaluate
conditions to determine the resulting value
The SOUNDEX function looks for records based on the
phonetic representation of characters
The DUAL table can be helpful when testing functions

Dr. Chen, Oracle Database System (Oracle)

67