D80182GC20 Ag1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 82

Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans Oracle Database 12c R2:
G n-t
no PL/SQL Fundamentals

Activity Guide
D80182GC20
Edition 2.0 | November 2016 | D98674

Learn more from Oracle University at education.oracle.com


Author Copyright © 2016, Oracle and/or it affiliates. All rights reserved.

Jayashree Sharma Disclaimer

This document contains proprietary information and is protected by copyright and


Technical Contributors other intellectual property laws. You may copy and print this document solely for
and Reviewers your own use in an Oracle training course. The document may not be modified or
altered in any way. Except where your use constitutes "fair use" under copyright
Bryan Roberts law, you may not use, share, download, upload, copy, print, display, perform,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

reproduce, publish, license, post, transmit, or distribute this document in whole or in


Miyuki Osato part without the express authorization of Oracle.
Nancy Greenberg
The information contained in this document is subject to change without notice. If
Suresh Rajan you find any problems in the document, please report them in writing to: Oracle
University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This
document is not warranted to be error-free.
Editor
Vijayalakshmi Narasimhan Restricted Rights Notice

If this documentation is delivered to the United States Government or anyone using


Graphic Designers the documentation on behalf of the United States Government, the following notice
is applicable:
Prakash Dharmalingam
s a
Seema Bopaiah U.S. GOVERNMENT RIGHTS
) h a
The U.S. Government’s rights to use, modify, reproduce, release, perform, display,
Maheshwari Krishnamurthy
c o m ฺ
or disclose these training materials are restricted by the terms of the applicable
e
e ฺ i d
Oracle license agreement and/or the applicable U.S. Government contract.

Publishers r a cl t Gu
Trademark Notice
@ o en
Syed Imtiaz Ali
s a d
S t ud
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other
Sujatha Nagendra
ra this
names may be trademarks of their respective owners.
ฺ p
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no
Table of Contents
Security Credentials ................................................................................................................................. I-1
Security Credentials ............................................................................................................................... I-2
Practices for Lesson 1: Introduction ........................................................................................................ 1-1
Practices for Lesson 1............................................................................................................................. 1-2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Practice 1-1: Getting Started ................................................................................................................... 1-3


Solution 1-1: Getting Started ................................................................................................................... 1-5
Practices for Lesson 2: Introduction to PL/SQL....................................................................................... 2-1
Practices for Lesson 2: Introduction to PL/SQL ........................................................................................ 2-2
Practice 2: Introduction to PL/SQL ........................................................................................................... 2-3
Solution 2: Introduction to PL/SQL ........................................................................................................... 2-4
Practices for Lesson 3: Declaring PL/SQL Variables ............................................................................... 3-1
Practice 3: Declaring PL/SQL Variables ................................................................................................... 3-2
Solution 3: Declaring PL/SQL Variables ................................................................................................... 3-4
s a
Practices for Lesson 4: Writing Executable Statements .......................................................................... 4-1
) h a
c o m
Practice 4: Writing Executable Statements ............................................................................................... 4-2
e ฺ
e ฺ i d
Solution 4: Writing Executable Statements ............................................................................................... 4-4

r a cl t Gu 5-1
Practices for Lesson 5: Using SQL Statements within a PL/SQL Block ..................................................
@ o en
a d t u d
Practice 5: Using SQL Statements Within a PL/SQL................................................................................. 5-2

r a s sS
Solution 5: Using SQL Statements Within a PL/SQL................................................................................. 5-4

u ฺp e thi
Practices for Lesson 6: Writing Control Structures .................................................................................
r
6-1

d a lu us
Practice 6: Writing Control Structures ...................................................................................................... 6-2

