You are on page 1of 16

FILAMER CHRISTIAN UNIVERSITY

COLLEGE OF COMPUTER STUDY


Roxas City

ADVANCE DATABASE SYSTEM

BARRIENTOS,FAITH V. BSIT3-C

MODULE 2.1
D. Pre-Test:
Using Variables in PL/SQL Vocabulary Identify the vocabulary word for
each definition below:

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 SUB PROGRAM.

B. Variables can be assigned values in the DECLARATIVE 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:
VALID number_of_copies PLS_INTEGER;
INVALID printer_name CONSTANT VARCHAR2(10);
INVALID deliver_to VARCHAR2(10) := Johnson;
VALID 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’.
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
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_counrty_name
||’ is: ‘||v_lowest_elevation);
DBMS_OUTPUT.PUT_LINE(‘The highest elevation for ‘||v_country_name
||’ is: ‘||v_highest_elevation);
END;

MODULE 2.2

D. Pre-Test: Recognizing PL/SQL Lexical Units


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.

DELIMITER 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 INVALI Why Invalid?


(X) D
(X)

Today X

Last Name
today’s_date

number_of_days_in_februar
y_this_ year

Isleap$year

#number

NUMBER#

Number1to7

2. Identify the reserved words in the following list.

Word Reserved? Y/N

create Y

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 RESERVED WORD

:= DELIMITER

'TEST' LITERAL

FALSE LITERAL
-- new process COMMENT

FROM RESERVED WORD

/* select the country COMMENT


with the highest
elevation*/

v_test IDENTIFIER

4.09 LITERAL

MODULE 2.3

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

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.

Compuesto 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, Compuesto

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 Compuesto

PLS_INTEGER Scalar

LONG Scalar

TABLE Compuesto

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'

A movie LOB BFILE

A sound byte LOB BFILE OR


BLOB

FALSE Scalar BLOB

MODULE 2.4

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/INVALI
D

A number_of_students PLS_INTEGER; VALID

B STUDENT_NAME VARCHAR2(10) = Johnson; INVALID

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 it is incorrect since the Johnson value is wrong it


must be
STUDENT_NAME VARCHAR2 (10): = 'Johnson';
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 ('The number of students is:
'||number_of_students||'.');
DBMS_OUTPUT.PUT_LINE ('The name of the students is: '||student_name||'.');
DBMS_OUTPUT.PUT_LINE ('The number of students per class is:
'||stu_per_class||'.');
DBMS_OUTPUT.PUT_LINE ('Tomorrows date is: '||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
country_name VARCHAR2 (50);
median_age NUMBER(6,2);
BEGIN
SELECT country_name, median_age INTO country_name, median_age
FROM wf_countries
WHERE country_name = 'United States of America';
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.
country_name wf_countries.country_name%TYPE;
median_age wf_countries.median_age%TYPE;

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?

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;
BEGIN
tomorrow := today + 1;
DBMS_OUTPUT.PUT_LINE('Hello World');
DBMS_OUTPUT.PUT_LINE(today);
DBMS_OUTPUT.PUT_LINE(tomorrow);
END;

MODULE 2.5

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

EXPLICIT CONVERSION Converts values from one data type to another by


using built-in functions.

IMPLICIT CONVERSION Converts data types dynamically if they are


mixed in a statement.

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?
123456 OR ERROR
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
v_name VARCHAR2(50) :='<Enter your full name>';
v_length_name PLS_INTEGER;
BEGIN
v_length_name := LENGTH(v_name);
DBMS_OUTPUT.PUT_LINE(v_length_name);
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;
BEGIN
DBMS_OUTPUT.PUT_LINE(TO_CHAR (my_date, 'Month dd, yyyy'));
v_last_day := LAST_DAY(my_date);
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;
new_date DATE;
v_months_between NUMBER;
BEGIN
new_date := my_date + 45;
v_months_between := MONTHS_BETWEEN(new_date,my_date);
DBMS_OUTPUT.PUT_LINE(v_months_between);
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.

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

MODULE 2.6

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

BLOCK LABEL 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


VISIBILITY variable can be accessed 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'; 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 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_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 = 100;
--inner_block 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(outer_block.v_employee_id|| ‘ is a '||
outer_block.v_job);
END;
DBMS_OUTPUT.PUT_LINE(v_employee_id||‘ is a '||v_job); END;

MODULE 2.7

D. Pre-Test: In your own words, what are the good programming


practices.

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

DECLARE
v_country_name wf_countries.country_name%TYPE;
v_number NUMBER(4);
BEGIN
/* Read the country name of Barbados from the database
and assign it to the first variable */
SELECT country_name INTO v_country_name
FROM wf_countries
WHERE country_id = 1246;
v_number := TO_NUMBER('1234'); -- or v_number := 1234;
v_number := v_number * 2;
DBMS_OUTPUT.PUT_LINE(v_country_name);
END;

You might also like