IT 6 - Questions
IT 6 - Questions
IT 6 - Questions
• In the call to the function num_characters, the value returned by the function
will be
stored in the variable v_length_of_string.
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
F. Assessment:
Try It / Solve It
1. Identify valid and invalid variable declaration and initialization:
number_of_copies PLS_INTEGER;
printer_name CONSTANT VARCHAR2(10);
deliver_to VARCHAR2(10) := Johnson;
by_when DATE := SYSDATE+1;
2. Examine the following anonymous block and choose the appropriate statement.
DECLARE
fname VARCHAR2(25);
lname VARCHAR2(25) DEFAULT 'fernandez';
BEGIN
DBMS_OUTPUT.PUT_LINE(fname || ' ' || lname);
END;
A. The block will execute successfully and print ‘ fernandez’.
B. The block will give an error because the fname variable is used without
initializing.
C. The block will execute successfully and print ‘null fernandez’.
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
D. The block will give an error because you cannot use the DEFAULT keyword to
initialize a vari-able of the VARCHAR2 type.
E. The block will give an error because the FNAME variable is not declared.
3. In Application Express:
A. Create the following function:
CREATE FUNCTION num_characters (p_string IN VARCHAR2)
RETURN INTEGER AS
v_num_characters INTEGER;
BEGIN
SELECT LENGTH(p_string) INTO v_num_characters
FROM dual;
RETURN v_num_characters;
END;
B. Create and execute the following anonymous block:
DECLARE
v_length_of_string INTEGER;
BEGIN
v_length_of_string := num_characters('Oracle Corporation');
DBMS_OUTPUT.PUT_LINE(v_length_of_string);
END;
4. Write an anonymous block that uses a country name as input and prints the
highest and
lowest elevations for that country. Use the COUNTRIES table. Execute your block
three
times using Unit-ed States of America, French Republic, and Japan.
G. References:
https://academy.oracle.com/pages/programming_PLSQL_course.pdf
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
A. Introduction:
A spoken language has different parts of speech. Each part of speech (such as an
adjective, noun, and verb) is used differently and must follow rules. Similarly, a
programming
language has different parts of speech that are used differently and must follow
rules. These
parts of speech are called lexical units.
B. Objectives:
In this module, the lesson covers the following:
1. List and define the different types of lexical units available in PL/SQL
2. Describe identifiers and identify valid and invalid identifiers in PL/SQL
3. Describe and identify reserved words, delimiters, literals, and comments in
PL/SQL
C. Learning Content:
• Lexical units
• Identifiers
• Reserved words
• Delimiters
• Literals
• Comments
D. Pre-Test:
Recognizing PL/SQL Lexical Units
Vocabulary
Identify the vocabulary word for each definition below:
An explicit numeric, character string, date, or Boolean value that is not
represented by an identifier.
Symbols that have special meaning to an Oracle database.
Words that have special meaning to an Oracle database and cannot
be used as identifiers.
Describe the purpose and use of each code segment and are ignored
by PL/SQL.
Building blocks of any PL/SQL block and are sequences of characters
including letters, digits, tabs, returns, and symbols.
LESSON 2.2 – Recognizing PL/SQL Lexical Units
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
A name, up to 30 characters in length, given to a PL/SQL object.
E. Learning Activities:
Lexical Units in a PL/SQL Block
• Lexical units:
• Are the building blocks of any PL/SQL block
• Are sequences of characters including letters, digits, tabs, returns, and symbols
• Can be classified as:
- Identifiers
- Reserved words
- Delimiters
- Literals
- Comments
Identifiers
• An identifier is the name given to a PL/SQL object, including any of the
following:
• Do not be concerned if you do not know what all of the above objects are.
• You will learn about PL/SQL objects throughout this course.
Identifiers Highlighted
• Several identifiers are highlighted in the PL/SQL code shown below.
• Key: Variables Packages Procedures Functions
Identifier Properties
• Identifiers: Maximum
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
- 30 characters in length
- Must begin with a letter
- May include $ (dollar sign), _ (underscore), or # (hashtag)
- May not contain spaces
- Identifiers are NOT case sensitive
• Be sure to name your objects carefully. Ideally, the identifier name should
describe the
object and its purpose. Avoid using identifier names such as A, X, Y1, temp, etc.,
because they make your code more difficult to read.
Valid and Invalid Identifiers
• Examples of valid identifiers:
• Examples of valid identifiers:
Reserved Words
• Reserved words are words that have special meaning to the Oracle database.
• Reserved words cannot be used as identifiers in a PL/SQL program.
Partial List of Reserved Words
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
• The following is a partial list of reserved words.
• Note: For more information, refer to the “PL/SQL User’s Guide and Reference.”
Using Reserved Words
• What happens when you try to use a reserved word as an identifier in a PL/SQL
program?
Delimiters
• Delimiters are symbols that have special meaning.
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
• Simple delimiters consist of one character.
• Compound delimeters consists of two characters.
Literals
• A literal is an explicit numeric, character string, date, or Boolean value that
might be
stored in a variable.
• Literals are classified as:
- Character (also known as string literals)
- Numeric
- Boolean
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
Character Literals
• May include any printable character in the PL/SQL character set: letters,
numerals,
spaces, and symbols
• Typically defined using the VARCHAR2 data type
• Must be enclosed by character string delimiters (')
• Can be composed of zero or more characters
• Are case sensitive; therefore, PL/SQL is NOT equivalent to pl/sql
• The following are examples of character literals being assigned to variables.
• The literals are the characters between the single quotes (the character string
delimiters)
and are shown here in red text for emphasis
Numeric Literals
• Literals that represent numbers are numeric literals.
• Numeric literals can be a simple value (ex. 5, -32.5, 127634, 3.141592)
• Scientific notation also may be used(ex. 2E5, meaning 2*(10 to the power of 5).
• Typically defined using the NUMBER data type
• The following are examples of numeric literals being assigned to variables (and
one
constant).
• The literals are shown here in red text for emphasis.
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
Boolean Literals
• Values that are assigned to Boolean variables are Boolean literals.
• TRUE, FALSE, and NULL are the Boolean literals
• Note that character string delimiters are not required.
Comments
• Comments explain what a piece of code is trying to achieve.
• Well-placed comments are extremely valuable for code readability and future code
maintenance.
• Comments should describe the purpose and use of each block of code.
• It is good programming practice to comment code.
• Comments are ignored by PL/SQL.
• They make no difference to how a PL/SQL block executes or the results it
displays.
Syntax for Commenting Code
• Two ways to indicate comments in PL/SQL
• When commenting a single line, use two dashes (--)
• When commenting multiple lines, begin the comment with /* and end the comment
with
*/
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
F. Assessment:
Try It / Solve It Questions
1. Identify each of the following identifiers as valid or invalid. If invalid,
specify why.
Identifier Valid
(X)
Invalid
(X)
Why Invalid?
Today
Last name
today’s_date
number_of_days_in_february_this_
year
Isleap$year
#number
NUMBER#
Number1to7
2. Identify the reserved words in the following list.
Word Reserved? Y/N
create
make
table
seat
alter
rename
row
number
web
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
3. What kind of lexical unit (for example Reserved word, Delimiter, Literal,
Comment) is each of
the following?
Value Lexical Unit
SELECT
:=
'TEST'
FALSE
-- new process
FROM
/* select the country with the
highest elevation */
v_test
4.09
G. References:
https://academy.oracle.com/pages/programming_PLSQL_course.pdf
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
A. Introduction:
PL/SQL data types PL/SQL has two kinds of data types: scalar and composite. The
scalar types are types that store single values such as number, Boolean, character,
and
datetime whereas the composite types are types that store multiple values, for
example,
record and collection.
B. Objectives
In this module, the lesson covers the following:
• Define data type and explain why it is needed
• List and describe categories of data types
• Give examples of scalar and composite data types
C. Learning Content:
• BFILE
• BLOB
• CLOB
• Composite
• LOB
D. Pre-Test:
Identify the vocabulary word for each definition below:
Store large blocks of single-byte or fixed width multi-byte
NCHAR data in the database.
Hold values, called locators, that specify the location of large
objects (such as graphic images) that are stored out of line.
Hold a single value with no internal components.
Store large unstructured or structured binary objects.
Contain internal elements that are either scalar (record) or
composite (record and table)
Store large binary files outside of the database.
Hold values, called pointers, that point to a storage location.
A schema object with a name, attributes, and methods.
Store large blocks of character data in the database.
LESSON 2.3 – Recognizing Data Types
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
E. Learning Activities:
PL/SQL Data Types
• PL/SQL supports five categories of data type.
• A data type specifies a storage format, constraints, and a valid range of values.
indicator.
v_first_name varchar2(20) :=
‘NENA’;
Data Type Description
NUMBER Floating-point number from 1E-130 to 10E125.
NUMBER(p,s) Fixed-point number with precision p. Precision includes scale sand can
range from 1 to 38. Scale can range from –84 to 127 and determines
where rounding occurs as well as the fixed number of decimal places to
store.
NUMBER(p) Integers with maximum number of digits p(range 1-38).
PLS_INTEGE
R
Requires less storage and is faster than NUMBER.
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
• Ex.
Scalar Data Types: Date
• Date data types provide storage of dates and times.
Data Type Description
DATE Base type for dates and times. DATE values include the time of
day in seconds since midnight. The range for dates is between
1-Jan-4712 BCE and 31-Dec-9999 CE.
TIMESTAMP TIMESTAMP extends the DATE data type to store the year,
month, day, hour, minute, second, and fraction of seconds.
TIMESTAMP WITH TIME
ZONE
TIMESTAMP WITH TIME ZONE extends the TIMESTAMP
data type to include a time-zone displacement—that is, the
difference (in hours and minutes) between local time and
Coordinated Universal Time (UTC).
• Ex
Scalar Data Types: Boolean
• Use the BOOLEAN data type to store the logical values TRUE, FALSE, and NULL.
• Only logic operations are allowed on BOOLEAN variables.
• Column values cannot be fetched into a BOOLEAN variable and a table column cannot
Date Functions
• Valid date functions in PL/SQL include:
ADD_MONTHS MONTHS_BETWEEN
CURRENT_DATE ROUND
CURRENT_TIMESTAMP SYSDATE
LAST_DAY TRUNC
• This is not an exhaustive list
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
DECLARE
v_new_date DATE ;
v_num_months NUMBER := 6 ;
BEGIN
v_new_date := ADD_MONTHS (SYSDATE, v_num_months) ;
DBMS_OUTPUT.PUT_LINE(ROUND (v_new_date );
END;
DECLARE
v_no_months PLS INTEGER := 0 ;
BEGIN
v_no_months := MONTHS_BETWEEN (‘ 31-Jan-2006 ’ , ’ 31-May-2005 ’) ;
DBMS_OUTPUT.PUT_LINE(ROUND (v_no_months );
END;
Example of Date Functions
• Add months to a date:
• Calculate the number of months between two dates:
Data-Type Conversion
• In any programming language, converting one data type to another is a common
requirement.
• PL/SQL can handle such conversions with scalar data types.
• Data-type conversions can be of two types:
- Implicit conversions
- Explicit conversions
Implicit Conversions
• In implicit conversions, PL/SQL attempts to convert data types dynamically if
they are
mixed in a statement.
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
DECLARE
v_salary NUMBER (6) := 6000 ;
v_sal_increase VARCHAR2 (5) := ‘1000’ ;
v_total_salary v_salary%TYPE;
BEGIN
v_total_salary := v_salary + v_sal_increase;
DBMS_OUTPUT.PUT_LINE(ROUND (v_total_salary );
END;
• Implicit conversions can happen between many types in PL/SQL, as illustrated by
the
following chart.
DATE LONG NUMBER PLS_INTEGER VARCHAR2
DATE N / A X X
LONG N / A X
NUMBER X N / A X X
PLS_INTEGER X X N / A X
VARCHAR2 X X X X N / A
Example of implicit Conversion
• In this example, the variable v_sal_increaseis of type VARCHAR2.
• While calculating the total salary, PL/SQL first converts v_sal_increaseto NUMBER
and
then performs the operation.
• The result of the operation is the NUMBER type.
Drawbacks of Implicit Conversions
• At first glance, implicit conversions might seem useful; however, there are
several
drawbacks:
• Implicit conversions can be slower.
• When you use implicit conversions, you lose control over your program because you
are
making an assumption about how Oracle handles the data.
• If Oracle changes the conversion rules, then your code can be affected.
• Code that uses implicit conversion is harder to read and understand.
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
BEGIN
DBMS_OUTPUT.PUT_LINE (TO_CHAR (SYSDATE, ‘Month YYYY’ ) );
END;
Additional drawbacks:
• Implicit conversion rules depend upon the environment in which you are running.
- For example, the date format varies depending on the language setting and
installation type.
- Code that uses implicit conversion might not run on a different server or in a
different language.
• It is strongly recommended that you AVOID allowing SQL or PL/SQL to perform
implicit
conversions on your behalf.
• You should use conversion functions to guarantee that the right kinds of
conversions
take place.
• It is the programmer's responsibility to ensure that values can be converted.
• For instance, PL/SQL can convert the CHAR value '02-Jun-1992' to a DATE value,
but
cannot convert the CHAR value 'Yesterday' to a DATE value.
• Similarly, PL/SQL cannot convert a VARCHAR2 value containing alphabetic
characters
to a NUMBER value.
Valid? Statement
Yes v_new_date DATE := ’02-JUN-1992’ ;
No v_new_date DATE := ‘Yesterday’;
Yes v_my_number NUMBER := ‘123’ ;
No v_my_number NUMBER := ‘abc’;
Explicit Conversions
• Explicit conversions convert values from one data type to another by using built-
in
functions.
• Examples of conversion functions include:
TO_NUMBER ( ) ROWIDTONCHAR ( )
TO_CHAR ( ) HEXTORAW ( )
TO_CLOB ( ) RAWTOHEX ( )
CHARTOROWID ( ) RAWTONHEX ( )
ROWIDRTOCHAR ( ) TO_DATE ( )
Examples of Explicit Conversions
• TO_CHAR
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
BEGIN
DBMS_OUTPUT.PUT_LINE (TO_DATE (‘April-1999’ , ‘Month YYYY’ ) );
END;
DECLARE
v_a VARCHAR2 (10) := ‘-123456’ ;
v_a VARCHAR2 (10) := ‘+987654’ ;
v_c PLS_INTEGER
BEGIN
v_c := TO_NUMBER (v_a) + TO_NUMBER (v_b) ;
DBMS_OUTPUT.PUT_LINE ( v_c );
END;
v_date_of_joining DATE := ’02—Feb-2014’ ;
v_date_of_joining DATE := ‘February 02, 2014’ ;
v_date_of_joining DATE := TO_DATE ( ‘February 02, 2014’ , ‘Month DD, YYYY’) ;
• TO_DATE
• TO_NUMBER
• Note that the DBMS_OUTPUT.PUT_LINEprocedure expects an argument with a
charactertype such as VARCHAR2.
• Variable v_c is a number, therefore we should explicitly
code:DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_c));
Data Type Conversion Samples
• Example #1
• Example #2
• Example #3
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
v_loop_count := v_loop_count + 1;
v_good_sal := v_sal_BETWEEN 50000 and 150000 ;
v_valid := (v_empno IS NOT NULL) ;
Operators in PL/SQL
• The operations within an expression are performed in a particular order depending
on
their precedence (priority).
Same as
In SQL
• The following table shows the default order of operations from high priority to
low
priority:
Operator Operation
** Exponentiation
+, - Identity, negation
*, / Multiplication, division
+, -, | | Addition, subtraction, concatenation
=, <, >, <=, >=, <>, !=, ~=, ^=, IS, NULL, LIKE,
BETWEEN, IN
Comparison
NOT Logical negation
AND Conjunction
OR Inclusion
• Increment the counter for the loop.
• Set the value of Boolean flag.
• Validate whether an employee number contains a value.
• Logical
• Arithmetic
• Concatenation
• Parentheses to control the order
of operations
• Exponential operator (**)
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
F. Assessment:
1. Examine the following code and then answer the questions.
DECLARE
x VARCHAR2(20);
BEGIN
x := '123' + '456' ;
DBMS_OUTPUT.PUT_LINE(x);
END;
A. What do you think the output will be when you run the above code?
B. Now, run the code. What is the output?
C. In your own words, describe what happened when you ran the code. Did any
implicit
conversions take place?
2. Write an anonymous PL/SQL block that assigns the programmer’s full name to a
variable,
and then displays the number of characters in the name.
3. Write an anonymous PL/SQL block that uses today's date and outputs it in the
format of
‘Month dd, yyyy’. Store the date in a DATE variable called my_date. Create another
variable
of the DATE type called v_last_day. Assign the last day of this month to
v_last_day. Display
the value of v_last_day.
4. Modify the program created in question 3 to add 45 days to today’s date and then
calculate
and display the number of months between the two dates.
5. Examine the following code and then answer the questions.
DECLARE
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
x NUMBER(6);
BEGIN
x := 5 + 3 * 2 ;
DBMS_OUTPUT.PUT_LINE(x);
END;
A. What do you think the output will be when you run the above code?
B. Now run the code. What is the output?
C. In your own words, explain the results.
6. Examine the following code and then answer the question.
DECLARE
v_number NUMBER;
v_boolean BOOLEAN;
BEGIN
v_number := 25;
v_boolean := NOT(v_number > 30);
END;
What value is assigned to v_boolean?
7. List two drawbacks to relying on implicit data type conversions.
G. References:
https://academy.oracle.com/pages/programming_PLSQL_course.pdf
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
A. Introduction:
A PL/SQL block contains a declare section and a code section. A block can contain
other
blocks and these blocks are termed nested blocks. A nested block may have an
optional
declare and exception section. A nested block is seen as a single statement to the
outer
block. A variable defined in the declare section of a block can be seen by all the
statements
in the block to include the nested blocks. This is referred to as the variable's
scope.
B. Objectives:
In this module, the lesson covers the following:
1. Understand the scope and visibility of variables
2. Write nested blocks and qualify variables with labels
3. Describe the rules for variable scope when a variable is nested in a block
4. Recognize a variable scope issue when a variable is used in nested blocks
5. Qualify a variable nested in a block with a label
C. Learning Content:
• Block label
• Variable scope
• Variable visibility
D. Pre-Test:
Identify the vocabulary word for each definition below:
A name given to a block of code which allows access
to the variables that have scope, but are not visible.
Consists of all the blocks in which the variable is either local
(the declaring block) or global (nested blocks within the
declaring block).
The portion of the program where the variable can be accessed
without using a qualifier.
LESSON 2.6 – Nested Blocks and Variable Scope
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
E. Learning Activities:
Nested Blocks
• PL/SQL is a block-structured language.
• The basic units (procedures, functions, and anonymous blocks) are logical blocks,
which
can contain any number of nested sub-blocks.
• Each logical block corresponds to a problem to be solved.
Nested Blocks Illustrated
• Nested blocks are blocks of code placed within other blocks of code.
• There is an outer block and an inner block.
• You can nest blocks within blocks as many times as you need to; there is no
practical
limit to the depth of nesting Oracle allows.
Nested Block Example
The example shown in the slide has an outer (parent) block (illustrated in blue
text) and a
nested (child) block (illustrated in red text).
The variable v_outer_variable is declared in the outer block and the variable
v_inner_variable is
declared in the inner block.
DECLARE
v_outer_variable VARCHAR2(20):='GLOBAL
VARIABLE';
BEGIN
DECLARE
v_inner_variable VARCHAR2(20):='LOCAL
VARIABLE';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_inner_variable);
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
Variable Scope
• The scope of a variable is the block or blocks in which the variable is
accessible, that is,
where it can be used.
• In PL/SQL, a variable’s scope is the block in which it is declared plus all
blocks nested
within the declaring block.
• What are the scopes of the two variables declared in this example?
Variable Scope Example
• Examine the following code.
• What is the scope of each of the variables?
Local and Global Variables
• Variables declared in a PL/SQL block are considered local to that block and
global to all
blocks nested within it.
• V_outer_variable is local to the outer block but global to the inner block.
DECLARE
v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE';
BEGIN
DECLARE
v_inner_variable VARCHAR2(20):='LOCAL VARIABLE';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_inner_variable);
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
BEGIN
DBMS_OUTPUT.PUT_LINE('Father''sName: '||v_father_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
DBMS_OUTPUT.PUT_LINE('Child''sName: '||v_child_name);
END;
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
END;
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
Local and Global Variables
• When you access this variable in the inner block, PL/SQL first looks for a local
variable
in the inner block with that name.
• If there are no similarly named variables, PL/SQL looks for the variable in the
outer
block.
• The v_inner_variable variable is local to the inner block and is not global
because the
inner block does not have any nested blocks.
• This variable can be accessed only within the inner block.
DECLARE
v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE';
BEGIN
DECLARE
v_inner_variable VARCHAR2(20):='LOCAL VARIABLE';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_inner_variable);
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DECLARE
v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE';
BEGIN
DECLARE
v_inner_variable VARCHAR2(20):='LOCAL VARIABLE';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_inner_variable);
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DECLARE
v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE';
BEGIN
DECLARE
v_inner_variable VARCHAR2(20):='LOCAL VARIABLE';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_inner_variable);
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
• If PL/SQL does not find the variable declared locally, it looks upward in the
declarative
section of the parent blocks.
• PL/SQL does not look downward into the child blocks.
Variable Scope Accessible to Outer Block
• The variables v_father_name and v_date_of_birth are declared in the outer block.
• They are local to the outer block and global to the inner block.
• Their scope includes both blocks.
• The variable v_child_name is declared in the inner (nested) block.
• This variable is accessible only within the inner block and is not accessible in
the outer
block.
DECLARE
v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE';
BEGIN
DECLARE
v_inner_variable VARCHAR2(20):='LOCAL VARIABLE';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_inner_variable);
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
...
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
...
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
A Scoping Example
• Why this code not work correctly
A Second Scoping Example
• Will this code work correctly? Why or why not?
DECLARE
v_first_name VARCHAR2(20);
BEGIN
DECLARE
v_last_name VARCHAR2(20);
BEGIN
v_first_name:= 'Carmen';
v_last_name:= 'Miranda';
DBMS_OUTPUT.PUT_LINE
(v_first_name|| ' '|| v_last_name);
END;
DBMS_OUTPUT.PUT_LINE
(v_first_name|| ' '|| v_last_name);
END;
DECLARE
v_first_name VARCHAR2(20);
v_last_name VARCHAR2(20);
BEGIN
BEGIN
v_first_name:= 'Carmen';
v_last_name:= 'Miranda';
DBMS_OUTPUT.PUT_LINE
(v_first_name|| ' '|| v_last_name);
END;
DBMS_OUTPUT.PUT_LINE
(v_first_name|| ' '|| v_last_name);
END;
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
Three Level of Nested Blocks
• What is the scope of each of these variables?
Variable Naming
• You cannot declare two variables with the same name in the sameblock.
• However, you can declare variables with the same name in two different blocks
when
one block is nested within the other block.
• The two items represented by the same name are distinct, and any change in one
does
not affect the other.
Example of Variable Naming
• Are the following declarations valid?
DECLARE -- outer block
v_outervar VARCHAR2(20);
BEGIN
DECLARE --middle block
v_middlevarVARCHAR2(20);
BEGIN
BEGIN --inner block
v_outervar := 'Joachim';
v_middlevar := 'Chang';
END;
END;
END;
DECLARE --outer block
v_myvar VARCHAR2(20);
BEGIN
DECLARE --inner block
v_myvar VARCHAR2(15);
BEGIN
...
END;
END;
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
Variable Visibility
• What if the same name is used for two variables, one in each of the blocks?
• In this example, the variable v_date_of_birth is declared twice.
• The visibility of a variable is the portion of the program where the variable can
be
accessed without using a qualifier.
• What is the visibility of each of the variables?
• The v_date_of_birth variable declared in the outer block has scope even in the
inner
block.
• This variable is visible in the outer block.
• However, it is not visible in the inner block because the inner block has a local
variable
with the same name.
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
BEGIN
DBMS_OUTPUT.PUT_LINE('Date of Birth:' ||
v_date_of_birth);
...
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
BEGIN
DBMS_OUTPUT.PUT_LINE('Father''sName: ' || v_father_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: ' || v_date_of_birth);
DBMS_OUTPUT.PUT_LINE('Child''sName: ' || v_child_name);
END;
DBMS_OUTPUT.PUT_LINE('Date of Birth: ' || v_date_of_birth);
END;
1
2
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
• The v_father_name variable is visible in the inner and outer blocks.
• The v_child_name variable is visible only in the inner block.
• What if you want to reference the outer block’s v_date_of_birth within the inner
block?
Qualifying an Identifier
• A qualifier is a label given to a block.
• You can use this qualifier to access the variables that have scope but are not
visible.
• The outer block below is labeled <<outer>>.
• Each nested inner block also can be labeled.
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
...
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
...
<<outer>>
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
...
IT 6 – ADVANCE DATABASE SYSTEMS Module 2
• Using the outer label to qualify the v_date_of_birth identifier, you can now
print the
father’s date of birth using code in the inner block.
F. Assessment:
1. Evaluate the PL/SQL block below and determine the value of each of the following
variables
according to the rules of scoping.
DECLARE
Weight NUMBER(3) := 600;
Message VARCHAR2(255) := 'Product 10012';
BEGIN
DECLARE
weight NUMBER(3) := 1;
message VARCHAR2(255) := 'Product 11001';
new_locn VARCHAR2(50) := 'Europe';
BEGIN
weight := weight + 1;
new_locn := 'Western ' || new_locn;
<<outer>>
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_nameVARCHAR2(20):='Mike';
v_date_of_birthDATE:='12-Dec-2002';
BEGIN
DBMS_OUTPUT.PUT_LINE('Father''sName: ' || v_father_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: ' || outer.v_date_of_birth);