The document discusses various PL/SQL program data types including numeric, string, and date/time data types. It describes declaring variables and constants, subtypes, implicit and explicit data type conversions. For numeric data types it covers the NUMBER, PLS_INTEGER, BINARY_INTEGER, and floating point types as well as predefined subtypes. For strings it discusses the CHAR, VARCHAR2, NCHAR, NVARCHAR2 types and working with strings using functions. Date/time datatypes and intervals are also covered.
2. ORACLE PL / SQL
CHAPTER 3: PL / SQL PROGRAM DATA -
PART I
by Prabhat Kumar
3. Contents
Program Data:
- Declaring Program data.
- Subtypes.
- Datatypes Conversion.
String Datatypes:
- Type of String datatypes.
- String Subtypes.
- Working with strings.
Number Datatypes :
- Types of Numeric Datatypes.
- Pre-defined Numeric Subtypes.
- Number Conversions.
- Numeric Function.
- Numeric Operators.
VIC 3
4. Date and Timestamps Datatypes:
- Type of Datetime datatypes.
- Datetime variable declaration.
- Timezone in Datetime Datatypes.
- Interval Datatypes.
- Datetime Conversions.
- Interval Conversions.
- Useful datatime functions.
Practitioners Guide
Error Codes.
A bit of an Advice.
VIC 4
5. Program data
Program data consists of data structures that exist only within your PL/SQL session within the
Program
Global Area, or PGA, for your session); they are not stored in the database. Program data can
be:
- a Variable whose value can change during program execution.
- a Constant whose value is set at declaration and can not change during program
execution.
- a scalar that consists of a single value like a string or number or date.
- a composite that can have multiple values like a record, a collection, etc.
- a Containerized that can contain information obtained from database.
Declaring Program Data:
Before using any variable in a program, it needs to be defined in DECLARE section:
A. Declaring a variable means :
a. to give it a name. Naming your data structure must follow below rules:
1. Names can be up to 30 characters in length.(limit increased in latest version 12 c).
2. Names must start with a letter followed by any of letters, numerals, $, #, and _.VIC 5
6. b. assign it a datatype.
1. used to validate values assigned to a variable.
2. a datatype can be a predefined scalar or composite datatype( defined in PL/SQL
STANDARD package), or
3. it can be any of the user defined datatype( abstract datatypes).
B. inside, when a variable is declared, PL/SQL allocates memory for the variable's values and names
that memory
location for retrieval of value.
C. Syntax for Variable declaration:
name datatype [NOT NULL] [ := | DEFAULT default_assignment];
where, name is the name of variable to be declared, datatype is the datatype or subtype(described
later in
this chapter),
NOT NULL clause is used to raise exception whenever no value is assigned to the declared
variable,
default_assignment clause assigns default values to the declared variable.
D. Syntax for Constant declaration:
name CONSTANT datatype [NOT NULL] := | DEFAULT default_value;
where, CONSTANT keyword tells that the declaration is a constant, VIC 6
7. E. Anchored Declaration:
- anchor a datatype is to set the datatype of a variable as the datatype of an already defined data
structure.
- this can be done with already defined PL/SQL variable, a predefined TYPE or SUBTYPE, a
database
table or column in a table.
- Anchoring can be:
- Scalar anchoring:
- Using %TYPE to define variable using table's column or other PL/SQL scalar variable.
- Syntax:
variable_name type_attribute%TYPE [default_value_optional];
- Record anchoring:
- Using %ROWTYPE to define a record type based on table or predefined PLSQL explicit
cursor.
- Syntax:
variable_name table_name | cursor_name%ROWTYPE
[optional_default_value_optional];
VIC 7
8. Subtype:
- a subtype of any datatype specifies same set of rules as original datatype but might
allow
only subset of the datatype's values.
- Subtypes can be:
1. Constrained subtype:
- these subtypes restricts the values allowed by base datatype. For eg:
- POSITIVE is a constrained subtype of BINARY_INTEGER base type allowing
only positive
integer values.
2. Unconstrained subtype:
- these subtypes does not restricts the values allowed by base datatype. For eg:
- FLOAT is an unconstrained subtype of NUMBER base type.
- an unconstrained subtype provides an alternate name for the base datatype.
- Syntax:
SUBTYPE subtype_name IS base_type; VIC 8
9. VIC 9
Datatypes Conversion:
- a program data can be converted from one datatype to another datatype by two ways:
1. Implicit Conversion:
- this type of conversion is done by PL/SQL runtime engine itself.
2. Explicit Conversion:
- by calling predefined PL/SQL functions.
Table 1: Commonly used Explicit conversion functions.
Name Description
CAST Converts one built-in datatype or collection-typed value to another built-in datatype or collection-
typed value
MULTISE
T
Maps a database table to a collection.
CONVER
T
Converts a string from one character set to another.
TABLE Maps a collection to a database table; this is the inverse of MULTISET.
TO_LOB Converts from a LONG to a LOB.
TO_DAT
E
Converts a string to a date.
10. VIC 10
Type of String datatypes:
Oracle supports four string datatypes
1. CHAR:
- used for variables with Fixed-length Database character set.
- maximum length of a string needs to be specified in the declaration of CHAR datatype
that can be
between 1 and 32,767 bytes.
- Syntax:
standard_name CHAR(100 BYTE);
or standard_name CHAR(100 CHAR);
- actual number of bytes in 100-char defined here will be dependent on database
character set.
- if BYTE/CHAR is not specified in the declaration, result will be according to the
NLS_LENGTH_SEMANTICS initialization parameter settings.
- if max length is not specified, then string will be of 1 byte.
- PL/SQL will right pad any value assigned to a CHAR variable with spaces to the
maximum length specified in the declaration.
String Datatypes
11. 2. NCHAR : Fixed-length National character set. Details of this datatype will be given later.
3. VARCHAR2:
- Used for Variable-length Database character set.
- maximum length of a string needs to be specified in the declaration of VARCHAR2 datatype
that can be
between 1 and 32,767 bytes.
- Syntax:
variable_name VARCHAR2 (max_length [CHAR | BYTE]);
where, variable_name is the name of variable to be declared, max_length is the
maximum length
of the variable,
CHAR / BYTE indicates that max_length is expressed in terms of characters/
bytes resp.
- maximum length allowed for a PL/SQL VARCHAR2 variables is 32,767 bytes.
4. NVARCHAR2 : Variable-length National character set. Details of this datatype will be given later.
VIC 11
12. String Subtypes:
Following table lists PL/SQL string subtypes and their equivalent PL/SQL types:
TABLE 2 :Subtypes of Strings.
VIC 12
Subtype Equivalent PL/SQL type
CHAR VARYING VARCHAR2
CHARACTER CHAR
CHARACTER VARYING VARCHAR2
NATIONAL CHAR NCHAR
NATIONAL CHAR VARYING NVARCHAR2
NATIONAL CHARACTER NCHAR
NATIONAL CHARACTER VARYING NVARCHAR2
NCHAR VARYING NVARCHAR2
STRING VARCHAR2
VARCHAR VARCHAR2
13. Working with strings: Below code demonstrates concepts of string datatypes in PL/SQL:
PLS_1: SQL> DECLARE
2 A VARCHAR2(100 BYTE);
3 B VARCHAR2(100 BYTE);
4 C VARCHAR2(100 BYTE);
5 A_UPPERCASE VARCHAR2(100 BYTE);
6 A_LOWERCASE VARCHAR2(100 BYTE);
7 CONCAT_STR VARCHAR2(200 BYTE);
8 STR_CONSTANT VARCHAR2(30) := '.....String Constant.....';
9 STR_POS NUMBER;
10 BEGIN
11 DBMS_OUTPUT.PUT_LINE('<-------Working with strings------>');
12 A := 'This is a string constant.';
13 B := 'This is a quote( '' ) embedded string constant.';
14 C := q'!This is a quote( ' ) embedded string constant using q prefix.!';
15
16 DBMS_OUTPUT.PUT_LINE('<-------Print String constant on screen------->');
17 DBMS_OUTPUT.PUT_LINE(A);
18 DBMS_OUTPUT.PUT_LINE(B);
19 DBMS_OUTPUT.PUT_LINE(C);
20
21 DBMS_OUTPUT.PUT_LINE('<-------Passing string constant to a built-in function------->');
22 DBMS_OUTPUT.PUT_LINE(LENGTH('This is a string constant.'));
23
VIC 13
14. VIC
24 DBMS_OUTPUT.PUT_LINE('<-------Formatting Strings using CHR() function------->');
25 DBMS_OUTPUT.PUT_LINE( 'String constant A is: '||A||CHR(10)
26 ||'String constant B is: '||B||CHR(10)
27 ||'String constant C is: '||C||CHR(10) );
28
29 DBMS_OUTPUT.PUT_LINE('<-------Converting String constant to Upper-case string------->');
30 A_UPPERCASE := UPPER('This is a string constant');
31 DBMS_OUTPUT.PUT_LINE(A_UPPERCASE||UPPER(' in upper-case.'));
32
33 DBMS_OUTPUT.PUT_LINE('<-------Converting String constant to Lower-case string------->');
34 A_LOWERCASE := LOWER('This is a string constant');
35 DBMS_OUTPUT.PUT_LINE(A_LOWERCASE||LOWER(' in lower-case.'));
36
37 DBMS_OUTPUT.PUT_LINE('<-------Comparing strings after converting to lower-case----->');
38 IF LOWER(A_UPPERCASE) = LOWER(A_LOWERCASE) THEN
39 DBMS_OUTPUT.PUT_LINE('String constants match successful.');
40 END IF;
14
15. 41
42 DBMS_OUTPUT.PUT_LINE('<-------Concatenating Strings------->');
43 CONCAT_STR := CONCAT(A, B);
44 DBMS_OUTPUT.PUT_LINE('Result of concatenation is: '||CONCAT_STR);
45
46 DBMS_OUTPUT.PUT_LINE('<-------Search in Strings------->');
47 STR_POS := INSTR(A, 'string');
48 IF STR_POS > 0 THEN
49 DBMS_OUTPUT.PUT_LINE('Search is successful. Match found at position: '||STR_POS||'.');
50 ELSE
51 DBMS_OUTPUT.PUT_LINE('Search failed.');
52 END IF;
53
54 DBMS_OUTPUT.PUT_LINE('<-------Padding in Strings------->');
55 DBMS_OUTPUT.PUT_LINE(RPAD(A, 100)||'. Right padding ends here.');
56 DBMS_OUTPUT.PUT_LINE('Left padding starts here. '||LPAD(A, 100));
57
58 DBMS_OUTPUT.PUT_LINE('<-------Padding specific character pattern in Strings------->');
59 DBMS_OUTPUT.PUT_LINE(RPAD(A, 100, '*$$*' )||'. Right padding ends here.');
60 DBMS_OUTPUT.PUT_LINE('Left padding starts here. '||LPAD(A, 100, '*$$*'));
61
62 DBMS_OUTPUT.PUT_LINE('<-------Left Trim in Strings------->');
63 DBMS_OUTPUT.PUT_LINE('This string constant has no period at its end :'||RTRIM(A, '.'));
VIC 15
16. VIC 16
64
65 DBMS_OUTPUT.PUT_LINE('<-------Right Trim in Strings------->');
66 DBMS_OUTPUT.PUT_LINE('This string constant has no character at its left:'||
67 LTRIM(CONCAT_STR, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz'));
68
69 DBMS_OUTPUT.PUT_LINE('<-------Trim in Strings------->');
70 DBMS_OUTPUT.PUT_LINE( TRIM(LEADING '.' FROM STR_CONSTANT));
71 DBMS_OUTPUT.PUT_LINE( TRIM(TRAILING '.' FROM STR_CONSTANT));
72 DBMS_OUTPUT.PUT_LINE( TRIM(BOTH '.' FROM STR_CONSTANT));
73 DBMS_OUTPUT.PUT_LINE( TRIM('.' FROM STR_CONSTANT));
74 DBMS_OUTPUT.PUT_LINE( TRIM(STR_CONSTANT));
75 END;
76 /
The NOT NULL Clause:
- a variable declaration with NOT NULL clause gives compilation error if default value is not defined in the declaration.
- PL/SQL will raise the VALUE_ERROR exception whenever a variable with NOT NULL declaration is assigned a
NULL value.
CONCAT() function can be used to concatenate only two string at a time as compared to concatenation operator that
can combine
several string.
17. Output of PLS_1 is as shown below:
<-------Working with strings------>
<-------Print String constant on screen------->
This is a string constant.
This is a quote( ' ) embedded string constant.
This is a quote( ' ) embedded string constant using q prefix.
<-------Passing string constant to a built-in function------->
26
<-------Formatting Strings using CHR() function------->
String constant A is: This is a string constant.
String constant B is: This is a
quote( ' ) embedded string constant.
String constant C is: This is a quote( ' )
embedded string constant using q prefix.
<-------Converting String constant to Upper-case string------->
THIS IS A STRING CONSTANT IN UPPER-CASE.
<-------Converting String constant to Lower-case string------->
this is a string constant in lower-case.
<-------Comparing strings after converting to lower-case------->
String constants match successful.
<-------Concatenating Strings------->
Result of concatenation is: This is a string constant. This is a quote( ' )
embedded string constant.
<-------Search in Strings------->
VIC 17
18. Search is successful. Match found at position: 11.
<-------Padding in Strings------->
This is a string constant.
. Right padding ends here.
Left padding starts here.
This is a string constant.
<-------Padding specific character pattern in Strings------->
This is a string
constant.*$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$
**$. Right padding ends here.
Left padding starts here.
*$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$$**$This
is a string constant.
<-------Left Trim in Strings------->
This string constant has no period at its end :This is a string constant
<-------Right Trim in Strings------->
This string constant has no character at its left:.This is a quote( ' ) embedded
string constant.
<-------Trim in Strings------->
String Constant.....
.....String Constant
String Constant
String Constant
.....String Constant.....
PL/SQL procedure successfully completed.
VIC 18
19. Types of Numeric Datatypes:
PL/SQL offers a variety of numeric datatypes for different purposes. These are:
1. NUMBER Type:
- a platform-independent decimal datatype ideal to deal with monetary amounts.
- Used to store integer, fixed-point, or floating-point numbers of just about any size.
DECLARE
x NUMBER;
- this is a floating-point NUMBER declaration.
DECLARE
x NUMBER(precision, scale);
- this is a fixed-point NUMBER declaration with,
- precision signifying total number of significant digits. Valid range from 1 to 38.
- scale signifying number of digits to the right(positive scale) or left(negative
scale) of
decimal point. Valid range from -84 to 127.
- scale affects where the rounding off occurs.
2. PLS_INTEGER Type:
- stores signed integers with range -2,147,483,648 through 2,147,483,647
- conforms to hardware’s underlying integer representation.
- uses native machine arithmetic unlike NUMBER datatype that uses C language
arithmetic library.
- speeds up computation in intensive integer arithmetic.
- when used in integer arithmetic, results are rounded to whole numbers.
VIC 19
Number Datatypes
20. 3. BINARY_INTEGER Type:
- stores signed integers in a binary format.
- implemented using platform-independent library code.
4. SIMPLE_INTEGER Type:
- its a performance enhanced version of PLS_INTEGER with same range.
- it does not support NULL values or check for overflow conditions.
5. BINARY_FLOAT and BINARY_DOUBLE Types:
- conform to the single- and double-precision floating point types defined in the IEEE-754
floating
point standard.
- implemented by both PL/SQL and the database engine so can be used in table
definitions and
PL/SQL code.
- use suffix - either f or d, depending on whether you want your literal to be interpreted as a
BINARY_FLOAT or as a BINARY_DOUBLE.
DECLARE
v_binary_float BINARY_FLOAT := .95f;
v_binary_double BINARY_DOUBLE := .95d;
6. SIMPLE_FLOAT and SIMPLE_DOUBLE Types:
- these datatypes are performance-enhanced versions of the BINARY_FLOAT and
BINARY_DOUBLE
datatypes with same range.
- it does not support NULL values or check for overflow conditions.
VIC 20
21. Table_3: Pre-defined Numeric Subtypes:
VIC 21
Subtype Corresponding Oracle Datatype
DEC (precision, scale) NUMBER (precision, scale)
DECIMAL (precision, scale) NUMBER (precision, scale)
DOUBLE PRECISION NUMBER, with 126 binary digits of precision
FLOAT NUMBER, with 126 binary digits of precision
FLOAT (binary_precision) NUMBER, with a binary_precision of up to 126 (126 is the default)
INT NUMBER(38)
INTEGER NUMBER(38)
NATURAL PLS_INTEGER with only nonnegative values (0 and higher)
NATURALN NATURA with the additional restriction of never being NULL
NUMERIC NUMBER (precision, scale)
POSITIVE PLS_INTEGER with only positive values (1 and higher)
POSITIVEN POSITIVE with the additional restriction of never being NULL
REAL NUMBER with 63 binary digits of precision
SIGNTYPE PLS_INTEGER limited to the values -1, 0, and 1
SMALLINT NUMBER(38)
22. VIC 22
Number Conversions:
- PL/SQL allows you to convert numbers between human- and machine-readable form.
- the PL/SQL functions used for such conversions are:
1. TO_NUMBER:
- converts both fixed- and variable-length strings & IEEE-754 floating-point types to
NUMBER
datatype. Format:
TO_NUMBER(string [,format [,nls_params]])
- string is a string or BINARY_DOUBLE expression containing the representation of a
number.
- format specifies format mask of first parameter.
- nls_params specifies NLS parameter values overrides session-level NLS parameter
settings.
2. TO_CHAR:
- converts numbers to their character representations. Format:
TO_CHAR(number [,format [,nls_params]])
- number is the number to be represented in character form.
- format specifies the format to be used to represent number in character form.
- nls_params specifies NLS parameter values overrides session-level NLS parameter
23. VIC 23
3. CAST:
- used to convert numbers to strings and vice-versa.
- Format:
CAST (expression AS datatype)
- it does not support the use of number format models.
Numeric Functions:
Some useful numeric functions are:
A. Rounding off Functions:
1.CEIL : Returns the smallest integer that is greater than or equal to the specified value.
2.FLOOR : Returns the largest integer that is less than or equal to the specified value.
3.ROUND : Performs rounding on a number. You can round with a positive number of
decimal places
(the number of digits to the right of the decimal point) and also with a negative
number of decimal places (the number of digits to the left of the decimal point).
B. Truncation functions:
1.TRUNC : Truncates a number to the specified number of decimal places. It discards all
values
beyond the number of decimal places provided in the call.
24. C. Some others functions are:
1.GREATEST(n1, n2, ... n3) :
- Returns the largest number among the list of input numbers.
2.LEAST(n1, n2, ... n3) :
- returns the lowest number among the list of input numbers.
3.MOD(n, m) :
- returns the remainder of n divided by m.
- when n and m are both positive or both negative, remainder is n–(m*FLOOR(n/m))
- when the signs of n and m differ, remainder is n–(m*CEIL(n/m)).
4.REMAINDER(n, m) :
- returns the “remainder” of n divided by m. The remainder is defined as n-
(m*ROUND(n/m).
5.POWER(n, m) : raises n to the power m. If n is negative, then m must be an integer.
Numeric Operators:
The operators that can be used with numbers are shown below Table 4, in order of
precedence. The
operators with lower precedence evaluate first, while higher precedence evaluated later:
VIC 24
25. VIC 25
Operator Operation Precedence
** Exponentiation 1
+ Identity 2
- Negation 2
* Multiplication 3
/ Division 3
+ Addition 4
- Subtraction 4
= Equality 5
< Less than 5
> Greater than 5
<= Less than or equal to 5
>= Greater than or equal to 5
<>, !=, ~=, ^= Not equal 5
IS NULL Nullity 5
BETWEEN Inclusive range 5
NOT Logical negation 6
AND Conjunction 7
OR Inclusion 8
Table 4: Numeric Operators
26. VIC 26
Type of Datetime datatypes:
The four datetime datatypes are:
1. DATE:
a. Stores a date and time, resolved to the second.
2. TIMESTAMP:
a. Stores a date and time with resolution of time to the billionth of a second.
3. TIMESTAMP WITH TIME ZONE:
a. Stores the time zone along with the date and time value.
4. TIMESTAMP WITH LOCAL TIME ZONE:
a. Stores a date and time with up to nine decimal places of precision.
b. this datatype is sensitive to time zone differences is following manner:
- When values are stored in the database, they are converted to the database
time zone
- When a value is retrieved from the database, that value is converted from
the database time zone to the local (session) time zone.
Date and Timestamps
Datatypes
27. VIC 27
Datetime variable declaration:
- Following syntax is used to declare datetime variable:
var_name [CONSTANT] datetime_type [{:= | DEFAULT} initial_value]
where, datetime_type with any one of the following:
DATE
TIMESTAMP [(precision)]
TIMESTAMP [(precision)] WITH TIME ZONE
TIMESTAMP [(precision)] WITH LOCAL TIME ZONE
where, precision is the number of decimal digits used for fractional seconds.
For eg: Following are of the declarations of Datetime datatype:
DECLARE
join_date TIMESTAMP (0) WITH TIME ZONE;
present_date CONSTANT DATE := SYSDATE;
bill_date TIMESTAMP DEFAULT TO_TIMESTAMP('20180918','YYYYMMDD');
BEGIN
NULL;
END;
28. VIC 28
Below Table shows the functions that can be used to retrieve current value of date and time
based
on current session and database state.
Table 5: Current Date and Time functions.
Function Time zone Datatype returned
CURRENT_DATE Session DATE
CURRENT_TIMEST
AMP
Session TIMESTAMP WITH TIME ZONE
LOCALTIMESTAMP Session TIMESTAMP
SYSDATE Database server DATE
SYSTIMESTAMP Database server TIMESTAMP WITH TIME ZONE
A session is a logical entity in the database instance memory that represents the state of a
current user
login to a database. A single connection can have 0, 1 or more sessions established on it.
29. VIC 29
Timezone in Datetime Datatypes: Time zone information can be specified in any of the
following ways:
Using a positive or negative displacement of hours and minutes from UTC time, using a time zone
region name or
using a combination of time zone region name and abbreviation.
PLS_2: SQL> DECLARE
2 V_TIMESTAMP TIMESTAMP WITH TIME ZONE;
3 V_TIMESTAMP2 TIMESTAMP WITH TIME ZONE;
4 V_TIMESTAMP3 TIMESTAMP WITH TIME ZONE;
5 BEGIN
6 V_TIMESTAMP := TO_TIMESTAMP_TZ ('092418 081115.50 +5:30', 'MMDDYY HHMISS.FF TZH:TZM');
7 V_TIMESTAMP2 := TO_TIMESTAMP_TZ ('24-SEP-2018 08:15:00 Asia/Calcutta', 'dd-Mon-yyyy hh:mi:ss TZR');
8 V_TIMESTAMP3 := TO_TIMESTAMP_TZ ('02-Nov-2014 01:30:00.00 Asia/Calcutta IST','dd-Mon-yyyy hh:mi:ssxff TZR
TZD');
9 DBMS_OUTPUT.PUT_LINE('Using displacement of hours and minutes: '||V_TIMESTAMP||CHR(10)|| 'Using time
zone region
10 name: '||V_TIMESTAMP2||CHR(10)|| 'Using time zone region name and abbreviation: '||V_TIMESTAMP2);
11 END;
12 /
Using displacement of hours and minutes: 24-SEP-18 08.11.15.500000 AM +05:30
Using time zone region name: 24-SEP-18 08.15.00.000000 AM ASIA/CALCUTTA
Using time zone region name and abbreviation: 24-SEP-18 08.15.00.000000 AM ASIA/CALCUTTA
PL/SQL procedure successfully completed.
30. VIC 30
Interval Datatypes:
- these datatypes are used to records specific amount or quantity of time.
- two Interval datatypes are:
1. INTERVAL YEAR TO MONTH : defines interval of time in terms of years and
months.
2. INTERVAL DAY TO SECOND : defines interval of time in terms of days, hours,
minutes and
seconds (including fractional seconds).
- INTERVAL Variables declaration:
var_name INTERVAL YEAR [(year_precision)] TO MONTH
or:
var_name INTERVAL DAY [(day_precision)] TO SECOND [(frac_sec_prec)]
where: var_name is the name of the INTERVAL variable that you want to declare.
year_precision is the number of digits (from 0 to 4) for a year value( default =
2).
day_precision is the number of digits (from 0 to 9) for a day value.(default =
2).
frac_sec_prec is the number of digits (from 0 to 9) for fractional
seconds(default = 6).
31. VIC 31
- Below code PLS_3 describes interval year to month as a result of difference of to timestamp
datatypes:
PLS_3:
SQL> DECLARE
2 START_DATE TIMESTAMP;
3 END_DATE TIMESTAMP;
4 TIME_PERIOD INTERVAL YEAR TO MONTH;
5 BEGIN
6 START_DATE := TO_TIMESTAMP('05-JUL-2014','dd-mon-yyyy');
7 END_DATE := TO_TIMESTAMP ('21-JUL-2018','dd-mon-yyyy');
8 TIME_PERIOD := (END_DATE - START_DATE) YEAR TO MONTH;
9 DBMS_OUTPUT.PUT_LINE(TIME_PERIOD);
10 END;
11 /
+04-01
PL/SQL procedure successfully completed.
32. VIC 32
Datetime Conversions:
Two type of Datetype conversions are:
1. From Strings to Datetimes:
- Following functions converts strings to Dates and Timestamps:
a. TO_DATE(string[, format_mask[, nls_language]])
- Converts a character string to a DATE type.
b. TO_DATE(number[, format_mask[, nls_language]])
- Converts a number representing a Julian date to a DATE type.
c. TO_TIMESTAMP(string[, format_mask[, nls_language]])
- Converts a character string to a value of TIMESTAMP type.
d. TO_TIMESTAMP_TZ(string[, format_mask[, nls_language]])
- Converts a character string to a value of TIMESTAMP WITH TIME ZONE type.
- use this function when your target is TIMESTAMP WITH LOCAL TIMEZONE.
string is the string variable, literal, constant, or expression to be converted to
Date type.
format_mask is the format mask to be used in converting the string.
nls_language specifies the language to be used to interpret the names &
abbreviations.
33. VIC 33
2. From Datetimes to Strings:
- TO_CHAR function converts Dates and Timestamps to human-readable string format.
- Below is its specification:
FUNCTION TO_CHAR (date_in IN DATE [, format_mask IN VARCHAR2 [, nls_language
IN
VARCHAR2]]) RETURN VARCHAR2
where, date_in is the date to be converted to character format.
format_mask is the mask, made up of one or more of the date format elements.
The default format is 'DD-MON-RR'.
nls_language is a string specifying a date language.
PLS_4 below describes datetime conversions in details:
PLS_4:
SQL> DECLARE
2 DT DATE;
3 TS TIMESTAMP;
4 TSTZ TIMESTAMP WITH TIME ZONE;
5 TSLTZ TIMESTAMP WITH LOCAL TIME ZONE;
6 DT_CHR VARCHAR2(50);
7 A_TIMESTAMP VARCHAR2(100);
34. VIC 34
8 BEGIN
9 --<<-----From Strings to Datetimes----->>--
10 DT := TO_DATE('09/18/2018','mm/dd/yyyy');
11 TS := TO_TIMESTAMP('18-SEP-2018 11.13.00.50 PM');
12 TSTZ := TO_TIMESTAMP_TZ('09/18/2018 11:14:00.50 PM EST', 'mm/dd/yyyy hh:mi:ssxff AM TZD');
13 TSLTZ := TO_TIMESTAMP_TZ('09/18/2018 11:14:00.50 PM EST', 'mm/dd/yyyy hh:mi:ssxff AM TZD');
14 DBMS_OUTPUT.PUT_LINE(DT);
15 DBMS_OUTPUT.PUT_LINE(TS);
16 DBMS_OUTPUT.PUT_LINE(TSTZ);
17 DBMS_OUTPUT.PUT_LINE(TSLTZ);
18 --<<-----From Datetimes to Strings----->>--
19 DT_CHR := TO_CHAR(SYSDATE);
20 /*Returns default format DD-MON-RR*/
21 DBMS_OUTPUT.PUT_LINE(DT_CHR);
22 DT_CHR := TO_CHAR(SYSDATE, 'YYYY-DD-MM');
23 /*Returns specific format as defined in parameter of call to to_char()*/
24 DBMS_OUTPUT.PUT_LINE(DT_CHR);
25 DT_CHR := TO_CHAR (SYSDATE, 'Month DD, YYYY');
35. VIC 35
26 /*Notice two blanks between month and day*/
27 DBMS_OUTPUT.PUT_LINE(DT_CHR);
28 DT_CHR := TO_CHAR (SYSDATE, 'FMMonth DD, YYYY');
29 /*FM fill mode element is used to suppress blanks and zeroes*/
30 DBMS_OUTPUT.PUT_LINE(DT_CHR);
31 DT_CHR := TO_CHAR (SYSDATE, 'MON DDth, YYYY');
32 /*Month is in upper case when format mask is in upper case,
33 ||'th' is not CASE sensitive(always upper-case)*/
34 DBMS_OUTPUT.PUT_LINE(DT_CHR);
35 DT_CHR := TO_CHAR (SYSDATE, 'fmMon DDth, YYYY');
36 /*Month is in lower case when format mask is in lower case,
37 || 'th' is not CASE sensitive(always upper-case)*/
38 DBMS_OUTPUT.PUT_LINE(DT_CHR);
39 A_TIMESTAMP := TO_CHAR (CURRENT_TIMESTAMP, 'YYYY-MM-DD HH:MI:SS.FF AM TZH:TZM');
40 /*return specific format for a timestamp datatype*/
41 DBMS_OUTPUT.PUT_LINE(A_TIMESTAMP);
42 END;
43 /
36. VIC 36
Output of PLS_4 is shown below:
18-SEP-18
18-SEP-18 11.13.00.500000 PM
18-SEP-18 11.14.00.500000 PM +05:30
18-SEP-18 11.14.00.500000 PM
18-SEP-18
2018-18-09
September 18, 2018
September 18, 2018
SEP 18TH, 2018
Sep 18TH, 2018
2018-09-18 11:48:11.652000000 PM +05:30
PL/SQL procedure successfully completed.
Interval Conversions:
- An interval is composed of one or more of following datetime elements:
YEAR Some number of years, ranging 1 through 999,999,999
MONTH Some number of months, ranging 0 through 11
37. VIC 37
DAY Some number of days, ranging 0 to 999,999,999
HOUR Some number of hours, ranging 0 through 23
MINUTE Some number of minutes, ranging 0 through 59
SECOND Some number of seconds, ranging 0 through 59.999999999
Interval Conversion consists of two main type:
1.Numbers to Intervals Conversion:
a. NUMTOYMINTERVAL : converts a numeric value to an interval of type INTERVAL
YEAR TO
MONTH.
b. NUMTODSINTERVAL : converts a numeric value to an interval of type INTERVAL DAY
TO
SECOND.
2. Strings to Intervals Conversion:
a. TO_YMINTERVAL :
- converts a character string value into an INTERVAL YEAR TO MONTH. General
Syntax is:
TO_YMINTERVAL('Y-M'),
38. VIC 38
b. TO_DSINTERVAL : converts a character string value into an INTERVAL DAY TO
SECOND. Syntax is:
TO_DSINTERVAL('D HH:MI:SS.FF'), where
D is some number of days, HH:MI:SS.FF represents hours, minutes, seconds and
fractional seconds.
PLS_5 shows demonstrates Intervals to Strings Conversion:
PLS_5: SQL> DECLARE
2 INTRVL_YR_TO_MNTH INTERVAL YEAR TO MONTH;
3 INTRVL_DY_TO_SEC INTERVAL DAY TO SECOND;
4 BEGIN
5 INTRVL_YR_TO_MNTH := NUMTOYMINTERVAL (2.5,'Year');
6 DBMS_OUTPUT.PUT_LINE(INTRVL_YR_TO_MNTH);
7 INTRVL_DY_TO_SEC := NUMTODSINTERVAL (1440,'Minute');
8 DBMS_OUTPUT.PUT_LINE(INTRVL_DY_TO_SEC);
9 END;
10 /
+02-06
+01 00:00:00.000000
PL/SQL procedure successfully completed.
39. VIC
PLS_6 demonstrates Strings to Intervals Conversion:
PLS_6: SQL> DECLARE
2 INTRVL_YR_TO_MNTH INTERVAL YEAR TO MONTH;
3 INTRVL_DY_TO_SEC INTERVAL DAY TO SECOND;
4 INTRVL_DY_TO_SEC2 INTERVAL DAY TO SECOND;
5 BEGIN
6 INTRVL_YR_TO_MNTH := TO_YMINTERVAL('20-3');
7 INTRVL_DY_TO_SEC := TO_DSINTERVAL('10 1:02:10');
8 INTRVL_DY_TO_SEC2 := TO_DSINTERVAL('10 1:02:10.123');
9 DBMS_OUTPUT.PUT_LINE(INTRVL_YR_TO_MNTH);
10 DBMS_OUTPUT.PUT_LINE(INTRVL_DY_TO_SEC);
11 DBMS_OUTPUT.PUT_LINE(INTRVL_DY_TO_SEC2);
12 END;
13 /
+20-03
+10 01:02:10.000000
+10 01:02:10.123000
PL/SQL procedure successfully completed.
39
40. VIC
Useful datatime functions:
These are the standard SQL function used to convert string to datetime variables, to extract
specific
component of datetime variable or add some months to given date:
1.CAST: its a standard SQL function used to convert datetime values to and from character
strings or one
datetime type to another.
2.EXTRACT: used to extract date components from a datetime value. General syntax is:
EXTRACT (component_name, FROM {datetime | interval})
where, component_name is the name of a datetime element( See Table 6),
datetime | interval is a datetime or interval value from which datetime component is to be
extracted.
Table 6:Datetime components for use in EXTRACT function.
Component name Return datatype
YEAR NUMBER
MONTH NUMBER
DAY NUMBER
HOUR NUMBER
MINUTE NUMBER
40
41. VIC
Below code PLS_7 describes conversion functions in detail:
PLS_7: SQL> DECLARE
2 V_TSTZ TIMESTAMP WITH TIME ZONE;
3 V_STRING VARCHAR2(40);
4 V_TSLTZ TIMESTAMP WITH LOCAL TIME ZONE;
5 BEGIN
6 --<<-- convert string to datetime-->>--
7 V_TSTZ := CAST ('19-Sep-2018 10.00.00.00 PM US/Eastern' AS TIMESTAMP WITH TIME ZONE);
8 --<<-- convert datetime to string-->>--
9 V_STRING := CAST (V_TSTZ AS VARCHAR2);
10 V_TSLTZ := CAST ('19-Sep-2018 10.00.00.00 PM' AS TIMESTAMP WITH LOCAL TIME ZONE);
11 DBMS_OUTPUT.PUT_LINE(V_TSTZ);
12 DBMS_OUTPUT.PUT_LINE(V_STRING);
13 DBMS_OUTPUT.PUT_LINE(V_TSLTZ);
Component name Return datatype
TIMEZONE_HOUR NUMBER
TIMEZONE_MINUTE NUMBER
TIMEZONE_REGION VARCHAR2
TIMEZONE_ABBR VARCHAR2
41
42. VIC
14 IF EXTRACT (MONTH FROM SYSDATE) = 09 THEN
15 DBMS_OUTPUT.PUT_LINE('It is September.');
16 ELSE
17 DBMS_OUTPUT.PUT_LINE('It is not September.');
18 END IF;
19 --<<--Extract Region name from Server timestamp-->>--
20 DBMS_OUTPUT.PUT_LINE(EXTRACT (TIMEZONE_REGION FROM SYSTIMESTAMP));
21 --<<--Extract Hour from Session timestamp-->>--
22 DBMS_OUTPUT.PUT_LINE(EXTRACT (TIMEZONE_HOUR FROM CURRENT_TIMESTAMP));
23 END;
24 /
19-SEP-18 10.00.00.000000 PM US/EASTERN
19-SEP-18 10.00.00.000000 PM US/EASTERN
19-SEP-18 10.00.00.000000 PM
It is September.
UNKNOWN
5
PL/SQL procedure successfully completed.
42
43. VIC
3.MONTHS_BETWEEN:
This function is highly useful in computing intervals between two DATEs. The function has
syntax:
FUNCTION MONTHS_BETWEEN (date1 IN DATE, date2 IN DATE) RETURN NUMBER
Above function returns values as per below cases:
- If date1 is greater than date2, result is positive.
- If date1 is less than date2, result is negative.
- If date1 and date2 are in same month, result is a fraction value between -1 and 1.
- If date1 and date2 both are last day of their months, result is a whole number.
- If date1 and date2 are in different months and at least one of them is not the last day of
month,
result is a fractional number.
Below code PLS_8 describes months_between function in detail:
PLS_8: SQL> BEGIN
2 -- when two ends of month, the first earlier than the second:
3 DBMS_OUTPUT.PUT_LINE(MONTHS_BETWEEN ('31-JAN-2018', '28-FEB-2018'));
4 -- when two ends of month, the first later than the second:
43
44. VIC
6 -- when both dates fall in the same month:
7 DBMS_OUTPUT.PUT_LINE(MONTHS_BETWEEN ('28-FEB-2018', '15-FEB-2018'));
8 -- Perform months_between with a fractional component:
9 DBMS_OUTPUT.PUT_LINE(MONTHS_BETWEEN ('31-JAN-2018', '01-MAR-2018'));
10 DBMS_OUTPUT.PUT_LINE(MONTHS_BETWEEN ('10-MAR-2018', '31-JAN-2018'));
11 END;
12 /
-1
1
.4193548387096774193548387096774193548387
-1.03225806451612903225806451612903225806
1.32258064516129032258064516129032258065
PL/SQL procedure successfully completed.
44
45. Practitioners Guide
Slides ahead contains PL/SQL programs for
complete understanding of theories just
explained.Programs are designed in a way to
demonstrate the important and critical aspects of
PL/SQL programming in a unified manner.
46. VIC 46
PLS_9 describes string, datetime and timestamp datatypes, implicit and explicit conversions:
PLS_9:SQL> DECLARE
2 V_STRING VARCHAR2(20):='24-SEP-2018';
3 V_STRING2 VARCHAR2(20):='24-09-2018';
4 V_DATE DATE;
5 V_DATE2 DATE;
6 V_TIMESTAMP TIMESTAMP;
7 V_TIMESTAMP_TZ TIMESTAMP WITH TIME ZONE;
8 V_TIMESTAMP_LTZ TIMESTAMP WITH LOCAL TIME ZONE;
9 V_YEAR INTEGER;
10 BEGIN
11 V_DATE := V_STRING;
12 V_DATE2 := TO_DATE(V_STRING2, 'DD-MM-YYYY');
13 V_TIMESTAMP := V_DATE;
14 V_TIMESTAMP_TZ := V_TIMESTAMP;
15 V_TIMESTAMP_LTZ := V_TIMESTAMP_TZ;---- Local timezone data
16 V_YEAR := EXTRACT( YEAR FROM (V_TIMESTAMP_TZ));
17 DBMS_OUTPUT.PUT_LINE( 'Character String : '||V_STRING ||CHR(10)||
18 'Date Type - Implicit Conversion : '||V_DATE ||CHR(10)||
19 'Date Type - Explicit Conversion : '||V_DATE2 ||CHR(10)||
20 'Timestamp Type : '||V_TIMESTAMP ||CHR(10)||
21 'Timestamp with timezone Type : '||V_TIMESTAMP_TZ ||CHR(10)||
22 'Timestamp with Local timezone Type : '||V_TIMESTAMP_LTZ ||CHR(10)||
23 'Timestamp Hour datetime component : '||V_YEAR ||CHR(10));
24 END;
25 /
Character String : 24-SEP-2018
Date Type - Implicit Conversion : 24-SEP-18
Date Type - Explicit Conversion : 24-SEP-18
Timestamp Type : 24-SEP-18 12.00.00.000000 AM
Timestamp with timezone Type : 24-SEP-18 12.00.00.000000 AM +05:30
Timestamp with Local timezone Type : 24-SEP-18 12.00.00.000000 AM
Timestamp Hour datetime component : 2018
PL/SQL procedure successfully completed.
47. Error Codes
This slide describes certain errors that you may encounter while creating programs
related to the topics covered in this chapter.
Purpose of this slide is to provide assistance while practicing PL/SQL.
Following are the error codes, error messages, Cause and Actions for some ORA/PLS
errors:
ORA-01481: invalid number format model
Cause: The user is attempting to either convert a number to a string via TO_CHAR or a
string
to a number via TO_NUMBER and has supplied an invalid number format model
parameter.
Action: Consult your manual.
ORA-01483: invalid length for DATE or NUMBER bind variable
Cause: A bind variable of type DATE or NUMBER is too long.
Action: Consult your manual for the maximum allowable length.
ORA-01489: result of string concatenation is too long
Cause: String concatenation result is more than the maximum size.
Action: Make sure that the result is less than the maximum size.
VIC 47
48. ORA-01858: a non-numeric character was found where a numeric was expected
Cause: The input data to be converted using a date format model was incorrect. The input data
did not
contain a number where a number was required by the format model.
Action: Fix the input data or the date format model to make sure the elements match in number
and type.
Then retry the operation.
ORA-01859: a non-alphabetic character was found where an alphabetic was expected
Cause: The input data to be converted using a date format model was incorrect.
The input data did not contain a letter where a letter was required by the format model.
Action: Fix the input data or the date format model to make sure the elements match in number
and type.
Then retry the operation.
ORA-01861: literal does not match format string
Cause: Literals in the input must be the same length as literals in the format (with the exception
of leading
whitespace). If the "FX" modifier has been toggled on, the literal must match exactly, with
no extra
whitespace. VIC 48
49. A bit of an Advice
Usage of PLS_INTEGER is recommended in intensive integer arithmetic but
if computation involves frequent conversions to and from the NUMBER type,
using NUMBER type is better.
As CAST function does not support number format models using
TO_NUMBER and TO_CHAR functions are recommended unless you are
writing 100% ANSI-compliant code as CAST is the part of ISO SQL standard.
Implicit conversions gives less control to the programmer over the code. It is
highly recommended to use explicit conversion in programming as it makes
code more efficient, eliminates ambiguity and makes the code self
documenting and easier to understand.
While writing code with datetime functions, decide carefully which current
datetime function needs to be used based on the requirement like time on
the database or current session. If you decide to use a function that returns
the time in the session time zone, be certain that you have correctly specified
your session time zone. The functions SESSIONTIMEZONE and
DBTIMEZONE will report your session and database time zones,
respectively.
VIC 49
50. Thanks for reading. We hope you have got some of what you were looking for in PL/SQL
programming fundamentals. Part 2 of this chapter will be covering user defined PL/SQL datatypes
and next chapters will be giving details of how SQL is used in PL/SQL and PLSQL based
application development with suitable examples expanding our SCHOOL MANAGEMENT
SYSTEM(SMS) further. So stay with us.
THAT’S ALL FOLKS!