Vous êtes sur la page 1sur 16

Section 1 Lesson 1: Introduction to PL/SQL

Vocabulary
Identify the vocabulary word for each definition below:
PL/SQL

Oracle Corporations standard procedural language for relational


databases which allows basic program logic and control flow to be
combined with SQL statements

Try It / Solve It
1. Circle the programming language meeting the criteria
Criteria
Language
3GL
PL/SQL
4GL
PL/SQL
Is proprietary to Oracle Corporation
PL/SQL
Nonprocedural
PL/SQL
Procedural
PL/SQL
Is ANSI-compliant
PL/SQL

SQL
SQL
SQL
SQL
SQL
SQL

2. In your own words, describe why a procedural language like PL/SQL is needed.
Allows basic program logic and control flow to be combined with SQL statements. It can be used only with
3. Define a procedural construct.
an Oracle database or
You use PL/SQL to write the procedural code, and embed SQL data-accessing statements
within the
tool
4. List some examples of procedural constructs in PL/SQL.

Variables, constants, and types, Control structures, such as conditional statements and loops

5. In the following code, identify and circle examples of these procedural constructs:
variable, conditional control, SQL statement

DECLARE
v_first_name varchar2(40);
v_last_name varchar2(40);
v_first_letter varchar2(1);
BEGIN
SELECT first_name, last_name into v_first_name, v_last_name
FROM students
WHERE student_id=105;
v_first_letter := get_first_letter(last_name);
IF 'N' > 'v_first_letter' THEN
DBMS_OUTPUT.PUT_LINE('The last name for: '||first_name||' '||last_name||' is
between A and M');
ELSE
DBMS_OUTPUT.PUT_LINE('The last name for: '||first_name||' '||last_name||' is
between N and Z');
END IF;
END;
Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

Section 1 Lesson 2: Benefits of PL/SQL


Vocabulary
Identify the vocabulary word for each definition below:

Portability

The ability for PL/SQL programs to run anywhere an Oracle


server runs.
The basic unit of PL/SQL programs- also known as modules.

Modularized Program Development

Exception Handling

An error that occurs in the database or in a users program


during runtime.

Try It / Solve It You can share blocks with other programmers to speed up development time
1. Why is it more efficient to combine SQL statements into PL/SQL blocks?
2. Why is it beneficial to use PL/SQL with an Oracle database? List at least three reasons.

You can group logically related statements within blocks.You can nest blocks inside other blocks to build pwf prg.

3. How is PL/SQL different from C and Java? List three differences.

Requires Oracle database or tool; Performance against an Oracle database; Ease of learning
4. List three examples of what you can build with PL/SQL code.
You can write PL/SQL code to manage application data or to manage the Oracle database itself. For example, you can write code for
updating data (DML), creating data (DDL), generating reports, managing security, and so on.
Using the Web Application Toolkit, you can create database-centric web applications written entirely or partially in PL/SQL.
Using a Web browser you can develop web applications that include PL/SQL.
1.The application can send the entire block to the database instead of sending the SQL statements one at a time. This significantly
reduces the number of database calls (consider a database with several million records).

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

Section 1 Lesson 3: Creating PL/SQL Blocks


Vocabulary
Identify the vocabulary word for each definition below:
Unnamed blocks of code not stored in the database and do not
Anonymous Blocks
exist after they are executed
A program that computes and returns a value
Function
Subprograms
Compiler
Procedure

Named PL/SQL blocks that are stored in the database and can
be declared as procedures or functions
Software that checks and translates programs written in highlevel programming languages into binary code to execute
A program that performs an action and does not have to return a
value

Try It / Solve It
1. Complete the following chart defining the syntactical requirements for a PL/SQL block:
Optional or Mandatory?
DECLARE
BEGIN
EXCEPTION
END;

optional
mandatory
optional
mandatory

Describe what is included


in this section
variabile,constante,cursori.

sql statements to retrieve data.


actiuni atunci cand sunt erori sau conditii anormale
in sectiunea executabila

2. Which of the following PL/SQL blocks executes successfully? For the blocks that fail,
explain why they fail
A.

BEGIN No declaration or exception sections


END;

B.

DECLARE
amount INTEGER(10);
END;

C.

DECLARE
BEGIN Declaration and execution sections, but no exception section
END;

D.

DECLARE
amount NUMBER(10);
BEGIN
DBMS_OUTPUT.PUT_LINE(amount);
END;

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

3. Fill in the blanks:


Anonymous Blocks
A. PL/SQL blocks that have no names are called __________________.
Function
Procedure
B. _______________
and _______________
are named blocks and are stored in the
database.

4. In Application Express, create and execute a simple anonymous block that outputs Hello
World.
Extension Exercise
1. Create and execute a simple anonymous block that does the following:
Declares a variable of datatype DATE and populates it with the date that is six
months from today
Outputs In six months, the date will be: <insert date>.

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

Section 2 Lesson 1: Using Variables in PL/SQL


Vocabulary
Identify the vocabulary word for each definition below:
Declaring VariablesUsed 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.
PL/SQL subprogram
A. Variables can be assigned to the output of a __________________.
executable

B. Variables can be assigned values in the _____________________ section of a


PL/SQL block.
parameters
C. Variables can be passed as ____________________
to subprograms.

2. Identify valid and invalid variable declaration and initialization:


number_of_copies
printer_name
deliver_to
by_when

PLS_INTEGER; invalid
CONSTANT VARCHAR2(10); invalid
VARCHAR2(10):=Johnson; valid
DATE:= SYSDATE+1; invalid

3. Examine the following anonymous block and choose the appropriate statement.
DECLARE
fname VARCHAR2(20);
lname VARCHAR2(15) DEFAULT 'fernandez';
BEGIN
DBMS_OUTPUT.PUT_LINE( FNAME ||' ' ||lname);
END;
The block will execute successfully and print fernandez.
The block will give an error because the fname variable is used without initializing.
The block will execute successfully and print null fernandez.
The block will give an error because you cannot use the DEFAULT keyword to
initialize a variable of the VARCHAR2 type.
E. The block will give an error because the FNAME variable is not declared.
A.
B.
C.
D.

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

4. 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;
5. Write an anonymous block that uses a country name as input and prints the highest and
lowest elevations for that country. Use the wf_countries table. Execute your block three
times using United States of America, French Republic, and Japan.

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

Section 2 Lesson 2: 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.

literal
Delimiters
Reserved words
Comments
Character Literals
Identifier

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.
A name, up to 30 characters in length, given to a PL/SQL object.

Try It / Solve It Questions


1. Fill in the blanks.
identifier
A. An ___________________
is the name given to a PL/SQL object.
Reserved words
B. A ____________________
is a word that has special meaning to the Oracle database.
Delimiters
C. A ____________________
is a symbol that has special meaning to the Oracle
database.
literal
D. A ____________________
is an explicit numeric, character string, date, or Boolean
value that is not represented by an identifier.
Comment
E. A_____________________
explains what a piece of code is trying to achieve.

2. Identify each of the following identifiers as valid or invalid. If invalid, specify why.
Identifier
Today
Last name
todays_date
number_of_days_in_february_this_
year
Isleap$year
#number
NUMBER#
Number1to7

Valid
(X)

Invalid
(X)
x
x
x

Why Invalid?

Contains a space
Contains a space
More than 30 characters

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

3. Identify the reserved words in the following list.


Word

Reserved?
Y/N

create
make
table
seat
alter
rename
row
number
web

n
y
y

n
y

y
n

4. What kind of lexical unit (for example Reserved word, Delimiter, Literal, Comment) is each
of the following?
Value
SELECT
:=
'TEST'
FALSE
-- new process
FROM
/*select the country
with the highest
elevation */
V_test
4.09

Lexical Unit

reserved word
delimiter
literal
boolean literals
comment
reserved word
comment
identifier
literal

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

Section 2 Lesson 3: Recognizing Data Types


Vocabulary
Identify the vocabulary word for each definition below:
National language character large Store
object large blocks of single-byte or fixed width multi-byte NCHAR
Large Object (LOB)
Scalar
Binary large object
Composite
Binary file
Reference
Object
Character large object

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.

Try It / Solve It
1. In your own words, describe what a data type is and explain why it is important.
A data type specifies a storage format, constraints, and a valid range of values.

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

2. Match the data type category (LOB, Scalar, Composite, Reference, and Object) with the
appropriate definition. Each data type may be used more than once.
Description
Stores a large amount of data

Data Type
LOB

Has internal components that can be


manipulated individually
Has a name, attributes, and methods

composite
object

Includes CLOBs, BLOBs, BFILEs, and


NCLOBs
Has no internal components
Includes TABLEs, RECORDs, NESTED
TABLEs, and VARRAYs
Includes TIMESTAMP, DATE,
BINARY_INTEGER, LONG, LONG RAW,
and BOOLEAN
Holds values, called pointers, that point to
a storage location

LOB
scalar
composite
scalar
reference

3. Enter the data type category for each value into the Data Type Category column. In
the Data Type column, enter a specific data type that can be used for the value. The
first one has been done for you.
Value
Switzerland
100.20
1053
12-DEC-2005
False
Index
1
2
3
A movie
A soundbyte
A picture

Data Type
Category
Scalar
number

Last_name
'Newman'
'Raman'
'Han'

number
date
boolean
character

character
character
character

Data Type
VARCHAR2

number
PLS_INTEGER
interval year to month

long raw
char
char
char

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

Section 2 Lesson 4: Using Scalar Data Types


Vocabulary
Identify the vocabulary word for each definition below:
A datatype that stores one of the three possible values used for
logical calculations: TRUE, FALSE, or NULL.
Attribute used to declare a variable according to another
previously declared variable or database column.

Boolean
%TYPE

Try It / Solve It
1. Declarations:
A. Which of the following variable declarations are valid?
Declaration
a
b
c
d

number_of_students
STUDENT_NAME
stu_per_class
tomorrow

Valid or
Invalid
PLS_INTEGER;
VARCHAR2(10)=Johnson;
CONSTANT NUMBER;
DATE := SYSDATE+1;

valid

valid

invalid

invalid

B. For those declarations in 1.A. that are invalid, describe why they are invalid.
C. Write an anonymous block in which you declare and print each of the variables in 1.A,
correcting the invalid declarations.
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;
3. Examine the declarations in question 2. Change the declarations so that they use the
%TYPE attribute.

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

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?
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.

B. In the executable section, initialize the TOMORROW variable with an expression that
calculates tomorrows date (add 1 to the value in TODAY). Print the value of TODAY
and TOMORROW after printing Hello World.

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

Section 2 Lesson 5: Writing PL/SQL Executable Statements


Vocabulary
Identify the vocabulary word for each definition below:
Explicit Conversions
Implicit Conversions

Converts values from one data type to another by using built-in


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

Try It / Solve It
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 programmers 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 todays date and then
calculate and display the number of months between the two dates.

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

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?
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.

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

Section 2 Lesson 6: Nested Blocks and Variable Scope


Vocabulary
Identify the vocabulary word for each definition below.
Qualifying an Identifier
Local and Global Variables
Variable Visibility

A label given to a block.


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.

Try It / Solve It
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;
-- Position 1 -END;
weight := weight + 1;
message := message || ' is in stock';
-- Position 2 -END;
A. The value of weight at position 1 is:
B. The value of new_locn at position 1 is:
C. The value of weight at position 2 is:
D. The value of message at position 2 is:
E. The value of new_locn at position 2 is:
Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

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 '||v_job);
END;
DBMS_OUTPUT.PUT_LINE(v_employee_id|| ' is a '||v_job);
END;
A. Why does the inner block display the job_id of employee 103, not employee 100?
B. Why does the outer block display the job_id of employee 100, not employee 103?
C. Modify the code to display the details of employee 100 in the inner block. Use block labels.

Copyright 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.

Vous aimerez peut-être aussi