0% found this document useful (0 votes)
86 views21 pages

LESSON 2.1 - Using Variables in PL/SQL: Page - 1

This document provides an overview of using variables and data types in PL/SQL. It defines key terms like variables, parameters, literals, and data types. It also provides examples of declaring and initializing variables, passing variables as parameters, and identifying valid and invalid variable usage. The document tests the understanding of PL/SQL lexical units like reserved words, delimiters, literals, identifiers, comments, and different data type categories and examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views21 pages

LESSON 2.1 - Using Variables in PL/SQL: Page - 1

This document provides an overview of using variables and data types in PL/SQL. It defines key terms like variables, parameters, literals, and data types. It also provides examples of declaring and initializing variables, passing variables as parameters, and identifying valid and invalid variable usage. The document tests the understanding of PL/SQL lexical units like reserved words, delimiters, literals, identifiers, comments, and different data type categories and examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

IT 6- Advance Database Systems

MODULE 2

LESSON 2.1 – Using Variables in PL/SQL


D. Pre-Test:
Variable Used for storage of data and manipulation of
stored values.
Parameters Values passed to a program by a user or by another
program to customize the program.

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;

LESSON 2.2 – Recognizing PL/SQL Lexical Units

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

2. Identify the reserved words in the following list.


Word Reserved? Y/N
create Y
Page | 4
make N
table Y
seat N
alter Y
rename Y
row Y
number Y
web N

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

LESSON 2.3 – Recognizing Data Types


D. Pre-Test:

Identify the vocabulary word for each definition below:

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.

Scalar Hold a single value with no internal components.

BLOB Store large unstructured or structured binary objects.

Composite Contain internal elements that are either scalar (record) or composite (record
and table)

BFILE Store large binary files outside of the database.

Reference Hold values, called pointers, that point to a storage location.

Object A schema object with a name, attributes, and methods.

CLOB Store large blocks of character data in the database.

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.

2.Identify the three data type categories covered in this course.


- LOB, Scalar, Composite
Page | 6
3.Identify three data types covered in the Database Programming with SQL course.
- Number, Date, Varchar2

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.

Data Type Data Type Category

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.

Value Data Type Data Type


Category

‘Switzerland’ Scalar VARCHAR2

Text of a resume Scalar VARCHAR2

100.20 Scalar Number

A picture LOB BLOB

1053 Scalar Number

11-Jun-2016 Scalar Date

‘Computer science is the science of the 21st


century.’
Scalar Varchar2

Index Last_name

1 'Newman'
Composite Table
2 'Raman'

3 'Han'

Page | 8
A movie LOB BFILE

A sound byte LOB BFILE OR


BLOB

FALSE Scalar BLOB

LESSON 2.4 – Using Scalar Data Types


D. Pre-Test:
Identify the vocabulary word for each definition below:

BOOLEAN A data type that stores one of the three possible values
used for logical calculations: TRUE, FALSE, or NULL.

%TYPE Attribute used to declare a variable according to another


previously declared variable or database column.

F. Assessment:
Declarations:
A. Which of the following variable declarations are valid?

Declaration VALID/INVALID

A number_of_students PLS_INTEGER; VALID

B STUDENT_NAME VARCHAR2(10) = Johnson; INVALID

Page | 9
C stu_per_class CONSTANT NUMBER; INVALID

D tomorrow DATE := SYSDATE+1; VALID

B. For the invalid declarations above, describe why they are invalid.

- In statement b is incorrect because string literals should be in single quotation marks


('Johnson') and := is used to assign values, not =

- 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;

R = Executes correctly, but it is recommended to rename the


variables since it can be confused or not differentiated about the variables and the
name of the table fields in SQL. The names of the variables would be of this
way:
- v_country_name, v_media_age

3. Change the declarations in #2 above so they use the %TYPE attribute.


DECLARE
country_namecountries.country_name%TYPE := ’Japan’;
median_agecountries.median_age%TYPE;
BEGIN
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.

5. Create the following anonymous block:

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;

LESSON 2.5 – Writing PL/SQL Executable Statements


D. Pre-Test:
Identify the vocabulary word for each definition below:

EXPLICIT Converts values from one data type to another by using built-in
CONVERSION functions.

IMPLICIT Converts data types dynamically if they are mixed in a statement.


CONVERSION

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

B. Now, run the code. What is the output?


579

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;

5. Examine the following code and then answer the questions.


DECLARE
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?
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;

What value is assigned to v_boolean?


TRUE
7. List two drawbacks to relying on implicit data type conversions.
1. IMPLIED CONVERSIONS MAY BE SLOWER.
2. CODE USING IMPLIED CONVERSION IS MORE DIFFICULT TO READ AND
UNDERSTAND

Page | 16
LESSON 2.6 – Nested Blocks and Variable Scope
D. Pre-Test:
Identify the vocabulary word for each definition below:

QUALIFIER A name given to a block of code which allows access to the


variables that have scope, but are not visible.

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

DECLARE weight NUMBER(3) := 1;


Message VARCHAR2(255) := 'Product 11001';
new_locn VARCHAR2(50) := 'Europe';
BEGIN
weight := weight + 1;
new_locn:= 'Western ' || new_locn;
-- Position 1 --
END;
weight := weight + 1;
message := message || ' is in stock';

-- Position 2
-- END;

A. The value of weight at position 1 is: 2


B. The value of new_locn at position 1 is: Western Europe
C. The value of weight at position 2 is: 601
D. The value of message at position 2 is: Product 10012 is in stock
E. The value of new_locn at position 2 is: Can't be out of range of the block

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;

LESSON 2.7 – Good Programming Practices

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

You might also like