id se t o
Solution 6: Writing Control Structures ......................................................................................................
g
6-4
Practices for Lesson 7: Working d (
with Composite n......................................................................................
Data Types ................................................................. 7-1
a s a l i c e
r
Practice 7: Working with Composite
P Composite l e
Data Types
b Data Types ...................................................................................... 7-5
7-2

u r u
Solution 7: Working with
r a
d a UsingnExplicit
s fe Explicit Cursors ....................................................................................... 8-1
Practices for lLesson 8: Using
i d
Practice
G 8-1:
- t r a Cursors ......................................................................................................... 8-2

non
Solution 8-1: Using Explicit Cursors ......................................................................................................... 8-5
Practice 8-2: Using Explicit Cursors: Optional .......................................................................................... 8-10
Solution 8-2: Using Explicit Cursors: Optional .......................................................................................... 8-11
Practices for Lesson 9: Handling Exceptions .......................................................................................... 9-1
Practice 9-1: Handling Predefined Exceptions .......................................................................................... 9-2
Solution 9-1: Handling Predefined Exceptions .......................................................................................... 9-4
Practice 9-2: Handling Standard Oracle Server Exceptions....................................................................... 9-6
Solution 9-2: Handling Standard Oracle Server Exceptions....................................................................... 9-7
Practices for Lesson 10: Introducing Stored Procedures and Functions................................................ 10-1
Practice 10: Creating and Using Stored Procedures ................................................................................. 10-2
Solution 10: Creating and Using Stored Procedures ................................................................................. 10-4

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Oracle Database 12c R2: PL/SQL Fundamentals Table of Contents


i
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
o en
Security Credentials
@
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Security Credentials
Page 1
Security Credentials

username:ora41

password:ora41
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Security Credentials
Page 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
Practices for o en 1:
Lesson
Introduction
a d @ t ud
s
ra this S
r u ฺ p
Chapter 1
l u s e
i d da to u
d (g nse
r a s a l i ce
r u P able
d a lu sfer
n
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 1
Practices for Lesson 1

Lesson Overview
In these practices, you perform the following:
• Start SQL Developer
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Create a new database connection


• Browse the schema tables
• Set a SQL Developer preference
Note: All written practices use SQL Developer as the development environment. Although it is
recommended that you use SQL Developer, you can also use the SQL*Plus environment that is
available in this course.

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 2
Practice 1-1: Getting Started

1. Start SQL Developer.


2. Create a database connection by using the following information (Hint: Select the Save
Password check box):
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

a. Connection Name: MyConnection


b. Username: ora41
c. Password: (refer to security credential document)
d. Hostname: localhost
e. Port: 1521
f. Service name: pdborcl
3. Test the new connection. If the Status is Success, connect to the database by using this
new connection.
a. In the Database Connection window, click the Test button. s a
Note: The connection status appears in the lower-left corner of the window. )h a
b. If the Status is Success, click the Connect button. c m
o deฺ
l e ฺ u i
4. Browse the structure of the EMPLOYEES table and display its data.
a c G
a. Expand the MyConnection connection by clicking the plus
@ orsymbolennext t to it.
b. Expand Tables by clicking the plus symbol next s tod
a it.
S t ud
c. Display the structure of the EMPLOYEESฺp ra this
table.
5. Use the Data tab to view the data inathe l r u
uEMPLOYEES
s e table.
u
6. Use the SQL Worksheet to select
( g iddthe slast
e to and salaries of all employees whose
names
annual salary is greater d
sa thelicSELECT
Script (F5) icons rtoaexecute
en Usestatement.
than $10,000. both the Execute Statement (F9) and the Run
Review the results of both methods of
executing the u P b l e
statement on the appropriate tabs.
u r
l a few
SELECT
e r a
fminutes
Note:aTake s to familiarize yourself with the data, or consult Appendix A, which
i d d n
radescription and data for all the tables in the HR schema that you will use in this
Gprovides
n
course. - tthe
no
7. From the SQL Developer menu, select Tools > Preferences. The Preferences window
appears.
8. Select Database > Worksheet Parameters. In the “Select default path to look for scripts”
text box, use the Browse icon to select the /home/oracle/labs/plsf directory. This
directory contains the code example scripts, lab scripts, and practice solution scripts that
are used in this course. Then, in the Preferences window, click OK to save the Worksheet
Parameter setting.

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 3
9. Familiarize yourself with the structure of the /home/oracle/labs/plsf directory.
a. Select File > Open. The Open window automatically selects the …/plsf directory as
your starting location. This directory contains three subdirectories:
• The /code_ex directory contains the code examples that are found in the course
materials. Each .sql script is associated with a particular page in the lesson.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• The /labs directory contains the code that is used in certain lesson practices. You
are instructed to run the required script in the appropriate practice.
• The /soln directory contains the solutions for each practice. Each .sql script is
numbered with the associated practice_exercise reference.
b. You can also use the Files tab to navigate through the directories to open the script
files.
c. Using the Open window, and the Files tab, navigate through the directories and open a
script file without executing the code.
d. Close the SQL Worksheet.
s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 4
Solution 1-1: Getting Started
1. Start SQL Developer.
Double Click the SQL Developer icon on your desktop.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

2. Create a database connection by using the following information (Hint: Select the Save
Password check box):
a. Connection Name: MyConnection
b. Username: ora41
c. Password: refer to the security credential document
d. Hostname: localhost
s a
e. Port: 1521
) h a
f. Service name : pdborcl
c o m e ฺ
e ฺ i d
Connection. r a cl t Gu
Right-click the Connections node on the Connections tabbed page and select New

@ o en
s a d
S t ud
Result: The New/Select Database Connection window appears.

ฺ p ra this
Use the preceding information to create the new database connection. In addition, select the
Save Password check box. For example:
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 5
3. Test the new connection. If the Status is Success, connect to the database by using this
new connection.
a. In the Database Connection window, click the Test button.
Note: The connection status appears in the lower-left corner of the window.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
u
ur ubutton.
b. If the Status is Success, click the Connect
l s e
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Note: To display the properties of an existing connection, right-click the connection name
on the Connections tab and select Properties from the shortcut menu.
4. Browse the structure of the EMPLOYEES table and display its data.

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 6
a. Expand the MyConnection connection by clicking the plus symbol next to it.
b. Expand Tables by clicking the plus symbol next to it.
c. Display the structure of the EMPLOYEES table.
• Drill down on the EMPLOYEES table by clicking the plus symbol next to it.
• Click the EMPLOYEES table.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Result: The Columns tab displays the columns in the EMPLOYEES table as follows:

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u r u s e
5. Use the Data tab to view the datad a to u
d in theeEMPLOYEES table.
( g i
Result: The EMPLOYEES table data is s
s a d cen displayed as follows:
P ra ble li
l u ru fera
i d da rans
G n-t
no

6. Use the SQL Worksheet to select the last names and salaries of all employees whose
annual salary is greater than $10,000. Use both the Execute Statement (F9) and Run Script
(F5) icons to execute the SELECT statement. Review the results of both methods of
executing the SELECT statements on the appropriate tabs.
Note: Take a few minutes to familiarize yourself with the data, or consult Appendix A, which
provides the description and data for all the tables in the HR schema that you will use in this
course.
To display the SQL Worksheet, click the MyConnection tab.
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 7
Note: This tab was opened previously when you drilled down on your database connection.
Enter the appropriate SELECT statement. Press F9 to execute the query and F5 to execute the
query by using the Run Script method.
For example, when you press F9, the results appear similar to the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 8
7. From the SQL Developer menu, select Tools > Preferences. The Preferences window
appears.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 9
8. Select Database > Worksheet Parameters. In the “Select default path to look for scripts”
text box, use the Browse icon to select the /home/oracle/labs/plsf directory.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
)h a
c m
o deฺ
l e ฺ u i
a c G
@ or ent
s a d
S t ud
ฺ p ra this
l u
ur use
a
g idd scripts,
This directory contains the code example
( e tolab scripts, and practice solution scripts that
are used in this course.
s a d cens
Click Select to choosera
P l e li
the directory.

l u ru ferab
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 10
Then, in the Preferences window, click OK to save the Worksheet Parameter setting.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a dthe structure
c e n of the /home/oracle/labs/plsf directory.
9. Familiarize yourself with
ra bNavigate l i
a. Select u FileP> Open.
a le to the /home/oracle/labs/plsf directory. This
r
lu contains f er three subdirectories:
d a
directory
n s
Gid n-tra
no

• The /code_ex directory contains the code examples found in the course
materials. Each .sql script is associated with a particular page in the lesson.
• The /labs directory contains the code that is used in certain lesson practices.
You are instructed to run the required script in the appropriate practice.
• The /soln directory contains the solutions for each practice. Each .sql script is
numbered with the associated practice_exercise reference.

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 11
b. You can also use the Files tab to navigate through the directories to open the script
files.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
)h a
c m
o deฺ
l e ฺ u i
a c G
@ or ent
s a d
S t ud
ฺ p ra this
l u
ur use
a
c. Using the Open window, and
( g idthedthecode.
e o navigate through the directories and open a
Filesttab,

s a d cens
script file without executing
d. Close the SQL Worksheet.
P ra btab,l e li
To close any SQL Worksheet click X on the tab, as shown here:
u r u r a
d d al nsfe
Gi n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 12
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
Practices for o en 2:
Lesson
Introduction
a d @ to
t udPL/SQL
s
ra this S
r u ฺ p
Chapter 2
l u s e
i d da to u
d (g nse
r a s a l i ce
r u P able
d a lu sfer
n
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Introduction to PL/SQL


Chapter 2 - Page 1
Practices for Lesson 2: Introduction to PL/SQL

Lesson Overview
The /home/oracle/labs/plsf/labs folder is the working directory where you save the
scripts that you create.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

The solutions for all the practices are in the /home/oracle/labs/plsf/soln folder.

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Introduction to PL/SQL


Chapter 2 - Page 2
Practice 2: Introduction to PL/SQL

1. Which of the following PL/SQL blocks execute successfully?


a. BEGIN
commit;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

END;
b. DECLARE
v_amount INTEGER(10);
END;
c. DECLARE
BEGIN
END;
d. SET SERVEROUTPUT ON;
DECLARE
s a
v_amount INTEGER(10);
BEGIN ) h a
DBMS_OUTPUT.PUT_LINE(v_amount);
c o m e ฺ
e ฺ i d
END;
r a cl t Gu
2. o en
Create and execute a simple anonymous block that outputs “Hello World.” Execute and
@
save this script as lab_02_02_soln.sql.
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Introduction to PL/SQL


Chapter 2 - Page 3
Solution 2: Introduction to PL/SQL
1. Which of the following PL/SQL blocks execute successfully?
a. BEGIN
commit;
END;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

b. DECLARE
v_amount INTEGER(10);
END;
c. DECLARE
BEGIN
END;
d. SET SERVEROUTPUT ON;
DECLARE
v_amount INTEGER(10);
BEGIN
s a
DBMS_OUTPUT.PUT_LINE(v_amount);
) h a
END;
c o m e ฺ
The block in a executes successfully.
e ฺ i d
a cl t Gu
The block in b does not have the mandatory executable section that starts with the BEGIN
r
keyword.
@ o en
s a d t ud
The block in c has all the necessary parts, but no executable statements.
S
The block in d executes successfully. ฺ p ra this
l u
ur use
2. Create and execute a simple anonymous block that outputs “Hello World.” Execute and
a
( g idd se to
save this script as lab_02_02_soln.sql.

s a d cen
Enter the following code in the workspace, and then press F5.
SET SERVEROUTPUT
P r a ON le li
BEGIN
l u ru ferab Hello World ');
i d
END; da rans
DBMS_OUTPUT.PUT_LINE('

G nsee
o
You should
-t the following output on the Script Output tab:
n

Click the Save button. Select the folder in which you want to save the file. Enter
lab_02_02_soln.sql as the file name and click Save.

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Introduction to PL/SQL


Chapter 2 - Page 4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
Practices for o en 3:
Lesson
Declaring a @ t ud Variables
d PL/SQL
s
ra this S
r u ฺ p
Chapter 3
l u s e
i d da to u
d (g nse
r a s a l i ce
r u P able
d a lu sfer
n
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Declaring PL/SQL Variables


Chapter 3 - Page 1
Practice 3: Declaring PL/SQL Variables

In this practice, you declare PL/SQL variables.


1. Identify valid and invalid identifiers:
a. today
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

b. last_name
c. today’s_date
d. Number_of_days_in_February_this_year
e. Isleap$year
f. #number
g. NUMBER#
h. number1to7
2. Identify valid and invalid variable declaration and initialization:
s a
a. number_of_copies PLS_INTEGER;
)h a
b. PRINTER_NAME constant VARCHAR2(10);
c m
o deฺ
c. deliver_to VARCHAR2(10):=Johnson;
l e ฺ ui
d. by_when DATE:= CURRENT_DATE+1; rac t G
@ o efrom n
3. Examine the following anonymous block, and then select
a d a
t u d
statement the following
that is true. s
ra this S
DECLARE ฺ
ru sep
l u
v_fname VARCHAR2(20);
v_lname VARCHAR2(15) DEFAULT i d da 'fernandez';
t o u
BEGIN
d (g nse
a s a
DBMS_OUTPUT.PUT_LINE(v_fname
r l i ce ||' ' ||v_lname);
END;
r u P able
d a lu sfer
Ga.b.id The -
block
t r anexecutes successfully and prints “fernandez.”
n n block produces an error because the fname variable is used without initializing.
oThe
c. The block executes successfully and prints “null fernandez.”
d. The block produces an error because you cannot use the DEFAULT keyword to
initialize a variable of type VARCHAR2.
e. The block produces an error because the v_fname variable is not declared.

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Declaring PL/SQL Variables


Chapter 3 - Page 2
4. Modify an existing anonymous block and save it as a new script.
a. Open the lab_02_02_soln.sql script, which you created in Practice 2 titled
“Introduction to PL/SQL.”
b. In this PL/SQL block, declare the following variables:
1) v_today of type DATE. Initialize today with SYSDATE.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

2) v_tomorrow of type today. Use the %TYPE attribute to declare this variable.
c. In the executable section:
1) Initialize the v_tomorrow variable with an expression, which calculates
tomorrow’s date (add one to the value in today)
2) Print the value of v_today and v_tomorrow after printing “Hello World”
d. Save your script as lab_03_04_soln.sql, and then execute.
The sample output is as follows (the values of v_today and v_tomorrow will be
different to reflect your current today’s and tomorrow’s date):
s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
5. Edit the lab_03_04_soln.sql script.
s a d
S t ud
a. Add code to create two bind variables named ฺ p ra b_basic_percent
t his and
b_pf_percent. Both bind variables r u
lu us
are of e
type NUMBER.
d a toblock, assign the values 45 and 12 to
dthe PL/SQL
b. In the executable section of
( g i e
b_basic_percentdand b_pf_percent,
s a c e ns respectively.
c. Terminate the
P r li with “/” and display the value of the bind variables by
aPL/SQLleblock
ru PRINT
using the
r b
acommand.
l
a and
d. Execute u f e
s save your script as lab_03_05_soln.sql. The sample output is as
i d dfollows:r a n
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Declaring PL/SQL Variables


Chapter 3 - Page 3
Solution 3: Declaring PL/SQL Variables
1. Identify valid and invalid identifiers:
a. today Valid
b. last_name Valid
c. today’s_date Invalid – character “’” not allowed
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

d. Number_of_days_in_February_this_year Invalid – Too long


e. Isleap$year Valid
f. #number Invalid – Cannot start with “#”
g. NUMBER# Valid
h. number1to7 Valid
2. Identify valid and invalid variable declaration and initialization:
a. number_of_copies PLS_INTEGER; Valid
b. PRINTER_NAME constant VARCHAR2(10);
s a Invalid
c. deliver_to VARCHAR2(10):=Johnson; Invalid
)h a
d. by_when DATE:= CURRENT_DATE+1; Valid
c m
o deฺ
l e ฺ u i
a c G
The declaration in b is invalid because constant variables must be
@ orinitialized
e n t declaration.
during
a
The declaration in c is invalid because string literals should
s dbe enclosed
S t udwithin single quotation
marks.
ฺ p ra this
3. Examine the following anonymous block,
l u
urand then s eselect a statement from the following
a u
idd se to
that is true.
DECLARE (
d ceng
s
v_fname VARCHAR2(20);a i
P ra ble lDEFAULT
v_lname VARCHAR2(15) 'fernandez';
BEGIN
l u
ur sfera
d a
d ran
DBMS_OUTPUT.PUT_LINE(v_fname ||' ' ||v_lname);
i
G n-t
END;
no
a. The block executes successfully and prints “fernandez.”
b. The block produces an error because the fname variable is used without initializing.
c. The block executes successfully and prints “null fernandez.”
d. The block produces an error because you cannot use the DEFAULT keyword to
initialize a variable of type VARCHAR2.
e. The block produces an error because the v_fname variable is not declared.

a. The block will execute successfully and print “fernandez.”

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Declaring PL/SQL Variables


Chapter 3 - Page 4
4. Modify an existing anonymous block and save it as a new script.
a. Open the lab_02_02_soln.sql script, which you created in Practice 2 titled
“Introduction to PL/SQL.”
b. In the PL/SQL block, declare the following variables:
1) Variable v_today of type DATE. Initialize today with SYSDATE.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

