LESSON 2.1 - Using Variables in PL/SQL: Page - 1
LESSON 2.1 - Using Variables in PL/SQL: Page - 1
MODULE 2
Try It / Solve It
1. Fill in the blanks.
A. Variables can be assigned to the output of a ____String_____ PL/SQL subprogram.
B. Variables can be assigned values in the _____Declaration________ section of a PL/SQL block.
C. Variables can be passed as ______Parameters_________ to subprograms.
F. Assessment:
Try It / Solve It
1. Identify valid and invalid variable declaration and initialization:
number_of_copies PLS_INTEGER; VALID
printer_name CONSTANT VARCHAR2(10); INVALID
deliver_to VARCHAR2(10) := Johnson; INVALID
by_when DATE := SYSDATE+1; VALID
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;
Page | 1
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’.
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.
DECLARE
Page | 2
v_country_name varchar2(50):= "United States of America';
v_lowest_elevation number(6);
v_highest_elevation number(6);
BEGIN
SELECT lowest_elevation, highest_elevation
INTO v_lowest_elevation, v_highest_elevation
FROM wf_countries
WHERE country_name = v_country name;
DBMS_OUTPUT.PUT_LINE(‘The lowest elevation for ‘||v_country_name||‘ is: ‘||
v_lowest_elevation);
DBMS OUTPUT.PUT_LINE(‘The highest elevation for ‘||v_country_name ||' is:
‘||v_highest_elevation);
END;
D. Pre-Test:
Recognizing PL/SQL Lexical Units
Page | 3
Vocabulary
Identify the vocabulary word for each definition below
Literals An explicit numeric, character string, date, or
Boolean value that is not represented by an
identifier.
Delimiters Symbols that have special meaning to an Oracle
database.
Reserved words Words that have special meaning to an Oracle
database and cannot be used as identifiers.
Comments Describe the purpose and use of each code
segment and are ignored by PL/SQL.
Lexical units Building blocks of any PL/SQL block and are
sequences of characters including letters, digits,
tabs, returns, and symbols.
Identifiers A name, up to 30 characters in length, given to a
PL/SQL object.
F. Assessment:
Try It / Solve It Questions
1. Identify each of the following identifiers as valid or invalid. If invalid, specify why.
Identifier Valid Invalid Why invalid?
(X) (X)
Today X
Last name X Contains a space
today’s_date X Contains quote
number_of_days_in_february_this_ X Contains more that
year 30 characters
Isleap$year X
#number X Must start with a
letter not with #
NUMBER# X
Number1to7 X
3. What kind of lexical unit (for example Reserved word, Delimiter, Literal, Comment) is each of
the following?
Value Lexical Unit
SELECT Reserve word
:= Delimiter
'TEST' Literal
FALSE Literal
-- new process Comment
FROM Reserve word
/* select the country with the highest elevation*/ Comment
v_test Identificator
4.09 Literal
Page | 5
NCLOB Store large blocks of single-byte or fixed width multi-byte NCHAR data in the
database.
LOB Hold values, called locators, that specify the location of large objects (such as
graphic images) that are stored out of line.
Composite Contain internal elements that are either scalar (record) or composite (record
and table)
Try It / Solve It
1.In your own words, describe what a data type is and explain why it is important.
- PL / SQL uses special data types to keep track of the different types of data that it processes. These
data types define how the data is physically stored, what the restrictions are for the data, and finally
what is the valid range of values for the data.
4.What data type can be used in PL/SQL, but can’t be used to define a table column?
- Boolean
5.Which data type indicates a large data object that is stored outside of the database?
- BFILE
6.Identify the data type category (LOB, Scalar, or Composite) for each data type. Each category
may be used more than once.
CLOB LOB
VARCHAR2 Scalar
BLOB LOB
NUMBER Scalar
BFILE LOB
TIMESTAMP Scalar
NCLOB LOB
RECORD Composite
PLS_INTEGER Scalar
LONG Scalar
Page | 7
TABLE Composite
BOOLEAN Scalar
7.Enter the data type category and the data type for each value. The first one has been done
for you.
Index Last_name
1 'Newman'
Composite Table
2 'Raman'
3 'Han'
Page | 8
A movie LOB BFILE
BOOLEAN A data type that stores one of the three possible values
used for logical calculations: TRUE, FALSE, or NULL.
F. Assessment:
Declarations:
A. Which of the following variable declarations are valid?
Declaration VALID/INVALID
Page | 9
C stu_per_class CONSTANT NUMBER; INVALID
B. For the invalid declarations above, describe why they are invalid.
- In the declaration c it will mark error since as it is a constant it is mandatory assign it a value
or add a default so that it can compile correctly.
C. Write an anonymous block in which you declare and print (on the screen) each of the variables
in 1A above, correcting the invalid declarations and adding information as needed.
DECLARE
number_of_students PLS_INTEGER :=30;
STUDENT_NAME VARCHAR2(10) := 'Johnson';
stu_per_class CONSTANT NUMBER :=1;
tomorrow DATE :=SYSDATE+1;
BEGIN
DBMS_OUTPUT.PUT_LINE('Linea A):'||number_of_students);
DBMS_OUTPUT.PUT_LINE('Linea B):'||STUDENT_NAME);
DBMS_OUTPUT.PUT_LINE('Linea C):'||stu_per_class);
DBMS_OUTPUT.PUT_LINE('Linea D):'||tomorrow); END;
2. Evaluate the variables in the following code. Answer the following questions about each
variable. Is it named well? Why or why not? If it is not named well, what would be a better name
and why?
DECLARE
Page | 10
country_nameVARCHAR2(50);
median_age NUMBER(6, 2);
BEGIN
SELECT country_name, median_age INTO country_name, median_age
FROM countries
WHERE country_name = 'Japan';
DBMS_OUTPUT.PUT_LINE('The median age in '|| country_name || ' is '
|| median_age || '.');
END;
4. In your own words, describe why using the %TYPE attribute is better than hard-coding data
types. Can you explain how you could run into problems in the future by hard-coding the data
types of the country_name and median_age variables in question 2?
Page | 11
The use of the% TYPE attribute, it will only have the type of data obtained in the field of the
table that was assigned but not the value. So at the time of compile the code you will need to put the
value to see it.
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World');
END;
A. Add a declarative section to this PL/SQL block. In the declarative section, declare the following
variables:
• A variable named TODAY of datatype DATE. Initialize TODAY with SYSDATE.
• A variable named TOMORROW with the same datatype as TODAY. Use the %TYPE attribute to
declare this variable.
DECLARE
TODAY DATE := SYSDATE;
TOMORROW TODAY%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World');
END;
B. In the executable section, initialize the TOMORROW variable with an expression that calculates
tomorrow’s date (add 1 to the value in TODAY). Print the value of TODAY and TOMORROW after
printing ‘Hello World’.
DECLARE
TODAY DATE := SYSDATE;
TOMORROW TODAY%TYPE :=SYSDATE+1;
Page | 12
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Hello World’);
DBMS_OUTPUT.PUT_LINE(TODAY);
DBMS_OUTPUT.PUT_LINE(‘TOMORROW);
END;
EXPLICIT Converts values from one data type to another by using built-in
CONVERSION functions.
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;
Page | 13
A. What do you think the output will be when you run the above code?
123456
C. In your own words, describe what happened when you ran the code. Did any implicit
conversions take place?
- WHEN THE ADD OPERATOR WAS USED, THE NUMBERS STILL
DATA TYPE VARCHAR2 THESE WERE ADDED.
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.
DECLARE
name VARCHAR2(30):= 'Airon Ness Gidor';
caracteres NUMBER;
BEGIN
caracteres:=length(name);
DBMS_OUTPUT.PUT_LINE(caracteres);
END;
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.
DECLARE
my_date DATE:=SYSDATE;
v_last_day DATE:=LAST_DAY(SYSDATE);
BEGIN
Page | 14
DBMS_OUTPUT.PUT_LINE(TO_CHAR(my_date,'MON-DD-YYYY'));
DBMS_OUTPUT.PUT_LINE(v_last_day);
END;
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.
DECLARE
my_date DATE:=SYSDATE+45;
v_last_day DATE:=LAST_DAY(SYSDATE);
BEGIN
DBMS_OUTPUT.PUT_LINE('Meses entre '||v_last_day||' y '||my_date||' :
'||ABS(TRUNC(MONTHS_BETWEEN(v_last_day,my_date))));
END;
A. What do you think the output will be when you run the above code?
11
B. Now run the code. What is the output?
11
C. In your own words, explain the results.
WHEN PERFORMING THE ARITHMETIC OPERATIONS, THEY ARE CARRIED OUT
ACCORDING TO THE PRIORITY AMONG THE ARITHMETIC OPERATORS.
Page | 15
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;
Page | 16
LESSON 2.6 – Nested Blocks and Variable Scope
D. Pre-Test:
Identify the vocabulary word for each definition below:
VARIABLE SCOPE Consists of all the blocks in which the variable is either local
(the declaring block) or global (nested blocks within the
declaring block) .
VARIABLE The portion of the program where the variable can be accessed
VISIBILITY without using a qualifier.
F. Assessment:
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';
Page | 17
BEGIN
-- Position 2
-- END;
2. Enter and run the following PL/SQL block, which contains a nested block. Look at the output
and answer the questions.
DECLARE
v_employee_id employees.employee_id%TYPE;
v_job employees.job_id%TYPE;
BEGIN
SELECT employee_id, job_id INTO v_employee_id, v_job
Page | 18
FROM employees
WHERE employee_id = 100;
DECLARE
v_employee_id employees.employee_id%TYPE;
v_job employees.job_id%TYPE;
BEGIN
SELECT employee_id, job_id INTO v_employee_id, v_job
FROM employees
WHERE employee_id = 103;
DBMS_OUTPUT.PUT_LINE(v_employee_id || ' is a(n) ' || v_job);
END;
DBMS_OUTPUT.PUT_LINE(v_employee_id || ' is a(n) ' || v_job);
END;
A. Why does the inner block display the job_id of employee 103, not employee 100?
Because the declaration of the inner block has more hierarchy than the outer block.
B. Why does the outer block display the job_id of employee 100, not employee 103?
Because the declaration of the inner block cannot be taken by the outer block
C. Modify the code to display the details of employee 100 in the inner block. Use block labels.
--outer_block DECLARE
v_employee_idemployees.employee_id%TYPE; v_jobemployees.job_id%TYPE;
BEGIN
SELECT employee_id, job_id INTO v_employee_id, v_job FROM employees
WHERE employee_id = 100;
--inner_block DECLARE
v_employee_idemployees.employee_id%TYPE; v_jobemployees.job_id%TYPE;
Page | 19
BEGIN
SELECT employee_id, job_id INTO v_employee_id, v_job FROM employees
WHERE employee_id = 103; DBMS_OUTPUT.PUT_LINE(outer_block.v_employee_id|| ‘ is a '||
outer_block.v_job);
END;
DBMS_OUTPUT.PUT_LINE(v_employee_id||‘ is a '||v_job); END;
D. Pre-Test: In your own words, what are the good programming practices.
Use meaningful identifiers when declaring variables, constants, and parameters. Declare one
variable or constant identifier per line for better readability and code maintenance. Documenting code
with comments. Comments assist in future maintenance or modification by helping other programmers
know what the original programmer intended by the code written and the naming of identifiers should be
clear, consistent, and unambiguous.
Try It / Solve It
1. Enter and run the following PL/SQL block. It will execute correctly if you have entered it
correctly, but it contains some examples of bad programming practices.
A. Modify the block to use good programming practices, and re-run the block.
B. Your modified block should contain examples of the following good programming practices:
explicit data type conversions, meaningful and consistent variable names, use of %TYPE, upper
and lowercase conventions, single and multi-line comments, and clear indentation.
DECLARE
myvar1 VARCHAR2(20);
Page | 20
myvar2 number(4);
BEGIN
SELECT country_name INTO myvar1 FROM
countries WHERE country_id = 421; myvar2 :=
'1234';
MYVAR2 := myvar2 * 2;
DBMS_OUTPUT.PUT_LINE(myvar1);
End;
Page | 21