DECLARE
v_today DATE:=SYSDATE;

2) Variable v_tomorrow of type today. Use the %TYPE attribute to declare this
variable.

v_tomorrow v_today%TYPE;

In the executable section: s a


1) Initialize the v_tomorrow variable with an expression, which calculates)h a
tomorrow’s date (add one to the value in v_today) c m
o deฺ
l e ฺ u i
a c
2) Print the value of v_today and v_tomorrow after printing “Hello World”
G
@ or ent
BEGIN s a d
S t ud
v_tomorrow:=v_today +1;
DBMS_OUTPUT.PUT_LINE(' HelloruWorld ฺpra e');this
DBMS_OUTPUT.PUT_LINE('TODAY
d a lu IS :u'||
s v_today);
g
DBMS_OUTPUT.PUT_LINE('TOMORROWd
i se t oIS : ' || v_tomorrow);
(
d cen
END;
s a li
P ra asblab_03_04_soln.sql,
c. Save your script l e and then execute.
u
The
l u ra is as follows (the values of v_today and v_tomorrow will be
r samplefeoutput
a
d different s
n to reflect your current today’s and tomorrow’s date):
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Declaring PL/SQL Variables


Chapter 3 - Page 5
5. Edit the lab_03_04_soln.sql script.
a. Add code to create two bind variables named b_basic_percent and
b_pf_percent. Both bind variables are of type NUMBER.
VARIABLE b_basic_percent NUMBER
VARIABLE b_pf_percent NUMBER
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

b. In the executable section of the PL/SQL block, assign the values 45 and 12 to
b_basic_percent and b_pf_percent, respectively.
:b_basic_percent:=45;
:b_pf_percent:=12;
c. Terminate the PL/SQL block with “/” and display the value of the bind variables by
using the PRINT command.
/
PRINT b_basic_percent
PRINT b_pf_percent
s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no
OR

PRINT
d. Execute and save your script as lab_03_05_soln.sql. The sample output is as
follows:

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Declaring PL/SQL Variables


Chapter 3 - Page 6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
Practices for o en 4:
Lesson
Writing a @ t ud
dExecutable
s
ra this S
u ฺ p
Statements
a l ur use
( g idd se Chapter
to 4
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Writing Executable Statements


Chapter 4 - Page 1
Practice 4: Writing Executable Statements

Note: If you have executed the code examples for this lesson, make sure that you execute the
following code before starting this practice:
DROP sequence my_seq;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

In this practice, you examine and write executable statements.

DECLARE
v_weight NUMBER(3) := 600;
v_message VARCHAR2(255) := 'Product 10012';
BEGIN
DECLARE
v_weight NUMBER(3) := 1;
v_message VARCHAR2(255) := 'Product 11001';
v_new_locn VARCHAR2(50) := 'Europe';
s a
BEGIN
v_weight := v_weight + 1; )h a
v_new_locn := 'Western ' || v_new_locn; c m
o deฺ
l e ฺ u i
1
a c G
END;
@ or ent
v_weight := v_weight + 1;
v_message := v_message || ' is in stock'; s a d
S t ud
v_new_locn := 'Western ' || v_new_locn; ฺ p ra this
2 l u
ur use
a
idd se to
END;
/ ( g
d cblock n and determine the data type and value of each of the
1. Evaluate the preceding s a PL/SQL
l i e
P
following variables, raaccording
b le to the rules of scoping.
a. The r u er a
luvalue ofsfv_weight at position 1 is:
d a
Gb.c.id The - t r anof v_new_locn at position 1 is:
value

n n value of v_weight at position 2 is:


oThe
d. The value of v_message at position 2 is:
e. The value of v_new_locn at position 2 is:

DECLARE
v_customer VARCHAR2(50) := 'Womansport';
v_credit_rating VARCHAR2(50) := 'EXCELLENT';
BEGIN
DECLARE
v_customer NUMBER(7) := 201;
v_name VARCHAR2(25) := 'Unisports';
BEGIN
v_credit_rating :='GOOD';

END;

END;

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Writing Executable Statements


Chapter 4 - Page 2
2. In the preceding PL/SQL block, determine the value and data type of each of the following
cases:
a. The value of v_customer in the nested block is:
b. The value of v_name in the nested block is:
c. The value of v_credit_rating in the nested block is:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

d. The value of v_customer in the main block is:


e. The value of v_name in the main block is:
f. The value of v_credit_rating in the main block is:
3. Use the same session that you used to execute the practices in the lesson titled “Declaring
PL/SQL Variables.” If you have opened a new session, execute lab_03_05_soln.sql.
Then, edit lab_03_05_soln.sql as follows:
a. Use single-line comment syntax to comment the lines that create the bind variables,
and turn on SERVEROUTPUT.
b. Use multiple-line comments in the executable section to comment the lines that assign
s a
values to the bind variables.
)h a
c. In the declaration section:
c m
o deฺ
e ฺ i
1) Declare and initialize two temporary variables to replace the commented out bind
l u
a c G
variables
@ or ent
v_emp_sal of type NUMBER and size 10 s a d
S t ud
2) Declare two additional variables: v_fname of type VARCHAR2 and size 15, and

ฺ p ra this
l u
d. Include the following SQL statement in the executable section:
ur use
a
SELECT first_name, g
( idd sINTO
salary e tov_fname, v_emp_sal
FROM employees
s a n
d WHEREceemployee_id=110;
ra ble l i
u P a prints “Hello World” to print “Hello” and the first name. Then,
e. Change
a l ur thethe
s
line rthat
f e
i d d ran
comment lines that display the dates and print the bind variables.

o n -t the contribution of an employee toward the provident fund (PF).


Gf. Calculate
n variables
PF is 12% of the basic salary, and the basic salary is 45% of the salary. Use local
for the calculation. Try to use only one expression to calculate the PF. Print
the employee’s salary and his or her contribution toward PF.
g. Execute and save your script as lab_04_03_soln.sql. The sample output is as
follows:

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Writing Executable Statements


Chapter 4 - Page 3
Solution 4: Writing Executable Statements
In this practice, you examine and write executable statements.

DECLARE
v_weight NUMBER(3) := 600;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

v_message VARCHAR2(255) := 'Product 10012';


BEGIN
DECLARE
v_weight NUMBER(3) := 1;
v_message VARCHAR2(255) := 'Product 11001';
v_new_locn VARCHAR2(50) := 'Europe';
BEGIN
v_weight := v_weight + 1;
v_new_locn := 'Western ' || v_new_locn;
1
s a
END;
v_weight := v_weight + 1; )h a
v_message := v_message || ' is in stock'; c m
o deฺ
l e ฺ u i
v_new_locn := 'Western ' || v_new_locn;
a c G
2
@ or ent
END;
s a d
S t ud
ra the
/
1. Evaluate the preceding PL/SQL block andu ฺ p
determine t s type and value of each of the
hidata
r e
lu of scoping:
following variables, according to thearules
d o us
a. The value of v_weightg atid t
position 1 is:
2
a d (
e n se
The data typeais
r sNUMBER.lic
u a b le at position 1 is:
Pof v_new_locn
b. The valuer
lu Europe f er
d a
Western s
Gc.id The - r
data
t antype is VARCHAR2.
no601n value of v_weight at position 2 is:
The

The data type is NUMBER.


d. The value of v_message at position 2 is:
Product 10012 is in stock
The data type is VARCHAR2.
e. The value of v_new_locn at position 2 is:
Illegal because v_new_locn is not visible outside the subblock

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Writing Executable Statements


Chapter 4 - Page 4
DECLARE
v_customer VARCHAR2(50) := 'Womansport';
v_credit_rating VARCHAR2(50) := 'EXCELLENT';
BEGIN
DECLARE
v_customer NUMBER(7) := 201;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

v_name VARCHAR2(25) := 'Unisports';


BEGIN
v_credit_rating :='GOOD';

END;

END;

2. In the preceding PL/SQL block, determine the value and data type for each of the following
cases:
a. The value of v_customer in the nested block is: s a
201 ) h a
The data type is NUMBER. c o m e ฺ
e ฺ i d
b. The value of v_name in the nested block is:
r a cl t Gu
Unisports
@ o en
The data type is VARCHAR2.
s a d
S t ud
c. The value of v_credit_rating in the nested
ฺ p ra block
t h isis:
GOOD u
ur use
The data type is VARCHAR2.dal
d. The value of v_customer ( g idin thesmain
e toblock is:
Womansport sad c e n
rais VARCHAR2. l i
The data P
u
type
a b le
e. The r
luvalue er visible
of v_name
f in the main block is:
d a
Null. n sis not in the main block and you would see an error.
Gf.id The a
name
t r
n-value of v_credit_rating in the main block is:
noEXCELLENT
The data type is VARCHAR2.
3. Use the same session that you used to execute the practices in the lesson titled “Declaring
PL/SQL Variables.” If you have opened a new session, execute lab_03_05_soln.sql.
Then, edit lab_03_05_soln.sql as follows:
a. Use single-line comment syntax to comment the lines that create the bind variables,
and turn on SERVEROUTPUT.

-- VARIABLE b_basic_percent NUMBER


-- VARIABLE b_pf_percent NUMBER
SET SERVEROUTPUT ON

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Writing Executable Statements


Chapter 4 - Page 5
b. Use multiple-line comments in the executable section to comment the lines that assign
values to the bind variables.

/*:b_basic_percent:=45;
:b_pf_percent:=12;*/
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

c. In the declaration section:


1) Declare and initialize two temporary variables to replace the commented out bind
variables
2) Declare two additional variables: v_fname of type VARCHAR2 and size 15, and
v_emp_sal of type NUMBER and size 10

DECLARE
v_basic_percent NUMBER:=45;
s a
v_pf_percent NUMBER:=12;
v_fname VARCHAR2(15); ) h a
v_emp_sal NUMBER(10);
c o m e ฺ
e ฺ i d
r a cl t Gu
d. Include the following SQL statement in the executable section:
@ o en
s a d
S t ud
SELECT first_name, salary INTO p
ฺ ra thisv_emp_sal
v_fname,
FROM employees WHERE employee_id=110;
l u
ur use
d a toto print “Hello” and the first name. Then,
( g
e. Change the line that prints id“Hello e
World”
comment the lines
s a d display
that c e nthesdates and print the bind variables.
P ra ble li
l u ru fera
DBMS_OUTPUT.PUT_LINE(' Hello '|| v_fname);
/* daDBMS_OUTPUT.PUT_LINE('TODAY
n s IS : '|| v_today);
i d -t r a
GDBMS_OUTPUT.PUT_LINE('TOMORROW IS : ' || v_tomorrow);*/
... on
...
n
/
--PRINT b_basic_percent
--PRINT b_basic_percent

f. Calculate the contribution of an employee toward the provident fund (PF).


PF is 12% of the basic salary, and the basic salary is 45% of the salary. Use local
variables for the calculation. Try to use only one expression to calculate the PF. Print
the employee’s salary and his or her contribution toward PF.

DBMS_OUTPUT.PUT_LINE('YOUR SALARY IS : '||v_emp_sal);


DBMS_OUTPUT.PUT_LINE('YOUR CONTRIBUTION TOWARDS PF:
'||v_emp_sal*v_basic_percent/100*v_pf_percent/100);
END;

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Writing Executable Statements


Chapter 4 - Page 6
g. Execute and save your script as lab_04_03_soln.sql. The sample output is as
follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Writing Executable Statements


Chapter 4 - Page 7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Writing Executable Statements


Chapter 4 - Page 8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
)h a
c m
o deฺ
l e ฺ u i
a c G
Practices for
@ orLessone n t 5: Using
s a d
SQL Statements S t ud within a
p
PL/SQL
ฺ ra thBlock
is
r u
lu Chapter e
d d a t o us 5
d (gi nse
r a sa lice
r u P able
d a lu sfer
n
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using SQL Statements within a PL/SQL Block


Chapter 5 - Page 1
Practice 5: Using SQL Statements Within a PL/SQL

Note: If you have executed the code examples for this lesson, make sure that you execute the
following code before starting this practice:
DROP table employees2;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

DROP table copy_emp;


In this practice, you use PL/SQL code to interact with the Oracle Server.
1. Create a PL/SQL block that selects the maximum department ID in the departments table
and stores it in the v_max_deptno variable. Display the maximum department ID.
a. Declare a variable v_max_deptno of type NUMBER in the declarative section.
b. Start the executable section with the BEGIN keyword and include a SELECT statement
to retrieve the maximum department_id from the departments table.
c. Display v_max_deptno and end the executable block.
d. Execute and save your script as lab_05_01_soln.sql. The sample output is as s a
follows: ) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
2. Modify the PL/SQL block that you created l u
ur in steps1eto insert a new department into the
a u
departments table.
( g idd se to
a. Load the lab_05_01_soln.sql
s a d cen script. Declare two variables:
v_dept_name
P r of type li
a ledepartments.department_name and

l u ru'Education'
v_dept_id
f e r atobNUMBER.
of type

d d a
Assign
n s v_dept_name in the declarative section.
Gb.i Youn - ra already retrieved the current maximum department number from the
thave
n odepartments table. Add 10 to it and assign the result to v_dept_id.
c. Include an INSERT statement to insert data into the department_name,
department_id, and location_id columns of the departments table.
Use the values in v_dept_name and v_dept_id for department_name and
department_id, respectively, and use NULL for location_id.
d. Use the SQL attribute SQL%ROWCOUNT to display the number of rows that are affected.
e. Execute a SELECT statement to check whether the new department is inserted. You
can terminate the PL/SQL block with “/” and include the SELECT statement in your
script.
f. Execute and save your script as lab_05_02_soln.sql. The sample output is as
follows:

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using SQL Statements within a PL/SQL Block


Chapter 5 - Page 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

3. In step 2, you set location_id to NULL. Create a PL/SQL block that updates
location_id to 3000 for the new department.
Note: If you successfully completed step 2, continue with step 3a. If not, first execute the
solution script /soln/sol_05.sql. (Task 2 in sol_05.sql)
a. Start the executable block with the BEGIN keyword. Include the UPDATE statement to
set location_id to 3000 for the new department (v_dept_id =280).
s a
b. a
End the executable block with the END keyword. Terminate the PL/SQL block with “/”
) h
and include a SELECT statement to display the department that you updated.
m
e ฺc uideฺ
c. Include a DELETE statement to delete the department that you ladded.
o
d. Execute and save your script as lab_05_03_soln.sql. o ac sample
rThe n t Goutput is as
follows:
s a d@ tude
ฺ p ra this S
l u ru se
i d da to u
d (g nse
r a s a l i ce
r u P able
d a lu sfer
n
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using SQL Statements within a PL/SQL Block


Chapter 5 - Page 3
Solution 5: Using SQL Statements Within a PL/SQL
In this practice, you use PL/SQL code to interact with the Oracle Server.
1. Create a PL/SQL block that selects the maximum department ID in the departments table
and stores it in the v_max_deptno variable. Display the maximum department ID.
a. Declare a variable v_max_deptno of type NUMBER in the declarative section.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

DECLARE
v_max_deptno NUMBER;

b. Start the executable section with the BEGIN keyword and include a SELECT statement
to retrieve the maximum department_id from the departments table.

BEGIN
SELECT MAX(department_id) INTO v_max_deptno FROM
s a
departments;
) h a
c o m e ฺ
e ฺ i d
c. Display v_max_deptno and end the executable block.
r a cl t Gu
@ o en
DBMS_OUTPUT.PUT_LINE('The maximum department_id
s a d
S t udis : ' ||
v_max_deptno);
ฺ p ra this
END;
l u
ur use
a
g iddas lab_05_01_soln.sql.
d. Execute and save your(script
s e to The sample output is as
follows: d
sa lice n
r a
P able
r u
lu sfer
d a n
Gid n-tra
no
2. Modify the PL/SQL block that you created in step 1 to insert a new department into the
departments table.
a. Load the lab_05_01_soln.sql script. Declare two variables:
v_dept_name of type departments.department_name and
v_dept_id of type NUMBER.
Assign 'Education' to v_dept_name in the declarative section.

v_dept_name departments.department_name%TYPE:= 'Education';


v_dept_id NUMBER;

b. You have already retrieved the current maximum department number from the
departments table. Add 10 to it and assign the result to v_dept_id.

v_dept_id := 10 + v_max_deptno;

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using SQL Statements within a PL/SQL Block


Chapter 5 - Page 4
c. Include an INSERT statement to insert data into the department_name,
department_id, and location_id columns of the departments table.
Use the values in v_dept_name and v_dept_id for department_name and
department_id, respectively, and use NULL for location_id.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

INSERT INTO departments (department_id, department_name,


location_id)
VALUES (v_dept_id, v_dept_name, NULL);

d. Use the SQL attribute SQL%ROWCOUNT to display the number of rows that are affected.

DBMS_OUTPUT.PUT_LINE (' SQL%ROWCOUNT gives ' || SQL%ROWCOUNT);


s a
e.
) h a
Execute a SELECT statement to check whether the new department is inserted. You
can terminate the PL/SQL block with “/” and include the SELECT statement in your
script. c o m e ฺ
e ฺ i d
r a cl t Gu

@ o en
/
s a d
S t ud
SELECT * FROM departments WHERE department_id=
ฺ p ra this 280;

l u ru se
f. Execute and save your scriptd asalab_05_02_soln.sql.
u The sample output is as
i d t o
follows:
d (g nse
r a s a l i ce
r u P able
d a lu sfer
n
Gid n-tra
no

3. In step 2, you set location_id to NULL. Create a PL/SQL block that updates the
location_id to 3000 for the new department.
Note: If you successfully completed step 2, continue with step 3a. If not, first execute the
solution script /soln/sol_05.sql. (Task 2 in sol_05.sql)
a. Start the executable block with the BEGIN keyword. Include the UPDATE statement to
set location_id to 3000 for the new department (v_dept_id =280).

BEGIN
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using SQL Statements within a PL/SQL Block


Chapter 5 - Page 5
UPDATE departments SET location_id=3000 WHERE
department_id=280;

b. End the executable block with the END keyword. Terminate the PL/SQL block with “/”
and include a SELECT statement to display the department that you updated.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

END;
/
SELECT * FROM departments WHERE department_id=280;

c. Include a DELETE statement to delete the department that you added.

DELETE FROM departments WHERE department_id=280;

d. Execute and save your script as lab_05_03_soln.sql. The sample output is as


s a
follows:
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using SQL Statements within a PL/SQL Block


Chapter 5 - Page 6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
Practices for o en 6:
Lesson
Writing a @
dControl
t udStructures
s
ra this S
r u ฺ p
Chapter 6
l u s e
i d da to u
d (g nse
r a s a l i ce
r u P able
d a lu sfer
n
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Writing Control Structures


Chapter 6 - Page 1
Practice 6: Writing Control Structures

In this practice, you create PL/SQL blocks that incorporate loops and conditional control
structures. This practice tests your understanding of various IF statements and LOOP
constructs.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

1. Execute the command in the lab_06_01.sql file to create the messages table. Write a
PL/SQL block to insert numbers into the messages table.
a. Insert the numbers 1 through 10, excluding 6 and 8.
b. Commit before the end of the block.
c. Execute a SELECT statement to verify that your PL/SQL block worked.
Result: You should see the following output:

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no
2. Execute the lab_06_02.sql script. This script creates an emp table that is a replica of the
employees table. It alters the emp table to add a new column, stars, of VARCHAR2 data
type and size 50. Create a PL/SQL block that inserts an asterisk in the stars column for
every $1000 of an employee’s salary. Save your script as lab_06_02_soln.sql.
a. In the declarative section of the block, declare a variable v_empno of type
emp.employee_id and initialize it to 176. Declare a variable v_asterisk of type
emp.stars and initialize it to NULL. Create a variable v_sal of type emp.salary.
b. In the executable section, write logic to append an asterisk (*) to the string for every
$1,000 of the salary. For example, if the employee earns $8,000, the string of asterisks
should contain eight asterisks. If the employee earns $12,500, the string of asterisks
should contain 13 asterisks (rounded to the nearest whole number).
c. Update the stars column for the employee with the string of asterisks. Commit before
the end of the block.

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Writing Control Structures


Chapter 6 - Page 2
d. Display the row from the emp table to verify whether your PL/SQL block has executed
successfully.

e. Execute and save your script as lab_06_02_soln.sql. The output is as follows:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Writing Control Structures


Chapter 6 - Page 3
Solution 6: Writing Control Structures
1. Execute the command in the lab_06_01.sql file to create the messages table. Write a
PL/SQL block to insert numbers into the messages table.
a. Insert the numbers 1 through 10, excluding 6 and 8.
b. Commit before the end of the block.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

BEGIN
FOR i in 1..10 LOOP
IF i = 6 or i = 8 THEN
null;
ELSE
INSERT INTO messages(results)
VALUES (i);
END IF;
END LOOP;
s a
COMMIT;
END; ) h a
c o m e ฺ
/
e ฺ i d
r a cl t Gu
c. Execute a SELECT statement to verify that your PL/SQLoblock worked.
n
d @ d e
r a sa s Stu
SELECT * FROM messages;
r u ฺp e thi
d a lu us
( g id se to
Result: You should see the following output:

s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Writing Control Structures


Chapter 6 - Page 4
2. Execute the lab_06_02.sql script. This script creates an emp table that is a replica of the
employees table. It alters the emp table to add a new column, stars, of VARCHAR2 data
type and size 50. Create a PL/SQL block that inserts an asterisk in the stars column for
every $1000 of the employee’s salary. Save your script as lab_06_02_soln.sql.
a. In the declarative section of the block, declare a variable v_empno of type
emp.employee_id and initialize it to 176. Declare a variable v_asterisk of type
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

emp.stars and initialize it to NULL. Create a variable v_sal of type emp.salary.

DECLARE
v_empno emp.employee_id%TYPE := 176;
v_asterisk emp.stars%TYPE := NULL;
v_sal emp.salary%TYPE;

b. In the executable section, write logic to append an asterisk (*) to the string for every
$1,000 of the salary. For example, if the employee earns $8,000, the string of asterisks
a
a s
should contain eight asterisks. If the employee earns $12,500, the string of asterisks
should contain 13 asterisks.
m )h
ฺ c o deฺ
c l e u i
BEGIN
SELECT NVL(ROUND(salary/1000), 0) INTO
a
orv_salent G
FROM emp WHERE employee_id = v_empno;
a d @ t ud
s
ra this S
u ฺ p
ur use
FOR i IN 1..v_sal
LOOP
d a l
v_asterisk :=id
g t
v_asterisk
e o ||'*';
END LOOP; (
d cens
s a
a le li
P
c. Updateuthe stars
r b for the employee with the string of asterisks. Commit before
l u r acolumn
r of thefeblock.
i d da rans
the end

G nUPDATE
o -t
n WHERE employee_id
emp SET stars = v_asterisk
= v_empno;
COMMIT;
END;
/

d. Display the row from the emp table to verify whether your PL/SQL block has executed
successfully.

SELECT employee_id,salary, stars


FROM emp WHERE employee_id =176;

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Writing Control Structures


Chapter 6 - Page 5
e. Execute and save your script as lab_06_02_soln.sql. The output is as follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Writing Control Structures


Chapter 6 - Page 6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
)h a
c m
o deฺ
l e ฺ u i
a c G
Practices for
@ orLessone n t 7:
Working s a S ud
dwithtComposite Data
r a
ฺp e this
Types
r u
lu Chapter
d d a t o us 7
d (gi nse
r a sa lice
r u P able
d a lu sfer
n
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Working with Composite Data Types


Chapter 7 - Page 1
Practice 7: Working with Composite Data Types

Note: If you have executed the code examples for this lesson, make sure that you execute the
following code before starting this practice:
DROP table retired_emps;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

DROP table empl;


1. Write a PL/SQL block to print information about a given country.
a. Declare a PL/SQL record based on the structure of the COUNTRIES table.
b. Declare a variable v_countryid. Assign CA to v_countryid.
c. In the declarative section, use the %ROWTYPE attribute and declare the
v_country_record variable of type countries.
d. In the executable section, get all the information from the COUNTRIES table by using
v_countryid. Display selected information about the country. The sample output is
as follows:
s a
)h a
c m
o deฺ
l e ฺ u i
a c G
@ or ent
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
e. You may want to execute
s a d and c e n the PL/SQL block for countries with the IDs DE, UK,
test
and US. ra ble l i
u
2. Create a PL/SQL P
r each blockato retrievename
the names of some departments from the DEPARTMENTS
table a l uprint f e rdepartment
d d and
n s on the screen, incorporating an associative array.
Ga.i Declare
Save the
n - tra
script as lab_07_02_soln.sql.

nodepartments.department_name.
an INDEX BY table dept_table_type of type
Declare a variable my_dept_table of type
dept_table_type to temporarily store the names of the departments.
b. Declare two variables: f_loop_count and v_deptno of type NUMBER. Assign 10 to
f_loop_count and 0 to v_deptno.
c. Using a loop, retrieve the names of 10 departments and store the names in the
associative array. Start with department_id 10. Increase v_deptno by 10 for every
loop iteration. The following table shows the department_id for which you should
retrieve the department_name.

DEPARTMENT_ID DEPARTMENT_NAME
10 Administration
20 Marketing
30 Purchasing
40 Human Resources
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Working with Composite Data Types


Chapter 7 - Page 2
50 Shipping
60 IT
70 Public Relations
80 Sales
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

90 Executive
100 Finance

d. Using another loop, retrieve the department names from the associative array and
display them.
e. Execute and save your script as lab_07_02_soln.sql. The output is as follows:

s a
)h a
c m
o deฺ
l e ฺ u i
a c G
@ or ent
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u u era
rblock
3. Modify
d a from
the
n s f you created in Task 2 to retrieve all information about each
that
i d
department
Garray - t r a the DEPARTMENTS table and display the information. Use an associative

non
with the INDEX BY table of records method.
a. Load the lab_07_02_soln.sql script.
b. You have declared the associative array to be of type
departments.department_name. Modify the declaration of the associative array to
temporarily store the number, name, and location of all the departments. Use the
%ROWTYPE attribute.
c. Modify the SELECT statement to retrieve all department information currently in the
DEPARTMENTS table and store it in the associative array.
d. Using another loop, retrieve the department information from the associative array and
display the information.

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Working with Composite Data Types


Chapter 7 - Page 3
The sample output is as follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Working with Composite Data Types


Chapter 7 - Page 4
Solution 7: Working with Composite Data Types
1. Write a PL/SQL block to print information about a given country.
a. Declare a PL/SQL record based on the structure of the COUNTRIES table.
b. Declare a variable v_countryid. Assign CA to v_countryid.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

SET SERVEROUTPUT ON

SET VERIFY OFF


DECLARE
v_countryid varchar2(20):= 'CA';

c. In the declarative section, use the %ROWTYPE attribute and declare the
v_country_record variable of type countries.

v_country_record countries%ROWTYPE; s a
)h a
d. In the executable section, get all the information from the COUNTRIES c m ฺ
otable dbyeusing
e ฺ i
v_countryid. Display selected information about the country.
r a cl t Gu
@ o en
BEGIN
s a d
S t ud
SELECT *
ฺ p ra this
INTO v_country_record
l u
ur use
FROM countries a
( g idd se to
WHERE country_id = UPPER(v_countryid);

s a d ('Country
c e n Id: ' ||
ra ble
DBMS_OUTPUT.PUT_LINE
l i
r u P
v_country_record.country_id
a
||

d
'u
a l ' Region:
Country
s f er ' || v_country_record.region_id);
Name: ' || v_country_record.country_name

id -tran
||
GEND;
non
The sample output after performing all the above steps is as follows:

e. You may want to execute and test the PL/SQL block for countries with the IDs DE, UK,
and US.

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Working with Composite Data Types


Chapter 7 - Page 5
2. Create a PL/SQL block to retrieve the names of some departments from the DEPARTMENTS
table and print each department name on the screen, incorporating an associative array.
Save the script as lab_07_02_soln.sql.
a. Declare an INDEX BY table dept_table_type of type
departments.department_name. Declare a variable my_dept_table of type
dept_table_type to temporarily store the names of the departments.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

SET SERVEROUTPUT ON

DECLARE
TYPE dept_table_type is table of
departments.department_name%TYPE
INDEX BY PLS_INTEGER;
my_dept_table dept_table_type;

s a
b. Declare two variables: f_loop_count and v_deptno of type NUMBER. Assign a
) h 10 to
f_loop_count and 0 to v_deptno.
c m
o deฺ
l e ฺ u i
a c G
f_loop_count NUMBER (2):=10;
@ or ent
v_deptno NUMBER (4):=0;
s a d
S t ud
ฺ p ra thand
c. Using a loop, retrieve the names of 10udepartments is store the names in the
r e
lu us 10. Increase v_deptno by 10 for every
associative array. Start with department_id
d a toshows the department_id for which you
( g id stable
iteration of the loop. The following
e
s a d cen
should retrieve the department_name and store in the associative array.

P ra ble li
l u ru fera
d d a n s
DEPARTMENT_ID DEPARTMENT_NAME
Gi n-tra 10 Administration
n o 20 Marketing
30 Purchasing
40 Human Resources
50 Shipping
60 IT
70 Public Relations
80 Sales
90 Executive
100 Finance

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Working with Composite Data Types


Chapter 7 - Page 6
BEGIN
FOR i IN 1..f_loop_count
LOOP
v_deptno:=v_deptno+10;
SELECT department_name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

INTO my_dept_table(i)
FROM departments
WHERE department_id = v_deptno;
END LOOP;

d. Using another loop, retrieve the department names from the associative array and
display them.

FOR i IN 1..f_loop_count
LOOP
DBMS_OUTPUT.PUT_LINE (my_dept_table(i));
s a
END LOOP;
END; ) h a
o m eฺ
e ฺc is asuifollows:
e. Execute and save your script as lab_07_02_soln.sql. The loutput d
o rac nt G
s a d@ tude
ฺ p ra this S
l u ru se
i d da to u
d (g nse
r a s a l i ce
r u P able
d a lu sfer
n
Gid n-tra
no

3. Modify the block that you created in Task 2 to retrieve all information about each
department from the DEPARTMENTS table and display the information. Use an associative
array with the INDEX BY table of records method.
a. Load the lab_07_02_soln.sql script.
b. You have declared the associative array to be of the
departments.department_name type. Modify the declaration of the associative
array to temporarily store the number, name, and location of all the departments. Use
the %ROWTYPE attribute.
SET SERVEROUTPUT ON

DECLARE
TYPE dept_table_type is table of departments%ROWTYPE
INDEX BY PLS_INTEGER;
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Working with Composite Data Types


Chapter 7 - Page 7
my_dept_table dept_table_type;
f_loop_count NUMBER (2):=10;
v_deptno NUMBER (4):=0;

c. Modify the SELECT statement to retrieve all department information currently in the
DEPARTMENTS table and store it in the associative array.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

BEGIN
FOR i IN 1..f_loop_count
LOOP
v_deptno := v_deptno + 10;
SELECT *
INTO my_dept_table(i)
FROM departments
WHERE department_id = v_deptno;
END LOOP;
s a
a
) harray and
c m
d. Using another loop, retrieve the department information from the associative
o deฺ
display the information.
l e ฺ u i
a c G
FOR i IN 1..f_loop_count @ or ent
LOOP
s a d
S t ud
DBMS_OUTPUT.PUT_LINE ('Department
my_dept_table(i).department_id ruฺ
pra Number:
t h is ' ||
|| ' Department Name: a ' lu u s e
idd my_dept_table(i).manager_id
|| my_dept_table(i).department_name
|| ' Manager Id: '||
( g e to
a e s
|| ' Location dId: ' ||nmy_dept_table(i).location_id);
END LOOP; s
ra ble li c
END; P
ru fera
l u
d da output
The isample r a n s
is as follows:
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Working with Composite Data Types


Chapter 7 - Page 8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
)h a
c m
o deฺ
l e ฺ u i
a c G
Practices for
@ orLessone n t 8: Using
Explicits a dCursors
S t ud
ฺ p ra this
l u r u
Chapter
s
8
e
i d da to u
d (g nse
r a s a l i ce
r u P able
d a lu sfer
n
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 1
Practice 8-1: Using Explicit Cursors

In this practice, you perform two exercises:


• First, you use an explicit cursor to process a number of rows from a table and populate
another table with the results by using a cursor FOR loop.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Second, you write a PL/SQL block that processes information with two cursors,
including one that uses a parameter.
1. Create a PL/SQL block to perform the following:
a. In the declarative section, declare and initialize a variable named v_deptno of type
NUMBER. Assign a valid department ID value (see table in step d for values).
b. Declare a cursor named c_emp_cursor, which retrieves the last_name, salary,
and manager_id of employees working in the department specified in v_deptno.
c. In the executable section, use the cursor FOR loop to operate on the data retrieved. If
the salary of the employee is less than 5,000 and if the manager ID is either 101 or
s a
h a
124, display the message “<<last_name>> Due for a raise.” Otherwise, display the
)
message “<<last_name>> Not Due for a raise.”
c o m e ฺ
d. Test the PL/SQL block for the following cases: e ฺ i d
r a cl t Gu
@ o en
Department ID Message
s a d
S t ud
10 Whalen Due for
ฺ p raa raise
t his
r u
luNot Due e
20 Hartstein
Fay id d a o
Not Due tfor
usa for
raise
a raise

50 d (g Not
Weiss n seDue for a raise
a a
s Fripp l e
ic Not Due for a raise
r l e
P abKaufling Not Due for a raise
l u r u er Vollman
d a n s f Not Due for a raise. . .

Gid n-tra
. . .
OConnell Due for a raise
n o Grant Due for a raise
80 Russell Not Due for a raise
Partners Not Due for a raise
Errazuriz Not Due for a raise
Cambrault Not Due for a raise
. . .
Livingston Not Due for a raise
Johnson Not Due for a raise

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 2
2. Next, write a PL/SQL block that declares and uses two cursors—one without a parameter
and one with a parameter. The first cursor retrieves the department number and
department name from the DEPARTMENTS table for all departments whose ID number is
less than 100. The second cursor receives the department number as a parameter, and
retrieves employee details for those who work in that department and whose
employee_id is less than 120.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

a. Declare a cursor c_dept_cursor to retrieve department_id and


department_name for those departments with department_id less than 100. Order
by department_id.
b. Declare another cursor c_emp_cursor that takes the department number as
parameter and retrieves the following data from the EMPLOYEES table: last_name,
job_id, hire_date, and salary of those employees who work in that department,
with employee_id less than 120.
c. Declare variables to hold the values retrieved from each cursor. Use the %TYPE
s a
attribute while declaring variables.
)h a
d. m
Open c_dept_cursor and use a simple loop to fetch values into the variables that
c o deฺ
l e ฺ
are declared. Display the department number and department name. Use the
u i
appropriate cursor attribute to exit the loop. a c G
e. @ or ent
Open c_emp_cursor by passing the current department number as a parameter.
s a d t ud
Start another loop and fetch the values of emp_cursor into variables, and print all the
S
ฺ p
details retrieved from the EMPLOYEES table. ra this
l u
ur use
a
Notes
( g idd se to
s a d cen is already open before opening the cursor.
• Check whether c_emp_cursor
ra blecursor
• Use the appropriate
P li attribute for the exit condition.
• When
l u ru the floop
e racompletes, print a line after you have displayed the details of each
d a
d ran s
department, and close c_emp_cursor.
i
G n-t
f. noEnd the first loop and close c_dept_cursor. Then end the executable section.

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 3
g. Execute the script. The sample output is as follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 4
Solution 8-1: Using Explicit Cursors
In this practice, you perform two exercises:
• First, you use an explicit cursor to process a number of rows from a table and populate
another table with the results by using a cursor FOR loop.
• Second, you write a PL/SQL block that processes information with two cursors,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

including one that uses a parameter.


1. Create a PL/SQL block to perform the following:
a. In the declarative section, declare and initialize a variable named v_deptno of the
NUMBER type. Assign a valid department ID value (see table in step d for values).

DECLARE
v_deptno NUMBER := 10;

s a
b. Declare a cursor named c_emp_cursor, which retrieves last_name, salary, and
manager_id of employees working in the department specified in v_deptno. )h a
c m
o deฺ
l e ฺ u i
a c G
or ent
CURSOR c_emp_cursor IS
SELECT
FROM
last_name, salary,manager_id
employees a d @ t ud
WHERE department_id = v_deptno; s
ra this S
u ฺ p
a l ur use
c. In the executable section, ( g ddthe cursor
iuse e to FOR loop to operate on the data retrieved. If
a d ciseless
the salary of the employee
s nsthan 5,000 and if the manager ID is either 101 or
P a message
124, display rthe
l e li“<<last_name>> Due for a raise.” Otherwise, display the
message
l u f e r ab Not Due for a raise.”
ru “<<last_name>>
i d da rans
GBEGINn-t
no
FOR emp_record IN c_emp_cursor
LOOP
IF emp_record.salary < 5000 AND (emp_record.manager_id=101 OR
emp_record.manager_id=124) THEN
DBMS_OUTPUT.PUT_LINE (emp_record.last_name || ' Due for a
raise');
ELSE
DBMS_OUTPUT.PUT_LINE (emp_record.last_name || ' Not Due for a
raise');
END IF;
END LOOP;
END;

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 5
d. Test the PL/SQL block for the following cases:

Department ID Message
10 Whalen Due for a raise
20 Hartstein Not Due for a raise
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Fay Not Due for a raise


50 Weiss Not Due for a raise
Fripp Not Due for a raise
Kaufling Not Due for a raise
Vollman Not Due for a raise. . .
. . .
OConnell Due for a raise
Grant Due for a raise
80 Russell Not Due for a raise
Partners Not Due for a raise
s a
Errazuriz Not Due for a raise
)h a
Cambrault Not Due for a raise
c m
o deฺ
. . .
l e ฺ u i
a c G
or ent
Livingston Not Due for a raise
Johnson Not Due for a raise
a d @ t ud
s
ra this S
2. Next, write a PL/SQL block that declaresrand u ฺpuses two cursors—one without a parameter
e
and one with a parameter. The first a l u retrieves
cursor s
u the department number and
d d t o
less than 100. The second d (gi receives
department name from the DEPARTMENTS
cursor n s e table
the
for all departments whose ID number is
department number as a parameter, and
s
a le a l i c e
retrieves employee
P rless
details for those who work in that department and whose
employee_id
l u ru ferab
is than 120.
a ancursor
a. dDeclare
d s c_dept_cursor to retrieve department_id and
i -t r a
G department_name for those departments with department_id less than 100. Order
n o n
by department_id.

DECLARE
CURSOR c_dept_cursor IS
SELECT department_id,department_name
FROM departments
WHERE department_id < 100
ORDER BY department_id;

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 6
b. Declare another cursor c_emp_cursor that takes the department number as
parameter and retrieves the following data from the EMPLOYEES table: last_name,
job_id, hire_date, and salary of those employees who work in that department,
with employee_id less than 120.

CURSOR c_emp_cursor(v_deptno NUMBER) IS


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

SELECT last_name,job_id,hire_date,salary
FROM employees
WHERE department_id = v_deptno
AND employee_id < 120;

c. Declare variables to hold the values retrieved from each cursor. Use the %TYPE
attribute while declaring variables.

v_current_deptno departments.department_id%TYPE; s a
v_current_dname departments.department_name%TYPE;
)h a
v_ename employees.last_name%TYPE;
c m
o deฺ
v_job employees.job_id%TYPE;
l e ฺ u i
a c G
or ent
v_hiredate employees.hire_date%TYPE;
v_sal employees.salary%TYPE;
a d @ t ud
s
ra this S
u ฺ
r loopp
d. Open c_dept_cursor and use a
a l usimple u s eto fetch values into the variables that
( g
appropriate cursor attributeidtodexitsthe
are declared. Display the department
e o and department name. Use the
number
tloop.
s a d cen
BEGIN P ra ble li
l u ru fera
OPEN c_dept_cursor;

i d da LOOP r a n s
G n-t v_current_dname;
FETCH c_dept_cursor INTO v_current_deptno,
no EXIT WHEN c_dept_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE ('Department Number : ' ||
v_current_deptno || ' Department Name : ' ||
v_current_dname);

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 7
e. Open c_emp_cursor by passing the current department number as a parameter.
Start another loop and fetch the values of emp_cursor into variables, and print all the
details retrieved from the EMPLOYEES table.

Notes
• Check whether c_emp_cursor is already open before opening the cursor.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Use the appropriate cursor attribute for the exit condition.


• When the loop completes, print a line after you have displayed the details of each
department, and close c_emp_cursor.

IF c_emp_cursor%ISOPEN THEN
CLOSE c_emp_cursor;
END IF;
OPEN c_emp_cursor (v_current_deptno);
LOOP
s a
FETCH c_emp_cursor INTO v_ename,v_job,v_hiredate,v_sal;
EXIT WHEN c_emp_cursor%NOTFOUND; ) h a
c o m e ฺ
DBMS_OUTPUT.PUT_LINE (v_ename || ' ' || v_job
e ฺ i d
|| ' ' || v_hiredate || ' ' || v_sal);
r a cl t Gu
END LOOP;
@ o en
s a d
S t ud
DBMS_OUTPUT.PUT_LINE('--------------------------------------------
--------------------------------------------');
CLOSE c_emp_cursor; ฺ p ra this
l u
ur use
a
( g idd se to
s
f. End the first loop a
and e n
d closecc_dept_cursor. Then end the executable section.
r a l i
r u P able
d
END
a lu LOOP;s f er
id -tran
CLOSE
GEND;
c_dept_cursor;

non

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 8
g. Execute the script. The sample output is as follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 9
Practice 8-2: Using Explicit Cursors: Optional
If you have time, complete the following optional practice. Here, create a PL/SQL block that
uses an explicit cursor to determine the top n salaries of employees.
1. Run the lab_08-02.sql script to create the TOP_SALARIES table for storing the salaries
of the employees.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

2. In the declarative section, declare the v_num variable of the NUMBER type that holds a
number n, representing the number of top n earners from the employees table. For
example, to view the top five salaries, enter 5. Declare another variable v_sal of type
employees.salary. Declare a cursor, c_emp_cursor, which retrieves the salaries of
employees in descending order. Remember that the salaries should not be duplicated.
3. In the executable section, open the loop, fetch the top n salaries, and then insert them into
the TOP_SALARIES table. You can use a simple loop to operate on the data. Also, try and
use the %ROWCOUNT and %FOUND attributes for the exit condition.
Note: Make sure that you add an exit condition to avoid having an infinite loop.
4. After inserting data into the TOP_SALARIES table, display the rows with a SELECT s a
)h a
statement. The output shown represents the five highest salaries in the EMPLOYEES table.
c m
o deฺ
l e ฺ u i
a c G
@ or ent
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru of special
5. Test a variety f e ra cases such as v_num = 0 or where v_num is greater than the
a s
idd -oftremployees
Gnumber an in the EMPLOYEES table. Empty the TOP_SALARIES table after each
test. n
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 10
Solution 8-2: Using Explicit Cursors: Optional
If you have time, complete the following optional exercise. Here, create a PL/SQL block that
uses an explicit cursor to determine the top n salaries of employees.

1. Execute the lab_08_02.sql script to create a new table, TOP_SALARIES, for storing the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

salaries of the employees.


2. In the declarative section, declare a variable v_num of type NUMBER that holds a number n,
representing the number of top n earners from the EMPLOYEES table. For example, to view
the top five salaries, enter 5. Declare another variable v_sal of type employees.salary.
Declare a cursor, c_emp_cursor, which retrieves the salaries of employees in descending
order. Remember that the salaries should not be duplicated.

DECLARE
v_num NUMBER(3) := 5;
v_sal employees.salary%TYPE;
s a
CURSOR c_emp_cursor IS
)h a
SELECT salary
c m
o deฺ
FROM employees
l e ฺ u i
ORDER BY salary DESC;
a c G
@ or ent
3. In the executable section, open the loop, fetch the top a d then insert them into
dn salaries,tuand
s S
raloop ttohoperate
the TOP_SALARIES table. You can use a simple
u ฺ p is on the data. Also, try and
use the %ROWCOUNT and %FOUND attributes
Note: Make sure that you add an d a
exit
ur utosavoid
for
lcondition the exit
e condition.
having an infinite loop.
i d t o
d (g nse
BEGIN
r a s a l i ce
u P ableINTO v_sal;
OPEN c_emp_cursor;
FETCH rc_emp_cursor
d a s er
lu c_emp_cursor%ROWCOUNT
f
i d
WHILE
r a n <= v_num AND c_emp_cursor%FOUND LOOP
G n-t INSERT INTO top_salaries (salary)
noFETCH c_emp_cursor INTO v_sal;
VALUES (v_sal);

END LOOP;
CLOSE c_emp_cursor;
END;
4. After inserting data into the TOP_SALARIES table, display the rows with a SELECT
statement. The output shown represents the five highest salaries in the EMPLOYEES table.

/
SELECT * FROM top_salaries;

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 11
The sample output is as follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

5. Test a variety of special cases such as v_num = 0 or where v_num is greater than the
number of employees in the EMPLOYEES table. Empty the TOP_SALARIES table after each
test.

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Explicit Cursors


Chapter 8 - Page 12
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
Practices for o en 9:
Lesson
Handling a @ t ud
d Exceptions
s
ra this S
r u ฺ p
Chapter 9
l u s e
i d da to u
d (g nse
r a s a l i ce
r u P able
d a lu sfer
n
Gid n-tra
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Handling Exceptions


Chapter 9 - Page 1
Practice 9-1: Handling Predefined Exceptions

In this practice, you write a PL/SQL block that applies a predefined exception to process only
one record at a time. The PL/SQL block selects the name of the employee with a given salary
value.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

1. Execute the command in the lab_06_01.sql file to re-create the messages table.
2. In the declarative section, declare two variables: v_ename of type
employees.last_name and v_emp_sal of type employees.salary. Initialize the latter
to 6000.
3. In the executable section, retrieve the last names of employees whose salaries are equal to
the value in v_emp_sal. If the salary entered returns only one row, insert the employee’s
name and salary amount into the MESSAGES table.
Note: Do not use explicit cursors.
4. If the salary entered does not return any rows, handle the exception with an appropriate
s
exception handler and insert the message “No employee with a salary of <salary>” into the a
MESSAGES table. ) h a
5. c o m e ฺ
If the salary entered returns multiple rows, handle the exception with an appropriate
e ฺ i d
r a cl t Gu
exception handler and insert the message “More than one employee with a salary of
<salary>” into the MESSAGES table.
@ o en
6.
s a d
S t ud
Handle any other exception with an appropriate exception handler and insert the message

ฺ p ra this
“Some other error occurred” into the MESSAGES table.
7. u
ur use
Display the rows from the MESSAGES table to check whether the PL/SQL block has
l
a
executed successfully. The output is as follows:
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

8. Change the initialized value of v_emp_sal to 2000 and re-execute. The output is as
follows:

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Handling Exceptions


Chapter 9 - Page 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Handling Exceptions


Chapter 9 - Page 3
Solution 9-1: Handling Predefined Exceptions
In this practice, you write a PL/SQL block that applies a predefined exception to process only
one record at a time. The PL/SQL block selects the name of the employee with a given salary
value.

1. Execute the command in the lab_06_01.sql file to re-create the MESSAGES table.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

2. In the declarative section, declare two variables: v_ename of type


employees.last_name and v_emp_sal of type employees.salary. Initialize the latter
to 6000.

DECLARE
v_ename employees.last_name%TYPE;
v_emp_sal employees.salary%TYPE := 6000;

3. a
In the executable section, retrieve the last names of employees whose salaries are equal to
s
)h a
the value in v_emp_sal. If the salary entered returns only one row, insert the employee’s
name and the salary amount into the MESSAGES table.
c m
o deฺ
Note: Do not use explicit cursors. l e ฺ u i
a c G
@ or ent
BEGIN
s a d
S t ud
SELECT last_name
ฺ p ra this
INTO
FROM
v_ename
employees l u
ur use
a
WHERE
INSERT INTO messages ( g idd se to
salary = v_emp_sal;
(results)
VALUES (v_enamea||
s d ' -c'en|| v_emp_sal);
P ra ble li
u ruentered
4. If the salary
l f e a not return any rows, handle the exception with an appropriate
rdoes
a s
idd -trhandler
exception
GMESSAGES
n and insert the message “No employee with a salary of <salary>” into the
atable.
non
EXCEPTION
WHEN no_data_found THEN
INSERT INTO messages (results)
VALUES ('No employee with a salary of '||
TO_CHAR(v_emp_sal));

5. If the salary entered returns multiple rows, handle the exception with an appropriate
exception handler and insert the message “More than one employee with a salary of
<salary>” into the MESSAGES table.

WHEN too_many_rows THEN


INSERT INTO messages (results)
VALUES ('More than one employee with a salary of '||
TO_CHAR(v_emp_sal));

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Handling Exceptions


Chapter 9 - Page 4
6. Handle any other exception with an appropriate exception handler and insert the message
“Some other error occurred” into the MESSAGES table.

WHEN others THEN


INSERT INTO messages (results)
VALUES ('Some other error occurred.');
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

END;

7. Display the rows from the MESSAGES table to check whether the PL/SQL block has
executed successfully.
/
SELECT * FROM messages;

The output is as follows:

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
8. Changelu ruinitialized
the f e ravalue of v_emp_sal to 2000 and re-execute. The output is as
d a n s
Gid n-tra
follows:

no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Handling Exceptions


Chapter 9 - Page 5
Practice 9-2: Handling Standard Oracle Server Exceptions
In this practice, you write a PL/SQL block that declares an exception for the Oracle Server error
ORA-02292 (integrity constraint violated – child record found). The block
tests for the exception and outputs the error message.
1. In the declarative section, declare an exception e_childrecord_exists. Associate the
declared exception with the standard Oracle Server error –02292.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

2. In the executable section, display “Deleting department 40....” Include a DELETE statement
to delete the department with the department_id 40.
3. Include an exception section to handle the e_childrecord_exists exception and
display the appropriate message.

The sample output is as follows:

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Handling Exceptions


Chapter 9 - Page 6
Solution 9-2: Handling Standard Oracle Server Exceptions
In this practice, you write a PL/SQL block that declares an exception for the Oracle Server error
ORA-02292 (integrity constraint violated – child record found). The block
tests for the exception and outputs the error message.
1. In the declarative section, declare an exception e_childrecord_exists. Associate the
declared exception with the standard Oracle Server error –02292.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

SET SERVEROUTPUT ON
DECLARE
e_childrecord_exists EXCEPTION;
PRAGMA EXCEPTION_INIT(e_childrecord_exists, -02292);

2. In the executable section, display “Deleting department 40....” Include a DELETE statement
to delete the department with department_id 40.

s a
BEGIN
)h a
DBMS_OUTPUT.PUT_LINE(' Deleting department 40........');
c m
o deฺ
delete from departments where department_id=40;
l e ฺ u i
a c G
@ or enexception
3. Include an exception section to handle the e_childrecord_exists
t and
a d t u d
display the appropriate message.
r a s sS
r u ฺ e thi
p
EXCEPTION
d a luTHEN us
WHEN e_childrecord_exists
( g id Cannot
e todelete this department. There are
DBMS_OUTPUT.PUT_LINE('
employees in thisadepartment
s d cens(child records exist.) ');
END;
P ra ble li
l u ru fera
i d da output
The sample
r a nissas follows:
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Handling Exceptions


Chapter 9 - Page 7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Handling Exceptions


Chapter 9 - Page 8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
Practices for o en 10:
Lesson
Introducing
a @ t ud
d Stored
s S
ra this and Functions
u ฺ p
Procedures
a l ur use
( g idd se Chapter
to 10
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Introducing Stored Procedures and Functions


Chapter 10 - Page 1
Practice 10: Creating and Using Stored Procedures

Note: If you have executed the code examples for this lesson, make sure that you execute the
following code before starting this practice:
DROP table dept;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

DROP procedure add_dept;


DROP function check_sal;
In this practice, you modify existing scripts to create and use stored procedures.
1. Open the sol_03.sql script from the /home/oracle/labs/plsf/soln/ folder. Copy
the code under task 4 into a new worksheet.
SET SERVEROUTPUT ON

DECLARE
v_today DATE:=SYSDATE;
s a
v_tomorrow v_today%TYPE;
BEGIN ) h a
c o m e ฺ
v_tomorrow:=v_today +1;
e ฺ i d
DBMS_OUTPUT.PUT_LINE(' Hello World ');
r a cl t Gu
DBMS_OUTPUT.PUT_LINE('TODAY IS : '|| v_today);
@ o en
s a d
DBMS_OUTPUT.PUT_LINE('TOMORROW IS : ' || v_tomorrow);
S t ud
END;
ฺ p ra this
l u
ur ublock s e to a procedure called greet.
a. Modify the script to convert the a anonymous
d to ON command.)
idSERVEROUTPUT
(Hint: Also remove the SET
( g s e
nprocedure.
b. Execute the scriptatodcreate the e The output results should be as follows:
r a s l i c
r u P able
d a lu sfer
n
Gid n-tra
no
c. Save this script as lab_10_01_soln.sql.
d. Click the Clear button to clear the workspace.
e. Create and execute an anonymous block to invoke the greet procedure.
(Hint: Ensure that you enable SERVEROUTPUT at the beginning of the block.)

The output should be similar to the following:

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Introducing Stored Procedures and Functions


Chapter 10 - Page 2
2. Modify the lab_10_01_soln.sql script as follows:
a. Drop the greet procedure by issuing the following command:

DROP PROCEDURE greet;


b. Modify the procedure to accept an argument of type VARCHAR2. Call the argument
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

p_name.
c. Print Hello <name> (that is, the contents of the argument) instead of printing Hello
World.
d. Save your script as lab_10_02_soln.sql.
e. Execute the script to create the procedure. The output results should be as follows:

s a
) h a
c o m e ฺ
l e ฺ
f. Create and execute an anonymous block to invoke the greetcprocedure i d
uwith a
r a
o en
parameter value. The block should also produce the output. t G
a d @ t ud
s
ra this S
u ฺ p
The sample output should be similar to the following:

a l ur use
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Introducing Stored Procedures and Functions


Chapter 10 - Page 3
Solution 10: Creating and Using Stored Procedures
In this practice, you modify existing scripts to create and use stored procedures.
1. Open the sol_03.sql script from the /home/oracle/labs/plsf/soln/ folder. Copy
the code under task 4 into a new worksheet.
SET SERVEROUTPUT ON
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

DECLARE
v_today DATE:=SYSDATE;
v_tomorrow v_today%TYPE;
BEGIN
v_tomorrow:=v_today +1;
DBMS_OUTPUT.PUT_LINE(' Hello World ');
DBMS_OUTPUT.PUT_LINE('TODAY IS : '|| v_today);
DBMS_OUTPUT.PUT_LINE('TOMORROW IS : ' || v_tomorrow);
END;
s a
a
) h(Hint:
c m
a. Modify the script to convert the anonymous block to a procedure called greet.
o deฺ
Also remove the SET SERVEROUTPUT ON command.)
l e ฺ u i
a c G
@ or ent
CREATE PROCEDURE greet IS
s a d
S t ud
ra this
v_today DATE:=SYSDATE;
v_tomorrow v_today%TYPE;
u ฺ p
...
a l ur use
( g ddprocedure.
ithe e to The output results should be as follows:
s a d cens
b. Execute the script to create

P ra ble li
l u ru fera
i d da rans
G n-t
no
c. Save this script as lab_10_01_soln.sql.
d. Click the Clear button to clear the workspace.
e. Create and execute an anonymous block to invoke the greet procedure. (Hint: Ensure
that you enable SERVEROUTPUT at the beginning of the block.)

SET SERVEROUTPUT ON

BEGIN
greet;
END;

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Introducing Stored Procedures and Functions


Chapter 10 - Page 4
The output should be similar to the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

2. Modify the lab_10_01_soln.sql script as follows:


a. Drop the greet procedure by issuing the following command:

DROP PROCEDURE greet; s a


) h a
b. Modify the procedure to accept an argument of type VARCHAR2. Callc o m
the e
argumentฺ
e ฺ i d
p_name.
r a cl t Gu
CREATE PROCEDURE greet(p_name VARCHAR2)aIS d @o tuden
r a s sS
v_today DATE:=SYSDATE;
v_tomorrow v_today%TYPE; r u ฺ e thi
p
d a lu us
g
c. Print Hello <name> instead
( e toHello World.
id of printing
s a d cens
BEGIN P ra ble li
u ru fera
v_tomorrow:=v_today
l +1;
d a
d ran s
DBMS_OUTPUT.PUT_LINE(' Hello '|| p_name);
i
G n-t
...
n o
d. Save your script as lab_10_02_soln.sql.
e. Execute the script to create the procedure. The output results should be as follows:

f. Create and execute an anonymous block to invoke the greet procedure with a
parameter value. The block should also produce the output.

SET SERVEROUTPUT ON;


BEGIN
greet('Nancy');
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Introducing Stored Procedures and Functions


Chapter 10 - Page 5
END;

The sample output should be similar to the following:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
e ฺ i d
r a cl t Gu
@ o en
s a d
S t ud
ฺ p ra this
l u
ur use
a
( g idd se to
s a d cen
P ra ble li
l u ru fera
i d da rans
G n-t
no

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Introducing Stored Procedures and Functions


Chapter 10 - Page 6

You might also like