+ All Categories
Home > Documents > DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code...

DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code...

Date post: 16-Aug-2020
Category:
Upload: others
View: 7 times
Download: 0 times
Share this document with a friend
148
DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover
Transcript
Page 1: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

V2.0.0.1

cover

���

Front cover

DB2 Stored ProceduresProgramming Workshop (Course Code CF71)

Student ExercisesERC 4.0

IBM Certified Course Material

Page 2: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Trademarks

IBM® is a registered trademark of International Business Machines Corporation.

The following are trademarks of International Business Machines Corporation in the United States, or other countries, or both:

Java and all-Java based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.

Microsoft, Windows and Windows NT are trademarks of Microsoft Corporation in the United States, other countries, or both

Intel is a trademark of Intel Corporation in the United States, other countries, or both

UNIX is a registered trademark of The Open Group in the United States and other countries

Linux is a registered trademark of Linus Torvalds in the United States and other countries.

Other company, product, and service names may be trademarks or service marks of others.

AIX DB2 DB2 Universal DatabaseiSeries OS/2 OS/390RACF SP SQL/DSSystem/36 VisualAge z/OS

The information contained in this document has not been submitted to any formal IBM test and is distributed on an “as is” basis withoutany warranty either express or implied. The use of this information or the implementation of any of these techniques is a customerresponsibility and depends on the customer’s ability to evaluate and integrate them into the customer’s operational environment. Whileeach item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results willresult elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.

© Copyright International Business Machines Corporation 1996, 2003. All rights reserved.This document may not be reproduced in whole or in part without the prior written permission of IBM.Note to U.S. Government Users — Documentation related to restricted rights — Use, duplication or disclosure is subject to restrictionsset forth in GSA ADP Schedule Contract with IBM Corp.

May 2003 Edition

Page 3: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

TOC

Contents

Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

Exercises Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Lab Introduction: About This Lab Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

Exercise 1. The Exercise Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1Exercise Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

Section 1: Exploring the Exercise Environment . . . . . . . . . . . . . . . . . . . . . . . . 1-2Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5

Section 1: Exploring the Exercise Environment . . . . . . . . . . . . . . . . . . . . . . . . 1-5

Exercise 2. The DB2 Development Center . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1Exercise Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2

Section 1: Register a New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2Section 2: Stored Procedure with CREATE TABLE . . . . . . . . . . . . . . . . . . . . . 2-4Section 3: Stored Procedure Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6

Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7Section 1: Register a New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7Section 2: Stored Procedure with CREATE TABLE . . . . . . . . . . . . . . . . . . . . . 2-9Section 3: Stored Procedure Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11

Exercise 3. SQL Procedure Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1Exercise Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3

Section 1: CASE Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3Section 2: IF Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5Section 3: REPEAT Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7Section 4: LOOP Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8Section 5: Median Salary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9Section 6: Creating a Result Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10Section 7: Stored Procedure Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12

Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13Section 1: CASE Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13Section 2: IF Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-16Section 3: REPEAT Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-18Section 4: LOOP Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-20Section 5: Median Salary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22Section 6: Creating a Result Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-24Section 7: Stored Procedure Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . 3-26

Exercise 4. Building Java Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1Exercise Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3

Section 1: JDBC Stored Procedure Returning Result Set . . . . . . . . . . . . . . . . 4-3

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Contents iii

Page 4: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 2: SQLJ Stored Procedure Returning Choice of Results Sets . . . . . . . 4-5Section 3: JDBC Stored Procedure Returning Choice of Result Sets . . . . . . . . 4-8Section 4: SQLJ Stored Procedure Returning Choice of COUNTs . . . . . . . . . 4-11Section 5: JDBC Stored Procedure Returning Choice of COUNTs . . . . . . . . . 4-14Section 6: Generate JDBC Stored Procedure for Further Coding . . . . . . . . . . 4-17Section 7: Stored Procedure Source Code. . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18

Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-19Section 1: JDBC Stored Procedure Returning Result Set. . . . . . . . . . . . . . . . 4-19Section 2: SQLJ Stored Procedure Returning Choice of Results Sets . . . . . . 4-21Section 3: JDBC Stored Procedure Returning Choice of Result Sets . . . . . . . 4-24Section 4: SQLJ Stored Procedure Returning Choice of COUNTs . . . . . . . . . 4-27Section 5: JDBC Stored Procedure Returning Choice of COUNTs . . . . . . . . . 4-30Section 6: Generate JDBC Stored Procedure for Further Coding . . . . . . . . . . 4-33Section 7: Stored Procedure Source Code. . . . . . . . . . . . . . . . . . . . . . . . . . . 4-34

Exercise 5. Calling Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-1Exercise Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-2

Section 1: CALL with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2Section 2: Processing a Result Set from a CALL . . . . . . . . . . . . . . . . . . . . . . . 5-4Section 3: Stored Procedure Source Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6

Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-7Section 1: CALL with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7Section 2: Processing a Result Set from a CALL . . . . . . . . . . . . . . . . . . . . . . . 5-9Section 3: Stored Procedure Source Code. . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11

Exercise 6. Create Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-1Exercise Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-3

Section 1: Register Previously Defined Java Stored Procedure . . . . . . . . . . . . 6-3Section 2: Import Previously Defined SQL Procedure Language Stored Procedure 6-5Section 3: Import SQL Procedure Language Stored Procedure Source Code . 6-7Section 4: Deployment of SQL Procedure Language Stored Procedure . . . . . . 6-8

Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-9Section 1: Register Previously Defined Java Stored Procedure . . . . . . . . . . . . 6-9Section 2: Import Previously Defined SQL Procedure Language Stored Procedure 6-11Section 3: Import SQL Procedure Language Stored Procedure Source Code 6-13Section 4: Deployment of SQL Procedure Language Stored Procedure . . . . . 6-14

Exercise 7. Debugging Stored Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-1Exercise Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-2

Section 1: Debugging an SQL Stored Procedure . . . . . . . . . . . . . . . . . . . . . . . 7-2Section 2: Debugging a Java Stored Procedure . . . . . . . . . . . . . . . . . . . . . . . . 7-4

Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-6Section 1: Debugging an SQL Stored Procedure . . . . . . . . . . . . . . . . . . . . . . . 7-6

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

iv Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 5: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

TOC

Section 2: Debugging a Java Stored Procedure . . . . . . . . . . . . . . . . . . . . . . . 7-8

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Contents v

Page 6: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

vi Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 7: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

TMK

Trademarks

The reader should recognize that the following terms, which appear in the content of this training document, are official trademarks of IBM or other companies:

IBM® is a registered trademark of International Business Machines Corporation.

The following are trademarks of International Business Machines Corporation in the United States, or other countries, or both:

Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.

Microsoft, Windows and Windows NT are trademarks of Microsoft Corporation in the United States, other countries, or both.

Intel is a trademark of Intel Corporation in the United States, other countries, or both.

UNIX is a registered trademark of The Open Group in the United States and other countries.

Linux is a registered trademark of Linus Torvalds in the United States and other countries.

Other company, product and service names may be trademarks or service marks of others.

AIX® DB2® DB2 Universal Database™iSeries™ OS/2® OS/390®RACF® SP™ SQL/DS™System/36™ VisualAge® z/OS™

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Trademarks vii

Page 8: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

viii Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 9: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

pref

Exercises Description

These lab exercises were designed to have the student run on a workstation with Windows 2000 and DB2/UDB for NT V8 installed.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercises Description ix

Page 10: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

x Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 11: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

pref

Lab Introduction: About This Lab Guide

Before you start:

For all labs, ensure that you are logged in to the system using ADMIN as the user ID with a password of ADMIN.

About code segments:

Because the width of a line of these printed labs is restricted by the physical size of the paper and font, many lines of code in the segments presented cannot fit on a single printed line. These lines of code are split into two or more printed lines. When entering these split lines, type them as a single line of code.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Lab Introduction: About This Lab Guide xi

Page 12: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

xii Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 13: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise 1. The Exercise Environment

What This Exercise Is About

This exercise provides an opportunity for the students to examine the lab exercise environment, DB2 UDB for Windows, by using some of the database manager's provided graphical user interfaces.

What You Should Be Able to Do

At the end of the lab, you should be able to:

• Start the DB2 Control Center application • Start the DB2 Command Center application • List the objects associated with the lab exercise database,

SAMPLE • Limit the objects by establishing a view of a subset of objects in the

database • List the tables in the SAMPLE database • Display the contents of SAMPLE database tables that will be used

in the labs

Introduction

This lab consists of one section.

• Section 1: Exploring the Exercise Environment

In Section 1, you will maneuver through the DB2 supplied Control Center and Command Center to list objects in the SAMPLE database and display the contents of two of the SAMPLE database tables, ORG and STAFF.

Requirements

• Basic understanding of navigating through a Windows desktop.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 1. The Exercise Environment 1-1

Page 14: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Exercise Instructions

The lab solutions can be found in “Exercise Solutions” on page 1-5.

Annotation convention: When your instruction contains the word click, you may see a symbol ->. This means that the first thing you click will result in a pop-up or drop-down selection. For example: Click START -> PROGRAMS first, click START, then click PROGRAMS.

Note: Anytime that you are going to close your Development Center, be sure to save your project. There is not an automatic save.

Note: DB2 UDB V8 was installed on the workstation prior to class start.

Section 1: Exploring the Exercise Environment

In this section, you will be examining the SAMPLE database and some of the objects in the SAMPLE database using the Control Center and Command Center user interfaces.

Note: DB2 UDB V8 was installed on the workstation prior to class start.

__ 1. Start DB2 Control Center.

• Click Windows Start -> Programs -> IBM DB2 -> General Administration Tools ->Control Center.

• This will show the DB2 instance we will work with for our class exercises.

__ 2. In the Control Center window, expand the tree structure labelled DB2...

• Click + DB2... -> + Instances -> + DB2 -> + Databases -> + SAMPLE. • This will show all objects associated with the SAMPLE database that will be used

during our class exercises.

__ 3. Click Tables folder icon.

• This will show all tables in the SAMPLE database.

__ 4. Limit your list of tables to exclude those in SCHEMA: SYSIBM.

• The command list at the top of the Control Center window contains the command View.

• Click View -> Filter. • In Filter window under Comparison for Schema: Click drop-down arrow -> Not in • Under Values for Schema, type SYSIBM (uppercase) • Make sure that Enable filter is checked. • Click OK button to process.

__ 5. Examine ADMIN.ORG.

• Double-click icon next to ORG. • In 'Alter Table - ORG' window, click Columns tab.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-2 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 15: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

What columns are found for ORG?

________________________________________________________________

________________________________________________________________

• Click Cancel to exit Alter Table - ORG window.

__ 6. Examine ADMIN.STAFF.

• Double-click icon next to STAFF. • In Alter Table - STAFF window, click Columns tab.

What columns are found for STAFF?

________________________________________________________________

________________________________________________________________

• Click Cancel to exit Alter Table - STAFF window.

__ 7. Let's connect to the SAMPLE database for a quick look at our tables' contents.

• The command list at the top of the Control Center window contains the command Tools.

• Click Tools -> Command Center. • In Command Center window, click Interactive tab (below icons line). • In the Interactive tab Command window: Type in: Connect to SAMPLE • Execute this DB2 command Click Gears icon on the icons line. • The window below the Command window should show the following:

connect to sample ; ---------------------------------------------------- Database Connection Information Database server = DB2/NT 8.1.0 SQL authorization ID = ADMIN Local database alias = SAMPLE

__ 8. Let's look at the ORG table.

• Click SQL ASSIST button. • Select FROM (Source tables). • Select ORG table by clicking icon next to ORG under ADMIN. • Click > button to move ORG to Selected tables. • SQL statement should read: SELECT * FROM ADMIN.ORG. AS ORG • Click Run button.

How many rows are there currently in table ORG?

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 1. The Exercise Environment 1-3

Page 16: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

What are the DEPTNUMB values in ORG at this time?

________________________________________________________________

________________________________________________________________

• Click OK to return to SQL Assist window. • Click OK to return to Command Center window.

__ 9. Let's look at the STAFF table.

• Click SQL ASSIST button. • Select FROM (Source tables). • Select the ORG table in the Selected tables section and click the < button to

remove it. • Select STAFF table by clicking the icon next to STAFF under ADMIN. • Click > button to move STAFF to Selected tables. • SQL statement should read: SELECT * FROM ADMIN.STAFF AS STAFF. • Click Run button.

How many rows does STAFF currently consist of?

________________________________________________________________

________________________________________________________________

Which employee has the highest value for YEARS in the STAFF table?

________________________________________________________________

________________________________________________________________

Is this employee the highest salaried employee?

________________________________________________________________

________________________________________________________________

• Click OK to return to SQL Assist window. • Click OK to return to Command Center window.

__ 10. Minimize the Command Center window.

This completes the last section of this exercise.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-4 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 17: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise Solutions

Section 1: Exploring the Exercise Environment

In this section, you will be examining the SAMPLE database and some of the objects in the SAMPLE database using the Control Center and Command Center user interfaces.

Note: Anytime that you are going to close your Development Center, be sure to save your project. There is not an automatic save.

Note: DB2 UDB V8 was installed on the workstation prior to class start.

__ 1. Start DB2 Control Center.

• Click Windows START -> PROGRAMS -> IBM DB2 -> CONTROL CENTER. • This will show the DB2 instance we will work with for our class exercises.

__ 2. In the Control Center window, expand the tree structure labelled DB2...

• Click + DB2... -> + Instances -> + DB2 -> + Databases -> + SAMPLE. • This will show all objects associated with the SAMPLE database that will be used

during our class exercises.

__ 3. Click Tables folder icon.

• This will show all tables in the SAMPLE database.

__ 4. Limit your list of tables to those in your SCHEMA: ADMIN.

• The command list at the top of the Control Center window contains the command View.

• Click View -> Filter. • In Filter window under Comparison for Schema: Click drop-down arrow -> Equal

to • Under Values for Schema, type ADMIN. • Click OK button to process.

__ 5. Examine ADMIN.ORG.

• Double-click icon next to ORG. • In 'Alter Table - ORG' window, click Columns tab.

What columns are found for ORG?

DEPTNUMB, DEPTNAME, MANAGER, DIVISION, LOCATION

• Click Cancel to exit Alter Table - ORG window.

__ 6. Examine ADMIN.STAFF.

• Double-click icon next to STAFF. • In Alter Table - STAFF window, click Columns tab.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 1. The Exercise Environment 1-5

Page 18: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

What columns are found for STAFF?

ID, NAME, DEPT, JOB, YEARS, SALARY, COMM

• Click Cancel to exit Alter Table - STAFF window.

__ 7. Let's connect to the SAMPLE database for a quick look at our tables' contents.

• The command list at the top of the Control Center window contains the command Tools.

• Click Tools -> Command Center. • In Command Center window, click Interactive tab (below icons line). • In the Interactive tab Command window: Type in: Connect to SAMPLE • Execute this DB2 command Click Gears icon on the icons line. • The window below the Command window should show the following:

connect to sample ; ------------------------------------------------- Database Connection Information Database server = DB2/NT 8.1.0 SQL authorization ID = ADMIN Local database alias = SAMPLE

__ 8. Let's look at the ORG table.

• Click SQL ASSIST button. • Select ORG table by clicking icon next to ORG under ADMIN. • Click > button to move ORG to Selected tables. • Click Review tab in the SQL Assist window. • SQL statement should read: SELECT * FROM ADMIN.ORG. • Click Run button.

How many rows are there currently in table ORG?

ADMIN.ORG has 8 rows

What are the DEPTNUMB values in ORG at this time?

DEPTNUMB contains: 10, 15, 20, 38, 42, 51, 66, 84

• Click OK to return to SQL Assist window. • Click OK to return to Command Center window.

__ 9. Let's look at the STAFF table.

• Click SQL ASSIST button. • Select STAFF table by clicking the icon next to STAFF under ADMIN. • Click > button to move STAFF to Selected tables. • Click Review tab in the SQL Assist window. • SQL statement should read: SELECT * FROM ADMIN.STAFF. • Click Run button.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-6 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 19: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

How many rows does STAFF currently consist of?

ADMIN.STAFF has 35 rows

Which employee has the highest value for YEARS in the STAFF table?

Graham, employee ID 310

Is this employee the highest salaried employee?

No, Graham is not the highest salaried employee.

• Click OK to return to SQL Assist window. • Click OK to return to Command Center window.

__ 10. Minimize the Command Center window.

This completes the last section of this exercise.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 1. The Exercise Environment 1-7

Page 20: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-8 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 21: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise 2. The DB2 Development Center

What This Exercise Is About

This exercise will have the students create stored procedures using the DB2 Development Center.

What You Should Be Able to Do

At the end of the lab, you should be able to:

• Maneuver through the Command Center and DB2 Development Center user interfaces

• Register a new project within the DB2 Development Center • Create a simple stored procedure using SQL Assist • Create a stored procedure without SQL Assist

Introduction

This exercise has several sections.

• Section 1: Registering a new project and creating a stored procedure

• Section 2: Using a stored procedure to create tables • Section 3: Stored procedure source code listings

In Section 1, you will register a project with the DB2 Development Center. After setting up a project, you will create a simple stored procedure using SQL Assist to SELECT from a table.

In Section 2, you will create a stored procedure that will use SQL to create tables and load values into those tables.

Section 3 provides a listing of the stored procedures source.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 2. The DB2 Development Center 2-1

Page 22: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Exercise Instructions

The lab solutions can be found in “Exercise Solutions” on page 2-7.

Section 1: Register a New Project

__ 1. Start the DB2 Development Center.

• Starting with the WIN/NT Start icon (lower left on DESKTOP): Click Start ->Programs ->IBM DB2 ->Development Tools->Development Center.

• If the Launch Pad is displayed, close it. (You might want to check ‘Do not show this again’).

• Register a new project with the DB2 Development Center. • In IBM DB2 Development Center window menu: Click Project->New Project. • Set the following fields as indicated:

- Project name: CF71 - Project path: x:\CF71_Project (where x is the your drive letter. This would be

the ‘D’ drive if you have one, otherwise ‘C’). • Click the OK button to complete project registration.

__ 2. Register a database connection.

• Right-click Database Connections, then select Add Connection. • The connection Type should be Online. • Click Next button. • On the Connection panel, Driver should be IBM DB2 alias. • Database Alias should be SAMPLE. • Under User Information, check Use your current user id and password. • Click the Finish button.

__ 3. Let's build an SQL stored procedure.

• Right-click Stored Procedures folder icon. Click New -> Stored Procedure Using Wizard.

• In the right hand pane, select SQL and click the OK button. • In the Create SQL Stored Procedure Wizard window:

- You should be in the Name panel; if not, click 1.Name. - Set Name: CF71.LAB2_1.

• On the Definition panel: - Click the tiny push button in the value field for Result set and select None. - Click the tiny push button in the value field for Statement. This takes you to

the SQL Statement window. - Select Generate one SQL statement and click the SQL Assist... push button.

• In SQL Assistant window: - In the outline, click FROM. - Expand ADMIN. - Find STAFF table and click its icon.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-2 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 23: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

- Click > button to move STAFF to selected tables area. - In the Selected tables area, select SYSCAT.PROCE... and click the < button. - In the outline, click SELECT. - Expand ADMIN.STAFF. Click ID and then hold down the Shift key and click

COMM. Now click the > button. - In the outline, click ORDER BY. - Expand ADMIN.STAFF. Click SALARY and then click the > button.

• The SQL statement generated is displayed in the SQL code area. • Click OK button to return to SQL Statement panel and then click the OK button. • In the Create SQL Stored Procedure Wizard - CF71.LAB2_1 window, click Finish

button. (The default is to Build the stored procedure when you finish. This can be changed on the Option pane in which case you are responsible for Building the stored procedure).

__ 4. What messages did you receive in the Messages tab?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 5. Right-click your stored procedures and select Edit. You might have to resize your Edit window.

__ 6. Return to the Development Center desktop (click it in the Windows taskbar at the bottom of the screen).

__ 7. Right-click your stored procedure and select Run. You should see three messages as a result in the Message tab.

__ 8. To the left of the messages are all of the actions and their status that you have done. If you click the Parameter or Result tab (at the bottom of your message pane), you will see that they are empty. Why do you think this is so?

________________________________________________________________

__ 9. Congratulations! You've just completed your first stored procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 2. The DB2 Development Center 2-3

Page 24: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 2: Stored Procedure with CREATE TABLE

__ 1. Build a stored procedure to create tables CF71.STAFF and CF71.ORG.

• In the Project View, right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure.

• Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB2_2. • Position your cursor at end of line containing BEGIN. • Press Enter to begin insert of new lines. • Code in the following SQL statements:

CREATE TABLE CF71.ORG LIKE ADMIN.ORG; CREATE TABLE CF71.STAFF LIKE ADMIN.STAFF;

• From the menu, click File->Save Object. • Return to the Development Center desktop. • Right-click your stored procedure (CF71.LAB2_2) and select Build.

What messages did you receive in the Messages tab?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 2. Execute the new stored procedure.

• Right-click your stored procedure and select Run.

What messages did you receive in the Result tab?

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 3. Verify that the tables were created.

• From the Development Center desktop menu, select Tools->Control Center. • Expand your DB2 system until the SAMPLE database is displayed. Now expand

it as well. Click Tables under the SAMPLE database. In the list of tables displayed, you should see the two tables that your stored procedure created.

__ 4. A second verification.

• Return to the Edit window for your stored procedure. If you did not close the editor, then access it from the taskbar. If you closed it, then right-click your stored procedure and select Edit.

• Position the cursor anywhere in the display stored procedure. • Click the SQL icon in the toolbar at the top of the window. The SQL Assist

displays.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-4 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 25: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

• Click FROM and expand CF71. You should see your two tables listed. • Click the Cancel button.

__ 5. Initialize your new tables with a stored procedure.

• Return to the Development Center desktop. • Right-click the Stored Procedures folder icon. Click New -> SQL Stored

Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB2_3. • Position your cursor at end of line containing BEGIN. • Press Enter to begin insert of new lines. • Code in the following SQL statements:

INSERT INTO CF71.ORG SELECT * FROM ADMIN.ORG; INSERT INTO CF71.STAFF SELECT * FROM ADMIN.STAFF;

• On the Editor’s menu, select File->Save Object. • Return to the Development Center desktop. • Right-click your stored procedure (CF71.LAB2_3) and select Build. • You should once again see the successful build messages. • Execute the new stored procedure by right-clicking it and selecting Run. • Once again you should see three messages indicating a successful run.

__ 6. Validate data in your new tables.

• Return to the Editor for your stored procedure. • Position the cursor in your stored procedure and click the SQL icon in the toolbar. • In SQL Assist window:

- Click FROM and expand CF71. - Double-click ORG icon under CF71 icon in Available tables list to move to

Selected tables list. - Select the SYSCAT.PROCE... in the Selected Tables and click the < button. - Click Run button to execute.

Did the Results windows show all 8 rows for CF71.ORG?

________________________________________________________________

________________________________________________________________

• Click OK button to exit Results window. • You can use the same technique to verify the data in the CF71.STAFF table. • You could also return to the Control Center and right-click the desired table and

select Sample Contents.

__ 7. Saving your project.

• Return to the Development Center desktop. • Right-click your project - CF71 and select Save Project.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 2. The DB2 Development Center 2-5

Page 26: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 3: Stored Procedure Source Code

The source for the stored procedures created for this lab exercise will be found in Section 3 of the solutions.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-6 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 27: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise Solutions

Section 1: Register a New Project

__ 1. Start the DB2 Development Center.

• Starting with the WIN/NT Start icon (lower left on DESKTOP): Click Start ->Programs ->IBM DB2 ->Development Tools->Development Center.

• If the Launch Pad is displayed, close it. (You might want to check ‘Do not show this again’).

• Register a new project with the DB2 Development Center. • In IBM DB2 Development Center window menu: Click Project->New Project. • Set the following fields as indicated:

- Project name: CF71 - Project path: x:\CF71_Project (where x is the your drive letter. This would be

the ‘D’ drive if you have one, otherwise ‘C’). • Click the OK button to complete project registration.

__ 2. Register a database connection.

• Right-click Database Connections, then select Add Connection. • The connection Type should be Online. • Click Next button. • On the Connection panel, Driver should be IBM DB2 alias. • Database Alias should be SAMPLE. • Under User Information, check Use your current user id and password. • Click the Finish button.

__ 3. Let's build an SQL stored procedure.

• Right-click Stored Procedures folder icon. Click New -> Stored Procedure Using Wizard.

• In the right hand pane, select SQL and click the OK button. • In the Create SQL Stored Procedure Wizard window:

- You should be in the Name panel; if not, click 1.Name. - Set Name: CF71.LAB2_1.

• On the Definition panel. - Click the tiny push button in the value field for Result set and select None. - Click the tiny push button in the value field for Statement. This takes you to

the SQL Statement window. - Select Generate one SQL statement and click the SQL Assist... push button.

• In SQL Assistant window: - In the outline, click FROM. - Expand ADMIN. - Find STAFF table and click its icon. - Click > button to move STAFF to selected tables area. - In the Selected tables area, select SYSCAT.PROCE... and click the < button.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 2. The DB2 Development Center 2-7

Page 28: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

- In the outline, click SELECT. - Expand ADMIN.STAFF. Click ID and then hold down the shift key and click

COMM. Now click the > button. - In the outline, click ORDER BY. - Expand ADMIN.STAFF. Click SALARY and then click the > button.

• The SQL statement generated is displayed in the SQL code area. • Click OK button to return to SQL Statement panel and then click the OK button. • In the Create SQL Stored Procedure Wizard - CF71.LAB2_1 window, click Finish

button. (The default is to Build the stored procedure when you finish. This can be changed on the Option pane in which case you are responsible for Building the stored procedure).

__ 4. What messages did you receive in the Messages tab?

CF71.LAB2_1 - Build started. CF71.LAB2_1 - Create stored procedure completed. CF71.LAB2_1 - Build successful.

__ 5. Right-click your stored procedures and select Edit. You might have to resize your Edit window.

__ 6. Return to the Development Center desktop (click it in the Windows taskbar at the bottom of the screen).

__ 7. Right-click your stored procedure and select Run. You should see three messages as a result in the Message tab.

__ 8. To the left of the messages are all of the actions and their status that you have done. If you click the Parameter or Result tab (at the bottom of your message pane), you will see that they are empty. Why do you think this is so?

Since there were no input parameters passed to your stored procedure, there is nothing listed on the Parameters tab. And since your stored procedure did not return any results, nothing will be displayed on the Results tab.

__ 9. Congratulations! You've just completed your first stored procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-8 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 29: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 2: Stored Procedure with CREATE TABLE

__ 1. Build a stored procedure to create tables CF71.STAFF and CF71.ORG.

• In the Project View, right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure.

• Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB2_2. • Position your cursor at end of line containing BEGIN. • Press Enter to begin insert of new lines. • Code in the following SQL statements:

CREATE TABLE CF71.ORG LIKE ADMIN.ORG; CREATE TABLE CF71.STAFF LIKE ADMIN.STAFF;

• From the menu, click File->Save Object. • Return to the Development Center desktop. • Right-click your stored procedure (CF71.LAB2_2) and select Build.

What messages did you receive in the Messages tab?

CF71.LAB2_2 - Build started. CF71.LAB2_2 - Create stored procedure completed. CF71.LAB2_2 - Build successful.

__ 2. Execute the new stored procedure.

• Right-click your stored procedure and select Run.

What messages did you receive in the Result tab?

CF71.LAB2_2 - Run started. CF71.LAB2_2 - Calling the stored procedure. CF71.LAB2_2 - Run completed.

__ 3. Verify that the tables were created.

• From the Development Center desktop menu, select Tools->Control Center. • Expand your DB2 system until the SAMPLE database is displayed. Now expand

it as well. Click Tables under the SAMPLE database. In the list of tables displayed, you should see the two tables that your stored procedure created.

__ 4. A second verification.

• Return to the Edit window for your stored procedure. If you did not close the editor, then access it from the taskbar. If you closed it, then right-click your stored procedure and select Edit.

• Position the cursor anywhere in the display stored procedure. • Click the SQL icon in the toolbar at the top of the window. The SQL Assist

displays. • Click FROM and expand CF71. You should see your two tables listed. • Click Cancel button.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 2. The DB2 Development Center 2-9

Page 30: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 5. Initialize your new tables with a stored procedure.

• Return to the Development Center desktop. • Right-click the Stored Procedures folder icon. Click New -> SQL Stored

Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB2_3. • Position your cursor at end of line containing BEGIN. • Press Enter to begin insert of new lines. • Code in the following SQL statements:

INSERT INTO CF71.ORG SELECT * FROM ADMIN.ORG; INSERT INTO CF71.STAFF SELECT * FROM ADMIN.STAFF;

• On the Editor’s menu, select File->Save Object. • Return to the Development Center desktop. • Right-click your stored procedure (CF71.LAB2_3) and select Build. • You should once again see the successful build messages. • Execute the new stored procedure by right-clicking it and selecting Run. • Once again you should see three messages indicating a successful run.

__ 6. Validate data in your new tables.

• Return to the Editor for your stored procedure. • Position the cursor in your stored procedure and click the SQL icon in the toolbar. • In SQL Assist window:

- Click FROM and expand CF71. - Double-click ORG icon under CF71 icon in Available tables list to move to

Selected tables list. - Select the SYSCAT.PROCE... in the Selected Tables and click the < button. - Click Run button to execute.

Did the Results windows show all 8 rows for CF71.ORG?

It should have.

• Click OK button to exit Results window. • You can use the same technique to verify the data in the CF71.STAFF table. • You could also return to the Control Center and right-click the desired table and

select Sample Contents.

__ 7. Saving your project.

• Return to the Development Center desktop. • Right-click your project - CF71 and select Save Project.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-10 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 31: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 3: Stored Procedure Source Code

1. LAB2_1

CREATE PROCEDURE CF71.LAB2_1 ( )-------------------------------------------------------------------------- SQL Stored Procedure ------------------------------------------------------------------------P1: BEGIN -- Declare variable --DECLARE ENDTABLE INT DEFAULT 0;

-- Declare cursor DECLARE cursor1 CURSOR FOR SELECT STAFF.ID, STAFF.NAME, STAFF.DEPT, STAFF.JOB, STAFF.YEARS, STAFF.SALARY, STAFF.COMM FROM ADMIN.STAFF AS STAFF ORDER BY STAFF.SALARY ASC;

-- Declare handler --DECLARE CONTINUE HANDLER FOR NOT FOUND --SET ENDTABLE = 1;

-- Sample code to access results. Goes with the lines -- "DECLARE ENDTABLE..." and "DECLARE CONTINUE..." shown above. --OPEN cursor1; --SET ENDTABLE = 0; --WHILE ENDTABLE = 0 DO --FETCH cursor1 INTO <declared variables> --END WHILE; --CLOSE cursor1;END P1

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 2. The DB2 Development Center 2-11

Page 32: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

2. LAB2_2

CREATE PROCEDURE CF71.LAB2_2 ( ) ------------------------------------------------------------------------ -- SQL Stored Procedure ------------------------------------------------------------------------ P1: BEGIN CREATE TABLE CF71.ORG LIKE ADMIN.ORG; CREATE TABLE CF71.STAFF LIKE ADMIN.STAFF; END P1

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-12 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 33: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

3. LAB2_3

CREATE PROCEDURE CF71.LAB2_3 ( ) ------------------------------------------------------------------------ -- SQL Stored Procedure ------------------------------------------------------------------------ P1: BEGIN INSERT INTO CF71.ORG SELECT * FROM ADMIN.ORG; INSERT INTO CF71.STAFF SELECT * FROM ADMIN.STAFF; END P1

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 2. The DB2 Development Center 2-13

Page 34: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-14 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 35: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise 3. SQL Procedure Language

What This Exercise Is About

This exercise provides an opportunity for the students to build several stored procedures using SQL Procedure Language constructs. Some stored procedures will solve the same user requirement with different SQL Procedure Language constructs.

What You Should Be Able to Do

At the end of the lab, you should be able to:

• Create a stored procedure written in SQL Procedure Language • Solve user requirements in more than one way with SQL

Procedure Language • Build and execute an SQL Procedure Language procedure with the

DB2 Development Center

Introduction

This lab has several sections.

• Section 1: Create an SQL stored procedure using the CASE SQL Procedure Language statement.

• Section 2: Create an SQL stored procedure using the IF SQL Procedure Language statement.

• Section 3: Create an SQL stored procedure using the REPEAT SQL Procedure Language statement.

• Section 4: Create an SQL stored procedure using the LOOP SQL Procedure Language statement.

• Section 5: Create an SQL stored procedure that will return the median salary from the CF71.STAFF table.

• Section 6: Create an SQL stored procedure that will return the median salary from the CF71.STAFF table and a result set with the ID, NAME, and SALARY from all rows where the SALARY is greater than the median salary.

• Section 7: Stored procedure source code listings

In Section 1, you will create a new stored procedure. That stored procedure will use the CASE construct to update the CF71.STAFF table.

In Section 2, you will create a new stored procedure. That stored procedure will use the IF construct to update the CF71.STAFF table.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-1

Page 36: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

In Section 3, you will create a new stored procedure. That stored procedure will use the REPEAT construct to find rows in the CF71.STAFF table.

In Section 4, you will create a new stored procedure. That stored procedure will use the LOOP construct to find rows in the CF71.STAFF table.

In Section 5, you will create a new stored procedure. That stored procedure will need to determine the median salary of the CF71.STAFF table. This will require finding the number of rows in the CF71.STAFF table, opening a cursor on the table in SALARY order, and returning the median salary to the caller.

In Section 6, you will create a new stored procedure. That stored procedure will need to determine the median salary of the CF71.STAFF table. Your procedure will return that median salary to the caller along with information from the CF71.STAFF table from rows where the SALARY is greater than the median salary.

Section 7 provides a listing of the stored procedures source.

Required Materials

• Student notebook for SQL Procedure Language statement syntax. • DB2 Info Center for SQL Procedure Language statement syntax

(optional).

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-2 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 37: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise Instructions

The lab solutions can be found in “Exercise Solutions” on page 3-13.

Section 1: CASE Construct

This section will have you build a stored procedure, CF71.LAB3_1, to satisfy a request to update your CF71.STAFF table. The update will be different based on parameters passed to the stored procedure. To accomplish this, you will use the CASE SQL Procedure Language statement.

__ 1. You've been asked to provide a stored procedure that will increase an employee's salary in your CF71.STAFF table based on a rating of 1, 2, or 3. A rating of 1 will warrant a 10% increase. A rating of 2 will warrant a 5% increase. If not a 1 or 2, increase the employee's salary by 2.5%. Use the CASE SQL Procedure Language construct to accomplish this. The new procedure should return the old salary and the updated salary.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_1.

__ 2. Define the parameters your new procedure will need.

• First parameter should be SMALLINT to receive an employee's ID • Second parameter should be SMALLINT to receive the rating of 1, 2, or 3 • Third parameter should be DEC(7,2) to return the old salary • Fourth parameter should be DEC(7,2) to return the new salary

__ 3. Include DECLAREs for the following:

• SQLSTATE • A condition named not_found for SQLSTATE '02000' • An exit handler for not_found that will return SQLSTATE '70444'

__ 4. Return the old salary in the third parameter you defined.

__ 5. Use the CASE construct for the updates to CF71.STAFF:

CASE argument WHEN argumentvalue1 THEN ... ; WHEN argumentvalue2 THEN ... ; ELSE ... ; END CASE;

__ 6. Return the updated salary in the fourth parameter you defined.

__ 7. Click the File->Save Object menu.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-3

Page 38: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 8. Return to the Development Center desktop.

__ 9. Right-click your stored procedure (CF71.LAB3_1) and choose Build. (You could also select your stored procedure and then on the toolbar, click the Wrench icon).

__ 10. Make sure that your stored procedure is selected and click the Run icon from the toolbar (the green triangle).

Specify the variables for the procedure.

• Enter 310 for the employee ID number. • Enter 2 for the rating. • Click OK.

What did you see in the Parameters panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

What did you see in the Messages panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 11. Click Run icon from the icon list at top of window to execute your procedure.

Specify the variables for the procedure.

• Enter 1776 for the employee ID number. • Enter 2 for the rating. • Click OK.

What did you see in the Messages panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-4 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 39: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 2: IF Construct

This section will have you build a stored procedure, CF71.LAB3_2, to satisfy a request to update your CF71.STAFF table. The update will be different based on parameters passed to the stored procedure. To accomplish this, you will use the IF SQL Procedure Language statement.

__ 1. You've been asked to provide a stored procedure that will increase an employee's salary in your CF71.STAFF table based on a rating of 1, 2, or 3. A rating of 1 will warrant a 10% increase. A rating of 2 will warrant a 5% increase. If not a 1 or 2, increase the employee's salary by 2.5%. Use the IF SQL Procedure Language construct to accomplish this. The new procedure should return the old salary and the updated salary.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_2.

__ 2. Define the parameters your new procedure will need.

• First parameter should be SMALLINT to receive an employee's ID • Second parameter should be SMALLINT to receive the rating of 1, 2, or 3 • Third parameter should be DEC(7,2) to return the old salary • Fourth parameter should be DEC(7,2) to return the old salary

__ 3. Include DECLAREs for the following:

• SQLSTATE • A condition named not_found for SQLSTATE '02000' • An exit handler for not_found that will return SQLSTATE '70444'

__ 4. Return the old salary in the third parameter you defined.

__ 5. Use the IF construct for the updates to CF71.STAFF.

IF cond1 THEN ...; ELSEIF cond2 THEN ...; ELSE ...; END IF;

__ 6. Return the updated salary in the fourth parameter you defined.

__ 7. Save your stored procedure and return to the Development Center desktop.

__ 8. Select your CF71.LAB3_2 stored procedure and Build it.

__ 9. Now Run the stored procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-5

Page 40: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Specify the variables for the procedure.

• Enter 310 for the employee ID number. • Enter 1 for the rating. • Click OK.

What did you see in the Parameters panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

What did you see in the Messages panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-6 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 41: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 3: REPEAT Construct

This section will have you build a stored procedure, CF71.LAB3_3, to satisfy a request for information from the CF71.STAFF table. You will use the REPEAT SQL Procedure Language statement to accomplish this.

__ 1. Our database manager has a peculiar glitch; the MAX function is temporarily not working! You have been asked to write a stored procedure to return the ID and salary of the highest paid employee in the CF71.STAFF table. Use the REPEAT construct to find the this employee in your stored procedure.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_3.

__ 2. Define the parameters your new procedure will need.

• First parameter should be SMALLINT to return the employee ID • Second parameter should be DEC(7,2) to return the employee salary

__ 3. Include the following DECLARES:

• at_end a small integer initialized to 0. • not_found as a condition for SQLSTATE '02000'. • The cursor you will need to process the request. • Declare a continue handler for not_found that sets at_end to a value of 1.

You will need to OPEN and CLOSE your cursor within your stored procedure.

__ 4. Use the REPEAT construct to find the last employee ID for CF71.STAFF.

repeat_loop_label: REPEAT ..... UNTIL condition END REPEAT repeat_loop_label;

__ 5. Click Build icon from the icon list at top of window to build your procedure.

__ 6. Click Run icon from the icon list at top of window to execute your procedure.

What did you see in the Parameters panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

What did you see in the Messages panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-7

Page 42: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 4: LOOP Construct

This section will have you build a stored procedure, CF71.LAB3_4, to satisfy a request for information from the CF71.STAFF table. You will use the LOOP SQL Procedure Language statement to accomplish this.

__ 1. Each week one of our staff is picked to be on call. This is done rather randomly by using the first number picked in our state lottery's PICK 3 game. This week the number is 5. You have been asked to write a stored procedure that will accept this number and pick out the employee that is in that row when ordered by name.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_4.

__ 2. Define the parameters your new procedure will need.

• First parameter should be INT to receive the PICK 3 number. • Second parameter should be SMALLINT to return the employee ID. • Third parameter should be varchar(9) to return the employee's name.

__ 3. DECLARE the following:

• v_ctr an integer initialized to 1 • at_end a small integer initialized to 0 • not_found a condition for SQLSTATE '02000'

__ 4. DECLARE a cursor.

• Declare a continue handler for not_found that sets at_end to 1:;

__ 5. Use LOOP construct to find nth employee ID and name.

loop_label: LOOP ... END LOOP loop_label;

__ 6. Save your stored procedure and return to the Development Center desktop.

__ 7. Select your stored procedure and Build it.

__ 8. Run your stored procedure.

Specify the variable for the procedure.

• For this exercise, enter a value of 5. • Click OK.

__ 9. What did you see in the Parameters panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-8 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 43: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 5: Median Salary

This section will have you build a stored procedure, CF71.LAB3_5, that will return the median salary from the CF71.STAFF table.

__ 1. You've been asked to provide a stored procedure that will return the median salary of employees in the CF71.STAFF table.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_5.

__ 2. Define the parameters your new procedure will need.

First, and only, parameter should be DEC(7,2) to return the median salary.

__ 3. You will need some local variables. Include the following local DECLARES:

• v_numRecords as integer initialized to 1 • v_counter as integer initialized to 0

__ 4. DECLARE a cursor that will return the salaries in order.

__ 5. Declare a continue handler for the not found condition that will set medianSalary to 6666.

__ 6. Write the code for determining the median salary.

• Initialize your median salary variable to zero. • Determine the number of employees. • Open your cursor. • Use the WHILE construct to determine the median salary.

WHILE cond DO ... END WHILE;

__ 7. Good programming technique would dictate closing the cursor you were processing.

__ 8. Save your stored procedure and return to the Development Center desktop.

__ 9. Build the stored procedure and then Run it.

What did you see in the Parameters panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-9

Page 44: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 6: Creating a Result Set

This section will have you build a stored procedure, CF71.LAB3_6, that will return a result set.

__ 1. In this section, you will build a stored procedure, CF71.LAB3_6, that will return the median salary from CF71.STAFF. In addition, the ID, name, and salary of all employees in the table with a salary greater than the median will be returned in a result set.

• The stored procedure CF71.LAB3_5 already has most of what we need. • Bring the CF71.LAB3_5 procedure into the Edit window of the DB2 Development

Center. • Select and copy all statements from CF71.LAB3_5.

__ 2. You will now use that procedure as a basis for your new one.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Select and delete all statements. • Paste the statements you copied from CF71.LAB3_5. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_6. • Insert the following after the procedure description comment:

-- Returns result set of salaries > median salary

__ 3. Specify the correct parameter to allow a median salary to be returned and specify that a single result set will be returned.

__ 4. Change the cursor to include all the columns requested and return a result set.

__ 5. Change the FETCH to handle the ID and name.

__ 6. Don't forget to leave the cursor open after finding the median.

__ 7. Save the stored procedure and return to the Development Center desktop.

__ 8. Build your stored procedure and then Run it.

What did you see in the Parameters panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

What did you see in the Results panel? Notice that since this time you are returning a result set, you will see something in the Result panel.

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-10 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 45: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 9. Save your project.

• Return to the Development Center desktop.

• Right-click your project - CF71 and select Save Project.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-11

Page 46: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 7: Stored Procedure Source Code

The source for the stored procedures created for this lab exercise will be found in Section 7 of the solutions.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-12 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 47: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise Solutions

Section 1: CASE Construct

This section will have you build a stored procedure, CF71.LAB3_1, to satisfy a request to update your CF71.STAFF table. The update will be different based on parameters passed to the stored procedure. To accomplish this you will use the CASE SQL Procedure Language statement.

__ 1. You've been asked to provide a stored procedure that will increase an employee's salary in your CF71.STAFF table based on a rating of 1, 2, or 3. A rating of 1 will warrant a 10% increase. A rating of 2 will warrant a 5% increase. If not a 1 or 2, increase the employee's salary by 2.5%. Use the CASE SQL Procedure Language construct to accomplish this. The new procedure should return the old salary and the updated salary.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_1.

__ 2. Define the parameters your new procedure will need.

CREATE PROCEDURE CF71.LAB3_1 (IN employee_number SMALLINT, IN rating SMALLINT, OUT old_salary DEC(7,2), OUT new_salary DEC(7,2))

__ 3. Include DECLAREs for the following:

DECLARE SQLSTATE CHAR(5); DECLARE not_found CONDITION FORSQLSTATE '02000'; DECLARE EXIT HANDLER FOR not_found

SIGNAL SQLSTATE '70444';

__ 4. Return the old salary in the third parameter you defined.

SELECT SALARY into old_salary FROM CF71.STAFF WHERE id = employee_number;

__ 5. Use the CASE construct for the updates to CF71.STAFF:

CASE ratingWHEN 1 THEN

UPDATE CF71.STAFFSET salary = salary * 1.10WHERE id = employee_number;

WHEN 2 THEN UPDATE CF71.STAFFSET salary = salary * 1.05WHERE id = employee_number;

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-13

Page 48: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

ELSE UPDATE CF71.STAFFSET salary = salary * 1.025WHERE id = employee_number;

END CASE;

__ 6. Return the updated salary in the fourth parameter you defined.

SELECT SALARY into new_salary FROM CF71.STAFF WHERE id = employee_number;

__ 7. Click the File->Save Object menu.

__ 8. Return to the Development Center desktop.

__ 9. Right-click your stored procedure (CF71.LAB3_1) and choose Build. (You could also select your stored procedure and then on the toolbar, click the Wrench icon).

__ 10. Make sure that your stored procedure is selected and click the Run icon from the toolbar (the green triangle).

Specify the variables for the procedure.

• Enter 310 for the employee ID number. • Enter 2 for the rating. • Click OK.

What did you see in the Parameters panel?

Both the input and output parameters - The values of the output parameters: OLD_SALARY = 21000.00NEW_SALARY = 22050.00

What did you see in the Messages panel?

CF71.LAB3_1 - Run started.

CF71.LAB3_1 - Calling the stored procedure.

CF71.LAB3_1 -Run completed.

__ 11. Click Run icon from the icon list at top of window to execute your procedure.

Specify the variables for the procedure.

• Enter 1776 for the employee ID number. • Enter 2 for the rating. • Click OK.

What did you see in the Messages panel?

CF71.LAB3_1 - Run started.

CF71.LAB3_1 - Exception occurred while running:

A database manager error occurred. [IBM][CLI Driver]DB2/NT- SQL0438N Application raised error with diagnostic text: SQLSTATE=70444

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-14 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 49: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

CF71.LAB3_1 - Roll back completed successfully.

CF71.LAB3_1 - Run failed.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-15

Page 50: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 2: IF Construct

This section will have you build a stored procedure, CF71.LAB3_2, to satisfy a request to update your CF71.STAFF table. The update will be different based on parameters passed to the stored procedure. To accomplish this, you will use the IF SQL Procedure Language statement.

__ 1. You've been asked to provide a stored procedure that will increase an employee's salary in your CF71.STAFF table based on a rating of 1, 2, or 3. A rating of 1 will warrant a 10% increase. A rating of 2 will warrant a 5% increase. If not a 1 or 2, increase the employee's salary by 2.5%. Use the IF SQL Procedure Language construct to accomplish this. The new procedure should return the old salary and the updated salary.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_2.

__ 2. Define the parameters your new procedure will need.

CREATE PROCEDURE CF71.LAB3_2 (IN employee_number SMALLINT, IN rating SMALLINT,

OUT old_salary DEC(7,2), OUT new_salary DEC(7,2))

__ 3. Include DECLAREs for the following:

DECLARE SQLSTATE CHAR(5); DECLARE not_found CONDITION FORSQLSTATE '02000'; DECLARE EXIT HANDLER FOR not_found

SIGNAL SQLSTATE '70444';

__ 4. Return the old salary in the third parameter you defined.

SELECT SALARY into old_salary FROM CF71.STAFF WHERE id = employee_number;

__ 5. Use the IF construct for the updates to CF71.STAFF.

IF (rating = 1) THEN UPDATE CF71.STAFFSET salary = salary * 1.10 WHERE id = employee_number;

ELSEIF (rating = 2) THEN UPDATE CF71.STAFF SET salary = salary * 1.05 WHERE id = employee_number;

ELSE UPDATE CF71.STAFF SET salary = salary * 1.025 WHERE id = employee_number;

END IF;

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-16 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 51: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 6. Return the updated salary in the fourth parameter you defined.

SELECT SALARY into new_salary FROM CF71.STAFF WHERE id = employee_number;

__ 7. Save your stored procedure and return to the Development Center desktop.

__ 8. Select your CF71.LAB3_2 stored procedure and Build it.

__ 9. Now Run the stored procedure.

Specify the variables for the procedure.

• Enter 310 for the employee ID number. • Enter 1 for the rating. • Click OK.

What did you see in the Parameters panel?

Both the input and output parameters - The value(s) of the output parameters: OLD_SALARY = 22050.00 NEW_SALARY = 24255.00

What did you see in the Messages panel?

CF71.LAB3_2 - Run started.

CF71.LAB3_2 - Calling the stored procedure.

CF71.LAB3_2 - Run completed.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-17

Page 52: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 3: REPEAT Construct

This section will have you build a stored procedure, CF71.LAB3_3, to satisfy a request for information from the CF71.STAFF table. You will use the REPEAT SQL Procedure Language statement to accomplish this.

__ 1. Our database manager has a peculiar glitch; the MAX function is temporarily not working! You have been asked to write a stored procedure to return the ID and salary of the highest paid employee in the CF71.STAFF table. Use the REPEAT construct to find the this employee in your stored procedure.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_3.

__ 2. Define the parameters your new procedure will need.

CREATE PROCEDURE CF71.LAB3_3(OUT employee_id SMALLINT, OUT hi_salary DEC(7,2))

__ 3. Include the following DECLARES:

• at_end a small integer initialized to 0 • not_found as a condition for SQLSTATE '02000' • The cursor you will need to process the request • Declare a continue handler for not_found that sets at_end to a value of 1

You will need to OPEN and CLOSE your cursor within your stored procedure.

DECLARE at_end SMALLINT DEFAULT 0; DECLARE not_found CONDITION FOR SQLSTATE '02000';

DECLARE c1 CURSOR FORSELECT id, salary

FROM CF71.STAFF ORDER BY salary;

DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1;

__ 4. Use the REPEAT construct to find the last employee ID for CF71.STAFF.

fetch_loop: REPEAT

FETCH c1 INTO employee_id, hi_salary;

UNTIL at_end <> 0 END REPEAT fetch_loop;

__ 5. Click Build icon from the icon list at top of window to build your procedure.

__ 6. Click Run icon from the icon list at top of window to execute your procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-18 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 53: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

What did you see in the Parameters panel?

The value(s) of the output parameters: EMPLOYEE_ID = 310 HI_SALARY = 24255.00

What did you see in the Messages panel?

CF71.LAB3_3 - Run started.

CF71.LAB3_3 - Calling the stored procedure.

CF71.LAB3_3 - Run Completed.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-19

Page 54: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 4: LOOP Construct

This section will have you build a stored procedure, CF71.LAB3_4, to satisfy a request for information from the CF71.STAFF table. You will use the LOOP SQL Procedure Language statement to accomplish this.

__ 1. Each week one of our staff is picked to be on call. This is done rather randomly by using the first number picked in our state lottery's PICK 3 game. This week the number is 5. You have been asked to write a stored procedure that will accept this number and pick out the employee that is in that row when ordered by name.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_4.

__ 2. Define the parameters your new procedure will need.

CREATE PROCEDURE CF71.LAB3_4 (IN which_one INT, OUT employee_idSMALLINT, OUT employee_name varchar(9) )

__ 3. DECLARE the following:

• v_ctr an integer initialized to 1 • at_end a small integer initialized to 0 • not_found a condition for SQLSTATE '02000'

DECLARE v_ctr INT DEFAULT 1;

DECLARE at_end SMALLINT DEFAULT 0;

DECLARE not_found CONDITION FOR SQLSTATE '02000';

__ 4. DECLARE a cursor.

• Declare a continue handler for not_found that sets at_end to 1:;

DECLARE c1 CURSOR FOR SELECT id, name

FROM CF71.STAFFORDER BY name;

DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1;

__ 5. Use LOOP construct to find nth employee ID and name.

fetch_loop: LOOP FETCH c1 INTO

employee_id, employee_name;IF v_ctr = which_one THEN

LEAVE fetch_loop; ELSE SET v_ctr = v_ctr + 1; END IF;

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-20 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 55: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

END LOOP fetch_loop;

__ 6. Save your stored procedure and return to the Development Center desktop.

__ 7. Select your stored procedure and Build it.

__ 8. Run your stored procedure.

Specify the variable for the procedure.

• For this exercise, enter a value of 5. • Click OK.

__ 9. What did you see in the Parameters panel?

Both the input and output parameters. The values of the output parameters:EMPLOYEE_ID = 340 EMPLOYEE_NAME = Edwards

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-21

Page 56: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 5: Median Salary

This section will have you build a stored procedure, CF71.LAB3_5, that will return the median salary from the CF71.STAFF table.

__ 1. You've been asked to provide a stored procedure that will return the median salary of employees in the CF71.STAFF table.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_5.

__ 2. Define the parameters your new procedure will need.

CREATE PROCEDURE CF71.LAB3_5 (OUT medianSalary DEC(7,2))

__ 3. You will need some local variables. Include the following local DECLARES:

DECLARE v_numRecords INT DEFAULT 1;

DECLARE v_counter INT DEFAULT 0;

__ 4. DECLARE a cursor that will return the salaries in order.

DECLARE c1 CURSOR FORSELECT salary FROM CF71.STAFFORDER BY salary;

__ 5. Declare a continue handler for the not found condition that will set medianSalary to 6666.

DECLARE CONTINUE HANDLER FOR NOT FOUND SET medianSalary = 6666;

__ 6. Write the code for determining the median salary.

-- initialize OUT parameter SET medianSalary = 0;

SELECT COUNT(*) INTO v_numRecords FROM STAFF;

OPEN c1; WHILE v_counter < (v_numRecords / 2 + 1) DO

FETCH c1 INTO medianSalary; SET v_counter = v_counter + 1;

END WHILE;

__ 7. Good programming technique would dictate closing the cursor you were processing.

-- close cursorCLOSE c1;

__ 8. Save your stored procedure and return to the Development Center desktop.

__ 9. Build the stored procedure and then Run it.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-22 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 57: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

What did you see in the Parameters panel?

The value(s) of the output parameters: MEDIANSALARY = 17654.50

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-23

Page 58: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 6: Creating a Result Set

This section will have you build a stored procedure, CF71.LAB3_6, that will return a result set.

__ 1. In this section, you will build a stored procedure, CF71.LAB3_6, that will return the median salary from CF71.STAFF. In addition, the ID, name, and salary of all employees in the table with a salary greater than the median will be returned in a result set.

• The stored procedure CF71.LAB3_5 already has most of what we need. • Bring the CF71.LAB3_5 procedure into the Edit window of the DB2 Development

Center. • Select and copy all statements from CF71.LAB3_5.

__ 2. You will now use that procedure as a basis for your new one.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Select and delete all statements. • Paste the statements you copied from CF71.LAB3_5. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.LAB3_6. • Insert the following after the procedure description comment:

-- Returns result set of salaries > median salary

__ 3. Specify the correct parameter to allow a median salary to be returned and specify that a single result set will be returned.

CREATE PROCEDURE CF71.LAB3_6 (OUT medianSalary DEC(7,2)) RESULT SETS 1LANGUAGE SQL

__ 4. Change the cursor to include all the columns requested and return a result set.

You will need declares for the ID and name before the declare for cursor.

DECLARE v_Id SMALLINT DEFAULT 0; DECLARE v_Name CHAR(9);

DECLARE c1 CURSOR WITH RETURN FORSELECT id, name, salary FROM CF71.STAFFORDER BY salary;

__ 5. Change the FETCH to handle the ID and name.

FETCH c1 INTO v_Id, v_Name, medianSalary;

__ 6. Don't forget to leave the cursor open after finding the median.

-- leave cursor c1 open to return result set

__ 7. Save the stored procedure and return to the Development Center desktop.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-24 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 59: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 8. Build your stored procedure and then Run it.

What did you see in the Parameters panel?

The values of the output parameters:

MEDIANSALARY = 17654.50

What did you see in the Results panel? Notice that since this time you are returning a result set, you will see something in the Result panel.

SALARY17844.0018001.7518006.0018171.2518352.8018357.5018555.5018674.5019260.2519456.5019818.0020010.0020659.8021150.0021234.0022959.2024255.00

__ 9. Save your project.

• Return to the Development Center desktop.

• Right-click your project - CF71 and select Save Project.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-25

Page 60: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 7: Stored Procedure Source Code

1. LAB3_1

CREATE PROCEDURE CF71.LAB3_1 (IN employee_number SMALLINT, IN rating SMALLINT, OUT old_salary DEC(7,2), OUT new_salary DEC(7,2)) LANGUAGE SQL ------------------------------------------------------------------------ -- SQL Stored Procedure -- use CASE construct to assign new salaries ------------------------------------------------------------------------ P1: BEGIN DECLARE SQLSTATE CHAR(5); DECLARE not_found CONDITION FOR SQLSTATE '02000'; DECLARE EXIT HANDLER FOR not_found SIGNAL SQLSTATE '70444' ; SELECT SALARY into old_salary FROM CF71.STAFF where id = employee_number; CASE rating WHEN 1 THEN UPDATE CF71.STAFF SET salary = salary * 1.10 WHERE id = employee_number; WHEN 2 THEN UPDATE CF71.STAFF SET salary = salary * 1.05 WHERE id = employee_number; ELSE UPDATE CF71.STAFF SET salary = salary * 1.025 WHERE id = employee_number; END CASE; SELECT SALARY into new_salary FROM CF71.STAFF where id = employee_number; END P1

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-26 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 61: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

2. LAB3_2

CREATE PROCEDURE CF71.LAB3_2 (IN employee_number SMALLINT, IN rating SMALLINT, OUT old_salary DEC(7,2), OUT new_salary DEC(7,2)) LANGUAGE SQL ------------------------------------------------------------------------ -- SQL Stored Procedure -- use IF construct to assign new salaries ------------------------------------------------------------------------ P1: BEGIN DECLARE SQLSTATE CHAR(5); DECLARE not_found CONDITION FOR SQLSTATE '02000'; DECLARE EXIT HANDLER FOR not_found SIGNAL SQLSTATE '70444' ; SELECT SALARY into old_salary FROM CF71.STAFF where id = employee_number; IF (rating = 1) THEN UPDATE CF71.STAFF SET salary = salary * 1.10 WHERE id = employee_number; ELSEIF (rating = 2) THEN UPDATE CF71.STAFF SET salary = salary * 1.05 WHERE id = employee_number; ELSE UPDATE CF71.STAFF SET salary = salary * 1.025 WHERE id = employee_number; END IF; SELECT SALARY into new_salary FROM CF71.STAFF where id = employee_number; END P1

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-27

Page 62: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

3. LAB3_3

CREATE PROCEDURE CF71.LAB3_3 (OUT employee_id SMALLINT, OUT hi_salary DEC(7,2)) LANGUAGE SQL ------------------------------------------------------------------------ -- SQL Stored Procedure -- Use REPEAT construct to find highest employee salary ------------------------------------------------------------------------ P1: BEGIN DECLARE at_end SMALLINT DEFAULT 0; DECLARE not_found CONDITION FOR SQLSTATE '02000'; DECLARE c1 CURSOR FOR SELECT id, salary FROM CF71.STAFF ORDER BY salary; DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1; -- open cursor OPEN c1; -- fetch each staff id fetch_loop: REPEAT FETCH c1 INTO employee_id, hi_salary; UNTIL at_end <> 0 END REPEAT fetch_loop; -- close cursor CLOSE c1; END P1

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-28 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 63: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

4. LAB3_4

CREATE PROCEDURE CF71.LAB3_4 (IN which_one INT, OUT employee_id SMALLINT, OUT employee_name varchar(9) ) LANGUAGE SQL ------------------------------------------------------------------------ -- SQL Stored Procedure -- Use LOOP construct to find nth STAFF NAME ------------------------------------------------------------------------ P1: BEGIN DECLARE v_ctr INT DEFAULT 1; DECLARE at_end SMALLINT DEFAULT 0; DECLARE not_found CONDITION FOR SQLSTATE '02000'; DECLARE c1 CURSOR FOR SELECT id, name FROM CF71.STAFF ORDER BY name; DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1; -- open cursor OPEN c1; -- fetch each staff id, name fetch_loop: LOOP FETCH c1 INTO employee_id, employee_name; IF v_ctr = which_one THEN LEAVE fetch_loop; ELSE SET v_ctr = v_ctr + 1; END IF; END LOOP fetch_loop; -- close cursor CLOSE c1; END P1

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-29

Page 64: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

5. LAB3_5

CREATE PROCEDURE CF71.LAB3_5 -- Declare medianSalary as OUT so it can be used in DECLARE CURSOR (OUT medianSalary DEC(7,2)) LANGUAGE SQL ------------------------------------------------------------------------ -- SQL Stored Procedure -- Returns median SALARY from CF71.STAFF using WHILE construct ------------------------------------------------------------------------ P1: BEGIN DECLARE v_numRecords INT DEFAULT 1; DECLARE v_counter INT DEFAULT 0; DECLARE c1 CURSOR FOR SELECT salary FROM CF71.STAFF ORDER BY salary; DECLARE CONTINUE HANDLER FOR NOT FOUND SET medianSalary = 6666; -- initialize OUT parameter SET medianSalary = 0; SELECT COUNT(*) INTO v_numRecords FROM STAFF; OPEN c1; WHILE v_counter < (v_numRecords / 2 + 1) DO FETCH c1 INTO medianSalary; SET v_counter = v_counter + 1; END WHILE; -- close cursor CLOSE c1; END P1

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-30 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 65: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

6. LAB3_6

CREATE PROCEDURE CF71.LAB3_6 (OUT medianSalary DEC(7,2)) RESULT SETS 1 LANGUAGE SQL ------------------------------------------------------------------------ -- SQL Stored Procedure -- Returns median SALARY from CF71.STAFF using WHILE construct -- Returns result set of salaries > median salary ------------------------------------------------------------------------ P1: BEGIN DECLARE v_numRecords INT DEFAULT 1; DECLARE v_counter INT DEFAULT 0; DECLARE v_Id SMALLINT DEFAULT 0; DECLARE v_Name CHAR(9); DECLARE c1 CURSOR WITH RETURN FOR SELECT id, name, salary FROM CF71.STAFF ORDER BY salary; DECLARE CONTINUE HANDLER FOR NOT FOUND SET medianSalary = 6666; -- initialize OUT parameter SET medianSalary = 0; SELECT COUNT(*) INTO v_numRecords FROM STAFF; OPEN c1; WHILE v_counter < (v_numRecords / 2 + 1) DO FETCH c1 INTO v_Id, v_Name, medianSalary; SET v_counter = v_counter + 1; END WHILE; -- leave cursor c1 open to return result set END P1

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 3. SQL Procedure Language 3-31

Page 66: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-32 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 67: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise 4. Building Java Stored Procedures

What This Exercise Is About

This exercise will have you create Java stored procedures using the DB2 Development Center.

What You Should Be Able to Do

At the end of the lab, you should be able to:

• Generate SQLJ and JDBC stored procedures • Create Java stored procedures using SQL Assist • Create Java stored procedures that return a result set • Create Java stored procedures that allow the user to select which

of several statements should be run • Generate a Java stored procedure that could be passed to a Java

programmer for completion

Introduction

This exercise has several sections.

• Section 1: Create a JDBC Stored Procedure that returns a result set.

• Section 2: Create an SQLJ Stored Procedure that returns one of a choice of result sets.

• Section 3: Create a JDBC Stored Procedure that returns one of a choice of result sets.

• Section 4: Create an SQLJ Stored Procedure that allows users to choose which count of rows they want to receive.

• Section 5: Create a JDBC Stored Procedure that allow the users to choose which count of rows they want to receive.

• Section 6: Generate a JDBC Stored Procedure with no code in it to provide to a Java programmer for completion.

• Section 7: Stored procedure source code listings.

In Section 1, you will create a JDBC Stored Procedure that returns a result set.

In Section 2, you will create an SQLJ Stored Procedure that allows the user to select which of multiple result sets they want returned.

In Section 3, you will create a JDBC Stored Procedure that allows the user to select which of multiple result sets they want returned.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-1

Page 68: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

In Section 4, you will create an SQLJ Stored Procedure that allows the user to choose which count of rows they want to receive.

In Section 5, you will create a JDBC Stored Procedure that allows the user to choose which count of rows they want to receive.

In Section 6, you will generate a JDBC Stored Procedure that has no code in it. This procedure would be suitable for providing to a Java programmer to complete more complicated Java code than we will be addressing in this class.

Section 7 provides a listing of the stored procedures source.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-2 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 69: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise Instructions

The lab solutions can be found in “Exercise Solutions” on page 4-19.

Section 1: JDBC Stored Procedure Returning Result Set

__ 1. You've been asked to provide a Java stored procedure that will return a result set of the CF71.STAFF table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_1. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Ensure Result set is set to One. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the push button in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate one SQL statement is selected.

• In SQL Statement panel, click SQL Assist button. • In SQL Assist window:

- In the Outline tree, click FROM. - Under Available tables, expand CF71. - Under CF71, select STAFF. - Click > to move STAFF to the selected tables area. - In the Selected tables area, select SYSCAT.PROCE... and click the < button

to remove that entry. - In the Outline tree, click SELECT (Result columns). - Under Available columns, expand CF71.STAFF and for each column, select it

and click the > button. (Or you can do a Windows Shift select to select all of the columns in order to move them all at once).

What SQL statement was generated for you?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

• Click OK button to return to SQL Statement panel. Then click the OK button. • Click Next> button to move to Parameters panel. No changes required on

Parameters panel. • Click Next> button to move to Options panel.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-3

Page 70: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

- Leave Specific name blank, leave the Jar ID unchanged, leave Java package blank.

- Indicate Database access as Dynamic SQL using JDBC. - Make sure Build is checked.

• Click Finish button to generate and build the JDBC stored procedure.

__ 2. What basic messages did you receive in the Messages tab?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 3. Right-click your stored procedure (CF71.LAB4_1) and select Edit. Find the SQL statement generated by the DB2 Development Center. How is the SQL statement passed to the database manager?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 4. Return to the Development Center desktop.

__ 5. Run your stored procedure.

__ 6. Your results should be in the Result panel.

__ 7. Congratulations! You've just completed your first Java stored procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-4 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 71: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 2: SQLJ Stored Procedure Returning Choice of Results Sets

__ 1. You've been asked to provide an SQLJ stored procedure that will return either a result set of the CF71.STAFF table or a result set of the CF71.ORG table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_2. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Ensure Result set is set to One. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the pushbutton in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate multiple SQL statements is selected.

• In SQL Statement panel, instead of using the SQL Assistant this time, just type in the statement you want to execute. Swipe over the statement that is provided by default (select from syscat.procedures) and replace the statement with:

select * from cf71.staff • Click Add button to add another SQL statement. • With the second SQL statement area selected, erase the statement that is there

(swipe over and press Delete) and type in the statement:select * from CF71.ORG

• Click the OK button. • Click Next> button to move to Parameters panel.

- Note that the Development Center has generated an input parameter to determine "whichQuery" is being requested.

• Click Next> button to move to Options panel. - Leave Specific name blank, leave the Jar ID unchanged, leave Java package

blank. - Indicate Database access as Static SQL using SQLJ.

Make sure you indicate Static SQL using SQLJ. - Make sure Build is checked.

• Click Finish button to generate and build the SQLJ stored procedure. If prompted for a userid and password, enter your userid and password.

__ 2. What basic messages did you receive in the Messages tab?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-5

Page 72: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center.

Note the sql iterator definitions for the SELECT statements.

Note the input parameter on the method statement.

How is the determination made for which SQL statement should be executed?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 4. Is there a difference in the way the SQL is executed in this procedure versus the JDBC program you generated in the previous section?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 5. Return to the Development Center desktop and Run your stored procedure. For the first run, give a value of 0 for WHICHQUERY.

__ 6. Your results should be in the Result panel.

__ 7. Which table was queried?

________________________________________________________________

__ 8. Click Run icon to execute your stored procedure. For the second run, give a value of 1 for WHICHQUERY.

__ 9. Your results should be in the Result panel.

__ 10. Which table was queried?

________________________________________________________________

__ 11. Click Run icon to execute your stored procedure. For the last run, give a value of 3 for WHICHQUERY (an invalid value).

__ 12. Your results should be in the Result panel.

__ 13. What do you see in the Result panel?

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-6 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 73: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 14. What do you see in the Messages panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

Noticed that there was not an indication that you entered an invalid value. The invalid value was handled by the Default statement in the Switch statement in your stored procedure. Essentially all that it did was return an empty result set.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-7

Page 74: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 3: JDBC Stored Procedure Returning Choice of Result Sets

__ 1. You've been asked to provide a Java JDBC stored procedure that will return either a result set of the CF71.STAFF table or a result set of the CF71.ORG table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_3. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Ensure Result set is set to One. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the push button in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate multiple SQL statements is selected.

• In SQL Statement panel, click SQL Assist button. • In SQL Assist window:

- In the Outline tree, click FROM. - Under Available tables, expand CF71. - Under CF71, select STAFF. - Click > to move STAFF to the selected tables area. - In the Selected tables area, select SYSCAT.PROCE... and click the < button.

What SQL statement was generated for you?

________________________________________________________________

• Click OK button to return to SQL Statement panel. • Click Add button to add another SQL statement. • With the second SQL statement area selected, click SQL Assist button. • In SQL Assist window:

- In the Outline tree, click FROM. - Under Available tables, expand CF71. - Under CF71, select ORG. - Click > to move ORG to the selected tables area. - In the Selected tables area, select SYSCAT.PROCE... and click the < button.

What SQL statement was generated for you?

________________________________________________________________

• Click OK button to return to SQL Statement panel. Then click OK to return to the Wizard panel.

• Click Next> button to move to Parameters panel.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-8 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 75: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

- Note that the Development Center has generated an input parameter to determine "whichQuery" is being requested.

• Click Next> button to move to Options panel. - Leave Specific name blank, leave the Jar ID unchanged, leave Java package

blank. - Indicate Database access as Dynamic SQL using JDBC. - Make sure Build is checked.

• Click Finish button to generate and build the JDBC stored procedure.

__ 2. What basic messages did you receive in the Messages tab?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center. Note the input parameter on the method statement. How is the determination made for which SQL statement should be executed?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 4. Return to the Development Center desktop.

__ 5. Run your stored procedure. For the first run, give a value of 0 for WHICHQUERY.

__ 6. Your results should be in the Result panel.

__ 7. Which table was queried?

________________________________________________________________

__ 8. Run your stored procedure. For the second run, give a value of 1 for WHICHQUERY.

__ 9. Your results should be in the Result panel.

__ 10. Which table was queried?

________________________________________________________________

__ 11. Click Run icon to execute your stored procedure. For the last run, give a value of 3 for WHICHQUERY (an invalid value).

__ 12. Your results should be in the Result panel.

__ 13. What do you see in the Result panel?

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-9

Page 76: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 14. Why did you get this result when you entered an invalid WHICHQUERY value? You did not get this result with your previous SQLJ stored procedure? Go back and edit your stored procedure. Look at the Default statement in the Switch statement. What do you see?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-10 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 77: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 4: SQLJ Stored Procedure Returning Choice of COUNTs

__ 1. You've been asked to provide an SQLJ stored procedure that will return either a count of the number of rows in the CF71.STAFF table or a count of the number of rows in the CF71.ORG table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_4. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Change the value for Result set to None. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the push button in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate multiple SQL statements is selected.

• In SQL Statement panel, type in these statements. (Columnar functions are not supported by the SQL Assist) The two statements we wish to be able to select from are: - SELECT COUNT(*) FROM CF71.STAFF - SELECT COUNT(*) FROM CF71.ORG

Note: Each SQL statement must be in a separate statement area. Click Add button for the second statement.

Note: You are missing the INTO clause of your SELECT statement. If you try to add that here, you will get an error. You will edit the stored procedure to add it in later.

• Click OK to return to the Wizard panel. • Click Next> button to move to Parameters panel.

- Note that the Development Center has generated an input parameter to determine "whichQuery" is being requested but you will have to define an output parameter for the count.

• Click the Add button. • Make sure Parameter mode is Out. • Change the Name to count. • Change the SQL type to Integer. • Click OK. • Click Next> button to move to Options panel.

- Leave Specific name blank, leave the Jar ID unchanged, leave Java package blank.

- Indicate Database access as Static SQL using SQLJ. Make sure you indicate Static SQL using SQLJ'. - Uncheck Build.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-11

Page 78: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

• Click Finish button. • Edit your stored procedure. • Under the statement SPContext ctx = null; add Int cnt = 0; • Update the two SELECT statements:

- From cursorX = SELECT COUNT(*) FROM ...

- To SELECT COUNT(*) INTO :cnt FROM...

• Towards the bottom of the stored procedure, change the statement:

count[0] = count[0]

to read count[0] = cnt;

• Save your stored procedure and return to the Development Center desktop.

__ 2. What basic messages did you receive in the Messages tab?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center.

Note the output parameter on the method definition.

How is the output parameter set?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 4. Return to the Development Center desktop and Run your stored procedure. For the first run, give a value of 0 for WHICHQUERY.

__ 5. There will not be anything in the Result panel. Why is that?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 6. Look at the Parameters panel. What is the count returned?

________________________________________________________________

__ 7. Run your stored procedure again. For the second run, give a value of 1 for WHICHQUERY.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-12 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 79: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 8. Look at the Parameter panel. What is the count returned?

________________________________________________________________

__ 9. Run your stored procedure a final time. For the last run, give a value of 3 for WHICHQUERY (an invalid value).

__ 10. Look at the Parameter panel. What is returned from the stored procedure?

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-13

Page 80: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 5: JDBC Stored Procedure Returning Choice of COUNTs

__ 1. You've been asked to provide a Java stored procedure that will return either a count of the rows of the CF71.STAFF table or a count of the rows of the CF71.ORG table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_5. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Change the value for Result set to None. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the pushbutton in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate multiple SQL statements is selected.

• In SQL Statement panel, type in these statements. (Columnar functions are not supported by the SQL Assist) The two statements we wish to be able to select from are: - SELECT COUNT(*) FROM CF71.STAFF - SELECT COUNT(*) FROM CF71.ORG

Note: Each SQL statement must be in a separate statement area. Click Add button for the second statement.

• Click OK to return to the Wizard panel. • Click Next> button to move to Parameters panel.

- Note that the Development Center has generated an input parameter to determine "whichQuery" is being requested. However, there is not an output parameter generated, so you need to add it: — Click Add button. — Parameter mode should be Out. — Name should be count. — SQL type should be int. — Click OK button.

• Click Next> button to move to Options panel. - Leave Specific name blank, leave the Jar ID unchanged, leave Java package

blank. - Indicate Database access as Dynamic SQL using JDBC. - Indicate Completion as Generate and build.

• Click Finish button to generate and build the JDBC stored procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-14 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 81: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 2. What messages did you receive in the Messages tab?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center.

If you do not know Java, it may not be apparent to you, but the code will just execute the statement, and no assignment is made to your output variable.

Find the area of code that is commented out but looks like:

// Access query results //while (rs1.next()) //{ // //}

Remove the comments (//) for the while and the next three lines and add a line to assign the result to your output variable:

// Access query results while (rs1.next()) { count [0] = rs1.getInt(1); }

__ 4. Save your stored procedure and return to the Development Center desktop.

__ 5. Build your stored procedure and then Run it.

When prompted that changes have been detected, indicate Build all changes to the database, then run the procedure. Click OK button.

For the first run, give a value of 0 for WHICHQUERY.

__ 6. Look at the Parameter panel. What is the count returned?

________________________________________________________________

__ 7. Run your stored procedure again. For the second run, give a value of 1 for WHICHQUERY.

__ 8. Look at the Parameter panel. What is the count returned?

________________________________________________________________

__ 9. Run your stored procedure a final time. For the last run, give a value of 3 for WHICHQUERY (an invalid value).

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-15

Page 82: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 10. Look at the Messages panel. Did you get an error? Why is this?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-16 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 83: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 6: Generate JDBC Stored Procedure for Further Coding

__ 1. You've been asked to provide a Java stored procedure skeleton that can be used by experienced Java programmers to provide a coded solution.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_6. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Ensure Result set is set to None.

Note: If you knew that the programmer was intending to create a stored procedure that returned a result set, you could leave this checked.

- For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the pushbutton in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate no SQL statement is selected. • Click OK and return to the Wizard panel. • Click Next> button. • Click Next> button to move to Parameters panel. No parameters - neither input

nor output. • Click Next> button to move to Options panel.

- Leave Specific name blank, leave the Jar ID unchanged, leave Java package blank.

- Indicate Database access as Dynamic SQL using JDBC. - Uncheck Build.

• Click Finish button to generate the JDBC stored procedure.

__ 2. There should not have been any messages?

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center.

Note that the DB2 Development Center has just created the structure of the stored procedure - no specific code has been included except for a connection statement.

This code could now be supplied to an experienced Java programmer for them to add JDBC code.

__ 4. Save your project.

• Return to the Development Center desktop.

• Right-click your project - CF71 and select Save Project.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-17

Page 84: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 7: Stored Procedure Source Code

The source for the stored procedures created for this lab exercise will be found in Section 7 of the solutions.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-18 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 85: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise Solutions

Section 1: JDBC Stored Procedure Returning Result Set

__ 1. You've been asked to provide a Java stored procedure that will return a result set of the CF71.STAFF table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_1. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Ensure Result set is set to One. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the push button in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate one SQL statement is selected.

• In SQL Statement panel, click SQL Assist button. • In SQL Assist window:

- In the Outline tree, click FROM. - Under Available tables, expand CF71. - Under CF71, select STAFF. - Click > to move STAFF to the selected tables area. - In the Selected tables area, select SYSCAT.PROCE... and click the < button

to remove that entry. - In the Outline tree, click SELECT (Result columns). - Under Available columns, expand CF71.STAFF and for each column, select it

and click the > button. (Or you can do a Windows Shift select to select all of the columns in order to move them all at once).

What SQL statement was generated for you?

SELECT STAFF.ID, STAFF.NAME, STAFF.DEPT, STAFF.JOB, STAFF.YEARS, STAFF.SALARY,STAFF.COMM

FROM CF71.STAFF

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-19

Page 86: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

• Click OK button to return to SQL Statement panel. Then click the OK button. • Click Next> button to move to Parameters panel. No changes required on

Parameters panel. • Click Next> button to move to Options panel.

- Leave Specific name blank, leave the Jar ID unchanged, leave Java package blank.

- Indicate Database access as Dynamic SQL using JDBC. - Make sure Build is checked.

• Click Finish button to generate and build the JDBC stored procedure.

__ 2. What basic messages did you receive in the Messages tab?

CF71.LAB4_1 - Build started.

CF71.LAB4_1 - Javac completed.

CF71.LAB4_1 - Jar file created.

CF71.LAB4_1 - sqlj.install_jar using jar name "ADMIN".SQLnnnnnnnnnnnnn completed

CF71.LAB4_1 - sqlj.refresh_classes completed.

CF71.LAB4_1 - Source updated.

CF71.LAB4_1 - Create stored procedure completed.

CF71.LAB4_1 - Build successful.

__ 3. Right-click your stored procedure (CF71.LAB4_1) and select Edit. Find the SQL statement generated by the DB2 Development Center. How is the SQL statement passed to the database manager?

• The SQL statement is assigned to a variable (which happens to be named sql)

• The variable is subsequently prepared: stmt = con.prepareStatement(sql)

• and executed: rs1[0] = stmt.execute().

__ 4. Return to the Development Center desktop.

__ 5. Run your stored procedure.

__ 6. Your results should be in the Result panel.

__ 7. Congratulations! You've just completed your first Java stored procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-20 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 87: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 2: SQLJ Stored Procedure Returning Choice of Results Sets

__ 1. You've been asked to provide an SQLJ stored procedure that will return either a result set of the CF71.STAFF table or a result set of the CF71.ORG table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_2. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Ensure Result set is set to One. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the pushbutton in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate multiple SQL statements is selected.

• In SQL Statement panel, instead of using the SQL Assistant this time, just type in the statement you want to execute. Swipe over the statement that is provided by default (select from syscat.procedures) and replace the statement with:

select * from cf71.staff • Click Add button to add another SQL statement. • With the second SQL statement area selected, erase the statement that is there

(swipe over and press Delete) and type in the statement:select * from CF71.ORG

• Click the OK button. • Click Next> button to move to Parameters panel

- Note that the Development Center has generated an input parameter to determine "whichQuery" is being requested.

• Click Next> button to move to Options panel. - Leave Specific name blank, leave the Jar ID unchanged, leave Java package

blank. - Indicate Database access as Static SQL using SQLJ.

Make sure you indicate Static SQL using SQLJ. - Make sure Build is checked.

• Click Finish button to generate and build the SQLJ stored procedure. If prompted for a userid and password, enter your userid and password.

__ 2. What basic messages did you receive in the Messages tab?

CF71.LAB4_2 - Build started.

CF71.LAB4_2 - sqlj -compile=false -profile=false -ser2class=false LAB4_2.sqlj

CF71.LAB4_2 - SQLJ precompilation completed.

CF71.LAB4_2 - Javac completed.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-21

Page 88: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

CF71.LAB4_2 - Class file updated.

Four packages were bound.

CF71.LAB4_2 - SQLJ profile customization complete

CF71.LAB4_2 - Jar file created.

CF71.LAB4_2 - sqlj.install_jar using jar name "ADMIN".SQLnnnnnnnnnnnnn completed

CF71.LAB4_2 - sqlj.refresh_classes completed.

CF71.LAB4_2 - Source updated.

CF71.LAB4_2 - Create stored procedure completed.

CF71.LAB4_2 - Build successful.

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center.

Note the sql iterator definitions for the SELECT statements.

Note the input parameter on the method statement.

How is the determination made for which SQL statement should be executed?

A Java switch statement is inserted to determine what the value of sql should be based on the input value of whichQuery.

__ 4. Is there a difference in the way the SQL is executed in this procedure versus the JDBC program you generated in the previous section?

In the SQLJ program, the execution of the SELECT statement is done via a #sql statement, passing the SQL statement in much the same format that you originally coded it.

__ 5. Return to the Development Center desktop and Run your stored procedure. For the first run, give a value of 0 for WHICHQUERY.

__ 6. Your results should be in the Result panel.

__ 7. Which table was queried?

CF71.STAFF table was queried.

__ 8. Click Run icon to execute your stored procedure. For the second run, give a value of 1 for WHICHQUERY.

__ 9. Your results should be in the Result panel.

__ 10. Which table was queried?

CF71.ORG table was queried.

__ 11. Click Run icon to execute your stored procedure. For the last run, give a value of 3 for WHICHQUERY (an invalid value).

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-22 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 89: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 12. Your results should be in the Result panel.

__ 13. What do you see in the Result panel?

Nothing displayed in the results panel.

__ 14. What do you see in the Messages panel?

CF71.LAB4_2 - Run started.

CF71.LAB4_2 - Calling the stored procedure.

CF71.LAB4_2 - Run completed.

Noticed that there was not an indication that you entered an invalid value. The invalid value was handled by the Default statement in the Switch statement in your stored procedure. Essentially all that it did was return an empty result set.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-23

Page 90: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 3: JDBC Stored Procedure Returning Choice of Result Sets

__ 1. You've been asked to provide a Java JDBC stored procedure that will return either a result set of the CF71.STAFF table or a result set of the CF71.ORG table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and clicks OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_3. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Ensure Result set is set to One. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the pushbutton in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate multiple SQL statements is selected.

• In SQL Statement panel, click SQL Assist button. • In SQL Assist window:

- In the Outline tree, click FROM. - Under Available tables, expand CF71. - Under CF71, select STAFF. - Click > to move STAFF to the selected tables area. - In the Selected tables area, select SYSCAT.PROCE... and click the < button.

What SQL statement was generated for you?

SELECT * FROM CF71.STAFF AS STAFF

• Click OK button to return to SQL Statement panel. • Click Add button to add another SQL statement. • With the second SQL statement area selected, click SQL Assist button. • In SQL Assist window:

- In the Outline tree, click FROM. - Under Available tables, expand CF71. - Under CF71, select ORG. - Click > to move ORG to the selected tables area. - In the Selected tables area, select SYSCAT.PROCE... and click the < button.

What SQL statement was generated for you?

SELECT * FROM CF71.ORG AS ORG

• Click OK button to return to SQL Statement panel. Then click OK to return to the Wizard panel.

• Click Next> button to move to Parameters panel.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-24 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 91: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

- Note that the Development Center has generated an input parameter to determine "whichQuery" is being requested.

• Click Next> button to move to Options panel. - Leave Specific name blank, leave the Jar ID unchanged, leave Java package

blank. - Indicate Database access as Dynamic SQL using JDBC. - Make sure Build is checked.

• Click Finish button to generate and build the JDBC stored procedure.

__ 2. What basic messages did you receive in the Messages tab?

CF71.LAB4_3 - Build started.

CF71.LAB4_3 - Javac completed.

CF71.LAB4_3 - Jar file created.

CF71.LAB4_3 - sqlj.install_jar using jar name "ADMIN".SQLnnnnnnnnnnnnn completed

CF71.LAB4_3 - sqlj.refresh_classes completed.

CF71.LAB4_3 - Source updated.

CF71.LAB4_3 - Create stored procedure completed.

CF71.LAB4_3 - Build successful.

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center. Note the input parameter on the method statement. How is the determination made for which SQL statement should be executed?

A Java switch statement is inserted to determine what the value of sql should be based on the input value of whichQuery.

__ 4. Return to the Development Center desktop.

__ 5. Run your stored procedure. For the first run, give a value of 0 for WHICHQUERY.

__ 6. Your results should be in the Result panel.

__ 7. Which table was queried?

CF71.STAFF table was queried.

__ 8. Run your stored procedure. For the second run, give a value of 1 for WHICHQUERY.

__ 9. Your results should be in the Result panel.

__ 10. Which table was queried?

CF71.ORG table was queried.

__ 11. Click Run icon to execute your stored procedure. For the last run, give a value of 3 for WHICHQUERY (an invalid value).

__ 12. Your results should be in the Result panel.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-25

Page 92: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 13. What do you see in the Result panel?

You see results returned from a query against SYSCAT.PROCEDURES.

__ 14. Why did you get this result when you entered an invalid WHICHQUERY value? You did not get this result with your previous SQLJ stored procedure? Go back and edit your stored procedure. Look at the Default statement in the Switch statement. What do you see?

There is an additional select statement that will execute as the default. This was not the case with the SQLJ stored procedure. Obviously there were at least two programmers involved in coding the Java stored procedure wizard.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-26 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 93: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 4: SQLJ Stored Procedure Returning Choice of COUNTs

__ 1. You've been asked to provide an SQLJ stored procedure that will return either a count of the number of rows in the CF71.STAFF table or a count of the number of rows in the CF71.ORG table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_4. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Change the value for Result set to None. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the pushbutton in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate multiple SQL statements is selected.

• In SQL Statement panel, type in these statements. (Columnar functions are not supported by the SQL Assist) The two statements we wish to be able to select from are: - SELECT COUNT(*) FROM CF71.STAFF - SELECT COUNT(*) FROM CF71.ORG

Note: Each SQL statement must be in a separate statement area. Click Add button for the second statement.

Note: You are missing the INTO clause of your SELECT statement. If you try to add that here, you will get an error. You will edit the stored procedure to add it in later.

• Click OK to return to the Wizard panel. • Click Next> button to move to Parameters panel.

- Note that the Development Center has generated an input parameter to determine "whichQuery" is being requested but you will have to define an output parameter for the count.

• Click the Add button. • Make sure Parameter mode is Out. • Change the Name to count. • Change the SQL type to Integer. • Click OK. • Click Next> button to move to Options panel.

- Leave Specific name blank, leave the Jar ID unchanged, leave Java package blank.

- Indicate Database access as Static SQL using SQLJ. Make sure you indicate Static SQL using SQLJ'. - Uncheck Build.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-27

Page 94: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

• Click Finish button. • Edit your stored procedure. • Under the statement SPContext ctx = null; add Int cnt = 0; • Update the two SELECT statements:

- From cursorX = SELECT COUNT(*) FROM ...

- To SELECT COUNT(*) INTO FROM...

• Towards the bottom of the stored procedure, change the statement:

count[0] = count[0]

to read count[0] = cnt;

• Save your stored procedure and return to the Development Center desktop.

__ 2. What basic messages did you receive in the Messages tab?

CF71.LAB4_4 - Build started.

CF71.LAB4_4 - sqlj -compile=false -profile=false -ser2class=false LAB4_4.sqlj

CF71.LAB4_4 - SQLJ precompilation completed.

CF71.LAB4_4 - Javac completed.

CF71.LAB4_4 - Class file updated.

Four packages created

CF71.LAB4_4 - SQLJ profile customization completed

CF71.LAB4_4 - Jar file created.

CF71.LAB4_4 - sqlj.install_jar using jar name "ADMIN".SQLnnnnnnnnnnnnn complete

CF71.LAB4_4 - sqlj.refresh_classes completed.

CF71.LAB4_4 - Source updated.

CF71.LAB4_4 - Create stored procedure completed.

CF71.LAB4_4 - Build successful.

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center.

Note the output parameter on the method definition.

How is the output parameter set?

Your ability to understand this code may depend on your background with Java, but the following occurs:

• The DB2 Development Center creates a single element array named count on the method definition.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-28 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 95: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 4. Return to the Development Center desktop and Run your stored procedure. For the first run, give a value of 0 for WHICHQUERY.

__ 5. There will not be anything in the Result panel. Why is that?

The Result panel is for result sets. This stored procedure is returning a value as a parameter.

__ 6. Look at the Parameters panel. What is the count returned?

count = 35

__ 7. Run your stored procedure again. For the second run, give a value of 1 for WHICHQUERY.

__ 8. Look at the Parameter panel. What is the count returned?

count = 8

__ 9. Run your stored procedure a final time. For the last run, give a value of 3 for WHICHQUERY (an invalid value).

__ 10. Look at the Parameter panel. What is returned from the stored procedure?

count = 0

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-29

Page 96: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 5: JDBC Stored Procedure Returning Choice of COUNTs

__ 1. You've been asked to provide a Java stored procedure that will return either a count of the rows of the CF71.STAFF table or a count of the rows of the CF71.ORG table.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_5. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Change the value for Result set to None. - For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the pushbutton in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate multiple SQL statements is selected.

• In SQL Statement panel, type in these statements. (Columnar functions are not supported by the SQL Assist) The two statements we wish to be able to select from are: - SELECT COUNT(*) FROM CF71.STAFF - SELECT COUNT(*) FROM CF71.ORG

Note: Each SQL statement must be in a separate statement area. Click Add button for the second statement.

• Click OK to return to the Wizard panel. • Click Next> button to move to Parameters panel.

- Note that the Development Center has generated an input parameter to determine "whichQuery" is being requested. However, there is not an output parameter generated, so you need to add it: — Click Add button. — Parameter mode should be Out. — Name should be count. — SQL type should be int. — Click OK button.

• Click Next> button to move to Options panel. - Leave Specific name blank, leave the Jar ID unchanged, leave Java package

blank. - Indicate Database access as Dynamic SQL using JDBC. - Indicate Completion as Generate and build.

• Click Finish button to generate and build the JDBC stored procedure.

__ 2. What messages did you receive in the Messages tab?

CF71.LAB4_5 - Build started.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-30 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 97: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

CF71.LAB4_5 - Javac completed.

CF71.LAB4_5 - Jar file created.

CF71.LAB4_5 - sqlj.install_jar using jar name "ADMIN".SQLnnnnnnnnn complete

CF71.LAB4_5 - sqlj.refresh_classes completed.

CF71.LAB4_5 - Source updated.

CF71.LAB4_5 - Create stored procedure completed.

CF71.LAB4_5 - Build successful.

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center.

If you do not know Java, it may not be apparent to you, but the code will just execute the statement, and no assignment is made to your output variable.

Find the area of code that is commented out but looks like:

// Access query results //while (rs1.next()) //{ // //}

Remove the comments (//) for the while and the next three lines and add a line to assign the result to your output variable:

// Access query results while (rs1.next()) { count [0] = rs1.getInt(1); }

__ 4. Save your stored procedure and return to the Development Center desktop.

__ 5. Build your stored procedure and then Run it.

When prompted that changes have been detected, indicate Build all changes to the database, then run the procedure. Click OK button.

For the first run, give a value of 0 for WHICHQUERY.

__ 6. Look at the Parameter panel. What is the count returned?

count = 35

__ 7. Run your stored procedure again. For the second run, give a value of 1 for WHICHQUERY.

__ 8. Look at the Parameter panel. What is the count returned?

count = 8

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-31

Page 98: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 9. Run your stored procedure a final time. For the last run, give a value of 3 for WHICHQUERY (an invalid value).

__ 10. Look at the Messages panel. Did you get an error? Why is this?

Once again for the JDBC stored procedure, a default SELECT statement was generated. Since you did not change it, it is not returning the same type of data that the other two SELECT statements return. So you get an exception.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-32 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 99: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 6: Generate JDBC Stored Procedure for Further Coding

__ 1. You've been asked to provide a Java stored procedure skeleton that can be used by experienced Java programmers to provide a coded solution.

• Right-click Stored Procedures folder icon. Click New->Stored Procedure Using Wizard.

• On the New Object panel, select Java and click OK. • In Create Java Stored Procedure Wizard window:

- Set Name: CF71.LAB4_6. • Click Next> button. Any changes can be made by clicking the button on the right

side of any of the value fields. - Ensure Result set is set to None.

Note: If you knew that the programmer was intending to create a stored procedure that returned a result set, you could leave this checked.

- For Errors, indicate Generate an SQLException if an SQL error occurs. - Click the pushbutton in the value field for Statement. The SQL Statement

panel should display. Make sure that Generate no SQL statement is selected. • Click OK and return to the Wizard panel. • Click Next> button. • Click Next> button to move to Parameters panel. No parameters - neither input

nor output. • Click Next> button to move to Options panel.

- Leave Specific name blank, leave the Jar ID unchanged, leave Java package blank.

- Indicate Database access as Dynamic SQL using JDBC. - Uncheck Build.

• Click Finish button to generate the JDBC stored procedure.

__ 2. There should not have been any messages?

__ 3. Edit your stored procedure and look at the code generated by the DB2 Development Center.

Note that the DB2 Development Center has just created the structure of the stored procedure - no specific code has been included except for a connection statement.

This code could now be supplied to an experienced Java programmer for them to add JDBC code.

__ 4. Save your project.

• Return to the Development Center desktop.

• Right-click your project - CF71 and select Save Project.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-33

Page 100: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 7: Stored Procedure Source Code

1. LAB4_1

/** * JDBC Stored Procedure CF71.LAB4_1 */ import java.sql.*; // JDBC classes public class LAB4_1 { public static void lAB4_1 ( ResultSet[] rs1 ) throws SQLException, Exc { // Get connection to the database Connection con = DriverManager.getConnection("jdbc:default:connection"); PreparedStatement stmt = null; boolean bFlag; String sql; sql = "SELECT" + " CF71.STAFF.ID AS ID," + " CF71.STAFF.NAME AS NAME," + " CF71.STAFF.DEPT AS DEPT," + " CF71.STAFF.JOB AS JOB," + " CF71.STAFF.YEARS AS YEARS," + " CF71.STAFF.SALARY AS SALARY," + " CF71.STAFF.COMM AS COMM" + " FROM" + " CF71.STAFF"; stmt = con.prepareStatement( sql ); bFlag = stmt.execute(); rs1[0] = stmt.getResultSet();// this following statement should be added if (con != null) con.close(); } }

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-34 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 101: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

2. LAB4_2

#sql iterator LAB4_2_Cursor2 ( short, String, short, String, String );

public class LAB4_2{ public static void lAB4_2 ( int whichQuery, ResultSet[] rs1 ) throws SQLException, Exception { LAB4_2_Cursor1 cursor1 = null; LAB4_2_Cursor2 cursor2 = null; SPContext ctx = null; try { ctx = new SPContext( "jdbc:default:connection", false ); switch (whichQuery) { case 0: #sql [ctx] cursor1 = { select * from cf71.staff }; rs1[0] = cursor1.getResultSet(); break; case 1: #sql [ctx] cursor2 = { select * from cf71.org }; rs1[0] = cursor2.getResultSet(); break; default: break; } } catch (SQLException e) {

// Close open resources try { if (cursor1 != null) cursor1.close(); if (cursor2 != null) cursor2.close(); if (ctx != null) ctx.close(); } catch (SQLException e2) { /* ignore */ }; throw e; } }}

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-35

Page 102: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

3. LAB4_3

/** * JDBC Stored Procedure CF71.LAB4_3 */import java.sql.*; // JDBC classes

public class LAB4_3{ public static void lAB4_3 ( int whichQuery, ResultSet[] rs1 ) throws SQLException, Exception { // Get connection to the database Connection con = DriverManager.getConnection("jdbc:default:connection"); PreparedStatement stmt = null; boolean bFlag; String sql;

switch (whichQuery) { case 0: sql = "SELECT * " + " " + " FROM CF71.STAFF AS STAFF"; stmt = con.prepareStatement( sql ); break; case 1: sql = "SELECT * " + " " + " FROM CF71.ORG AS ORG"; stmt = con.prepareStatement( sql ); break; default: sql = "SELECT PROCSCHEMA, PROCNAME FROM SYSCAT.PROCEDURES"; stmt = con.prepareStatement( sql ); } bFlag = stmt.execute(); rs1[0] = stmt.getResultSet(); }}

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-36 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 103: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

4. LAB4_4

/** * JDBC Stored Procedure CF71.LAB4_4 */import java.sql.*; // JDBC classes

/** * SQLJ Stored Procedure CF71.LAB4_4 * @param count */import java.sql.*; // JDBC classesimport sqlj.runtime.*;import sqlj.runtime.ref.*;#sql context SPContext;

#sql iterator LAB4_4_Cursor1 ( int );#sql iterator LAB4_4_Cursor2 ( int );

public class LAB4_4{ public static void lAB4_4 ( int whichQuery,

int[] count ) throws SQLException, Exception { LAB4_4_Cursor1 cursor1 = null; LAB4_4_Cursor2 cursor2 = null; SPContext ctx = null; int cnt = 0; try { ctx = new SPContext( "jdbc:default:connection", false ); switch (whichQuery) { case 0: #sql [ctx] { SELECT COUNT(*) INTO :cnt FROM CF71.STAFF }; break; case 1: #sql [ctx] { SELECT COUNT(*) INTO :cnt FROM CF71.ORG }; break; default: break; } // Sample code to access the results // ResultSet rs1 = null; // switch(whichQuery) // {

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-37

Page 104: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

// case 0 : // rs1 = cursor1.getResultSet(); // break; // case 1 : // rs1 = cursor2.getResultSet(); // break; // } // while (rs1.next()) // { // // }

// Close open resources if (cursor1 != null) cursor1.close(); if (cursor2 != null) cursor2.close();

// Set return parameter count[0] = cnt; } catch (SQLException e) {

// Close open resources try { if (cursor1 != null) cursor1.close(); if (cursor2 != null) cursor2.close(); if (ctx != null) ctx.close(); } catch (SQLException e2) { /* ignore */ }; throw e; } }}

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-38 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 105: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

5. LAB4_5

/** * JDBC Stored Procedure CF71.LAB4_4 */import java.sql.*; // JDBC classes

/** * SQLJ Stored Procedure CF71.LAB4_4 * @param count */import java.sql.*; // JDBC classesimport sqlj.runtime.*;import sqlj.runtime.ref.*;#sql context SPContext;

#sql iterator LAB4_41_Cursor1 ( int );#sql iterator LAB4_41_Cursor2 ( int );

public class LAB4_41{ public static void lAB4_41 ( int whichQuery, int[] count ) throws SQLException, Exception { LAB4_41_Cursor1 cursor1 = null; LAB4_41_Cursor2 cursor2 = null; SPContext ctx = null; int cnt = 0; try { ctx = new SPContext( "jdbc:default:connection", false ); switch (whichQuery) { case 0: #sql [ctx] { SELECT COUNT(*) INTO :cnt FROM CF71.STAFF }; break; case 1: #sql [ctx] { SELECT COUNT(*) INTO :cnt FROM CF71.ORG }; break; default: break; } // Sample code to access the results // ResultSet rs1 = null; // switch(whichQuery) // {

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-39

Page 106: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

// case 0 : // rs1 = cursor1.getResultSet(); // break; // case 1 : // rs1 = cursor2.getResultSet(); // break; // } // while (rs1.next()) // { // // }

// Close open resources if (cursor1 != null) cursor1.close(); if (cursor2 != null) cursor2.close();

// Set return parameter count[0] = cnt; } catch (SQLException e) {

// Close open resources try { if (cursor1 != null) cursor1.close(); if (cursor2 != null) cursor2.close(); if (ctx != null) ctx.close(); } catch (SQLException e2) { /* ignore */ }; throw e; } }}

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-40 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 107: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

6. LAB4_6

/** * JDBC Stored Procedure CF71.LAB4_6 */ import java.sql.*; // JDBC classes public class LAB4_6 { public static void lAB4_6 ( ) throws SQLException, Exception { // Get connection to the database Connection con = DriverManager.getConnection("jdbc:default:connection"); PreparedStatement stmt = null; String sql; if (con != null) con.close(); } }

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 4. Building Java Stored Procedures 4-41

Page 108: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-42 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 109: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise 5. Calling Procedures

What This Exercise Is About

This exercise provides an opportunity for the students to build stored procedures that will CALL other stored procedures.

What You Should Be Able to Do

At the end of the lab, you should be able to:

• Create a stored procedure written in SQL Procedure Language that will CALL a stored procedure that returns values in a parameter

• Create a stored procedure written in SQL Procedure Language that will CALL a stored procedure that returns a result set

Introduction

This lab has several sections:

• Section 1: Create an SQL Stored Procedure that will CALL another stored procedure passing values through the parameters only.

• Section 2: Create an SQL Stored Procedure that will CALL another stored procedure that will return a result set.

• Section 3: Stored procedure source code listings.

In Section 1, you will create a new stored procedure. That stored procedure will CALL a stored procedure. The only data exchanged will be through parameters on the CALL statement.

In Section 2, you will create a new stored procedure. That stored procedure will CALL a stored procedure. The CALLed stored procedure will return a result set that must be processed by the calling procedure.

Section 3 provides a listing of the stored procedures source.

Required Materials

• Student notebook for SQL Procedure Language statement syntax. • DB2 Info Center for SQL Procedure Language statement syntax

(optional).

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 5. Calling Procedures 5-1

Page 110: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Exercise Instructions

The lab solutions can be found in “Exercise Solutions” on page 5-7.

Section 1: CALL with Parameters

In this section, you will build a stored procedure, Lab5_1, that will CALL a stored procedure that returns values through the calling parameters.

__ 1. An existing procedure, CF71.LAB3_3, returns the employee ID and salary of the highest paid employee. A request has come in for a new procedure that will return the employee ID and salary of the employee that has the next higher employee ID. Since you know that our employee IDs are in increments of 10, this should be easy to do.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.Lab5_1.

__ 2. Define the parameters your new procedure will need.

• First parameter should be SMALLINT to return an employee's ID. • Second parameter should be DEC(7,2) to return an employee's salary.

__ 3. Include the following local DECLARES:

• at_end a small integer initialized to 0 • call_id a small integer initialized to 0 • call_salary DEC(7,2) initialized to 0.0 • not_found as a condition for SQLSTATE '02000' • A handler for not_found that will set at_end to a value of 1 and resume

execution at the next statement

__ 4. CALL CF71.LAB3_3 in your new stored procedure to return the ID and salary of the highest paid employee.

__ 5. Code the SELECT statement that will return the ID and salary of the desired employee. Keep in mind that our employee IDs are in increments of 10.

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 6. Save your stored procedure and return to the Development Center desktop.

__ 7. Build your stored procedure.

__ 8. Run your procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-2 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 111: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 9. What was in the Parameters panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 5. Calling Procedures 5-3

Page 112: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 2: Processing a Result Set from a CALL

In this section, you will build a stored procedure, Lab5_2, that will have to handle a result set from a stored procedure CALL.

__ 1. You've been asked to provide a stored procedure that will use an existing procedure's result set to determine the average salary of all employees whose salary exceeds the median salary.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.Lab5_2.

__ 2. Define the parameters your new procedure will need.

• First, and only, parameter should be DEC(7,2) to return the average high salary.

__ 3. Include a DECLARE for a result set locator.

__ 4. Include the following local DECLARES:

• v_ctr a small integer initialized to 0 • v_accumsalary DEC(10,2) • v_id a small integer initialized to 0 • v_name VARCHAR(9) initialized to blanks • v_salary DEC(7,2) initialized to 0.0 • at_end a small integer initialized to 0 • not_found as a condition for SQLSTATE '02000' • A handler for not_found that will set at_end to a value of 1 and resume

execution at the next statement

__ 5. CALL CF71.LAB3_6 to get result set of rows > median salary. This procedure will also pass the median salary in a parameter. Remember you must have an ASSOCIATE and ALLOCATE statement after the CALL.

__ 6. Use the REPEAT construct to FETCH all the rows in the result set. Accumulate the salaries and keep track of the count to calculate the average.

__ 7. Calculate the average of the rows returned. This should be in your output parameter. Remember that your counter will be 1 larger than the number of rows FETCHed.

__ 8. Good programming technique would dictate closing the cursor you were processing.

__ 9. Save your stored procedure and return to the Development Center desktop.

__ 10. Build your stored procedure.

__ 11. Run your procedure.

__ 12. The Parameters panel should display the average of all salaries greater than the median salary.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-4 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 113: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

What was in the Results panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 5. Calling Procedures 5-5

Page 114: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 3: Stored Procedure Source Code

The source for the stored procedures created for this lab exercise will be found in Section 3 of the solutions.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-6 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 115: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise Solutions

Section 1: CALL with Parameters

In this section, you will build a stored procedure, Lab5_1, that will CALL a stored procedure that returns values through the calling parameters.

__ 1. An existing procedure, CF71.LAB3_3, returns the employee ID and salary of the highest paid employee. A request has come in for a new procedure that will return the employee ID and salary of the employee that has the next higher employee ID. Since you know that our employee IDs are in increments of 10, this should be easy to do.

• Right-click folder icon Stored Procedures. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.Lab5_1.

__ 2. Define the parameters your new procedure will need.

CREATE PROCEDURE CF71.Lab5_1 (OUT employee_id SMALLINT, OUT employee_salary DEC(7,2))

__ 3. Include the following local DECLARES:

DECLARE at_end SMALLINT DEFAULT 0; DECLARE call_id SMALLINT DEFAULT 0; DECLARE call_salary DEC(7,2) DEFAULT 0.0; DECLARE not_found CONDITION FOR SQLSTATE '02000'; DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1;

__ 4. CALL CF71.LAB3_3 in your new stored procedure to return the ID and salary of the highest paid employee.

-- call procedure LAB3_3 to find id of highest salaried employee CALL CF71.LAB3_3 (call_id,call_salary);

__ 5. Code the SELECT statement that will return the ID and salary of the desired employee. Keep in mind that our employee IDs are in increments of 10.

-- select id and salary of employee with next id (id increment by 10)SELECT id, salary

INTO employee_id, employee_salary FROM CF71.STAFF WHERE id = (call_id + 10);

__ 6. Save your stored procedure and return to the Development Center desktop.

__ 7. Build your stored procedure.

__ 8. Run your procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 5. Calling Procedures 5-7

Page 116: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 9. What was in the Parameters panel?

The values of the output parameters: EMPLOYEE_ID = 320EMPLOYEE_SALARY = 16858.20

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-8 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 117: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 2: Processing a Result Set from a CALL

In this section, you will build a stored procedure, Lab5_2, that will have to handle a result set from a stored procedure CALL.

__ 1. You've been asked to provide a stored procedure that will use an existing procedure's result set to determine the average salary of all employees whose salary exceeds the median salary.

• Right-click Stored Procedures folder icon. Click New -> SQL Stored Procedure. • Look for CREATE PROCEDURE DDL statement. • Change the procedure name to CF71.Lab5_2.

__ 2. Define the parameters your new procedure will need.

CREATE PROCEDURE CF71.Lab5_2 (OUT avgHiSalary DEC(7,2))

__ 3. Include a DECLARE for a result set locator.

DECLARE loc1 RESULT_SET_LOCATOR VARYING;

__ 4. Include the following local DECLARES:

DECLARE v_ctr SMALLINT DEFAULT 0; DECLARE v_accumsalary DEC(10,2); DECLARE v_id SMALLINT DEFAULT 0; DECLARE v_name VARCHAR(9) DEFAULT ' '; DECLARE v_salary DEC (7,2) DEFAULT 0.0; DECLARE at_end SMALLINT DEFAULT 0; DECLARE not_found CONDITION FOR SQLSTATE '02000'; DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1;

__ 5. CALL CF71.LAB3_6 to get result set of rows > median salary. This procedure will also pass the median salary in a parameter. Remember you must have an ASSOCIATE and ALLOCATE statement after the CALL.

CALL CF71.LAB3_6(v_salary); ASSOCIATE RESULT SET LOCATORS (loc1)

WITH PROCEDURE CF71.LAB3_6; ALLOCATE c1 CURSOR FOR RESULT SET loc1;

__ 6. Use the REPEAT construct to FETCH all the rows in the result set. Accumulate the salaries and keep track of the count to calculate the average.

fetch_loop:REPEAT

FETCH c1 INTOv_id, v_name, v_salary;

SET v_accumsalary = v_accumsalary + v_salary;SET v_ctr = v_ctr + 1;

UNTIL at_end <> 0 END REPEAT fetch_loop;

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 5. Calling Procedures 5-9

Page 118: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 7. Calculate the average of the rows returned. This should be in your output parameter. Remember that your counter will be 1 larger than the number of rows FETCHed.

-- calc the average / v_ctr will be 1 higher than needed IF (v_ctr > 1)

THENSET avgHiSalary = v_accumsalary / (v_ctr-1);

ELSE SET avgHiSalary = v_salary;

END IF;

__ 8. Good programming technique would dictate closing the cursor you were processing.

-- close cursor CLOSE c1;

__ 9. Save your stored procedure and return to the Development Center desktop.

__ 10. Build your stored procedure.

__ 11. Run your procedure.

__ 12. The Parameters panel should display the average of all salaries greater than the median salary.

What was in the Parameters panel?

The values of the output parameters:AVGHISALARY = 18693.00

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-10 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 119: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 3: Stored Procedure Source Code

1. LAB5_1

CREATE PROCEDURE CF71.Lab5_1 (OUT employee_id SMALLINT, OUT employee_salary DEC(7,2)) LANGUAGE SQL ------------------------------------------------------------------------ -- SQL Stored Procedure -- Use CALL to LAB3_3 to find highest salaried employee -- in order to return id and salary of next employee ------------------------------------------------------------------------ P1: BEGIN DECLARE at_end SMALLINT DEFAULT 0; DECLARE call_id SMALLINT DEFAULT 0; DECLARE call_salary DEC(7,2) DEFAULT 0.0; DECLARE not_found CONDITION FOR SQLSTATE '02000'; DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1; -- call procedure LAB3_3 to find id of highest salaried employee CALL CF71.LAB3_3 (call_id,call_salary); -- select id and salary of employee with next id (id increment by 10) SELECT id, salary INTO employee_id, employee_salary FROM CF71.STAFF WHERE id = (call_id + 10); -- that's all END P1

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 5. Calling Procedures 5-11

Page 120: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

2. LAB5_2

CREATE PROCEDURE CF71.Lab5_2 ( OUT avgHiSalary DEC(7,2) ) LANGUAGE SQL ------------------------------------------------------------------------ -- SQL Stored Procedure -- CALL CF71.LAB3_6 to return all salaries > median -- calculate and return the average of those salaries ------------------------------------------------------------------------ P1: BEGIN DECLARE loc1 RESULT_SET_LOCATOR VARYING; DECLARE v_ctr SMALLINT DEFAULT 0; DECLARE v_accumsalary DEC(10,2); DECLARE v_id SMALLINT DEFAULT 0; DECLARE v_name VARCHAR(9) DEFAULT ' '; DECLARE v_salary DEC (7,2) DEFAULT 0.0; -- DECLARE at_end SMALLINT DEFAULT 0; DECLARE not_found CONDITION FOR SQLSTATE '02000'; DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1; -- call LAB3_6 / associate locator and allocate cursor CALL CF71.LAB3_6(v_salary); ASSOCIATE RESULT SET LOCATORS (loc1) WITH PROCEDURE CF71.LAB3_6; ALLOCATE c1 CURSOR FOR RESULT SET loc1; -- fetch all result rows and accumulate salary SET v_accumsalary = 0; fetch_loop: REPEAT FETCH c1 INTO v_id, v_name, v_salary; SET v_accumsalary = v_accumsalary + v_salary; SET v_ctr = v_ctr + 1; UNTIL at_end <> 0 END REPEAT fetch_loop; -- calc the average / v_ctr will be 1 higher than needed IF (v_ctr > 1) THEN SET avgHiSalary = v_accumsalary / (v_ctr-1); ELSE SET avgHiSalary = v_salary; END IF;

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-12 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 121: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

-- close cursor CLOSE c1; END P1

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 5. Calling Procedures 5-13

Page 122: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-14 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 123: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise 6. Create Stored Procedures

What This Exercise Is About

This exercise provides an opportunity for the student to register previously created stored procedures to the Development Center.

What You Should Be Able to Do

At the end of the lab, you should be able to:

• Register a previously written program as a stored procedure with the database manager

• Create stored procedures written in SQL Procedure Language without using the DB2 Stored Procedure Builder

Introduction

This lab has several sections.

• Section 1: Register a Java Stored Procedure for a previously written program.

• Section 2: Create an SQL Stored Procedure using a DB2 CLP script file for an SQL Procedure Language stored procedure and then register it.

• Section 3: Register Stored Procedures using their source code. • Section 4: Deploy an SQL Stored Procedure.

In Section 1, you will register a new Java stored procedure manually. Then you will import its definition into the Development Center.

In Section 2, you will create a new stored procedure. That stored procedure will be created using a DB2 CLP script file. The stored procedure will then be imported into your project.

In Section 3, you will only have access to the source code of your stored procedure. You will import the stored procedure into your Development Center project where you can then easily maintain it.

In Section 4, you will deploy one of your stored procedures into another database.

Required Materials

• Student notebook for SQL Procedure Language statement syntax.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 6. Create Stored Procedures 6-1

Page 124: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

• DB2 Info Center for SQL Procedure Language statement syntax (optional).

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-2 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 125: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise Instructions

The lab solutions can be found in “Exercise Solutions” on page 6-9.

Section 1: Register Previously Defined Java Stored Procedure

This section will have you import a previously defined Java stored procedure, CF71.LAB6_1, into your project. But first you will have to go through the steps required to manually define the stored procedure to DB2. After having done this, you might see how the Development Center simplifies things.

__ 1. The source for your stored procedure is found in the CF71 directory. Open a Windows command prompt, switch to the D drive if you have been working off of that drive, and then issue cd cf71 and press Enter.

__ 2. Compile your Java code. Key in javac Lab6_1.java. The file name is case sensitive.

__ 3. Create your jar file. Key in jar -cvf Lab6_1.jar Lab6_1.class and press Enter.

__ 4. Install your jar file in DB2. This must be done from a DB2 command prompt. Start a DB2 command window.

__ 5. Make sure that you replace the x with your proper drive letter. In your DB2 command window, type in db2 call sqlj.install_jar(‘file:x\cf71\lab6_1.jar’, ADMIN.lab6_1) and press Enter.

__ 6. Open the Command Center.

• Click Interactive tab once in the Command Center. • Enter CONNECT TO SAMPLE; in the Command area. • Click gears icon (top left of the toolbar) to execute the CONNECT statement. • You should see a message indicating that your are connected to the SAMPLE

database.

__ 7. Click the Script tab.

__ 8. In the Script area, type in the following:

CREATE PROCEDURE CF71.Lab6_1 ( IN id SMALLINT, OUT name VARCHAR(9), OUT job CHARACTER(5) ) NOT DETERMINISTIC LANGUAGE Java EXTERNAL NAME 'ADMIN.Lab6_1:Lab6_1.lab6_1' FENCED THREADSAFE PARAMETER STYLE JAVA

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 6. Create Stored Procedures 6-3

Page 126: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 9. Execute the script. You should get a message:

DB20000I The SQL command completed successfully.

These are all of the steps that are required to install a Java stored procedure manually. So now you will want to import this stored procedure into your project.

__ 10. From your Development Center desktop, right-click the Stored Procedures icon and select Import.

__ 11. Select Database in the left pane and click OK.

__ 12. On the Source Database panel, your Alias SAMPLE should be selected so just click Next>.

__ 13. On the Filter panel, select Java as the language and click Next>.

__ 14. On the Objects panel, under Available, select Lab6_1 and press the > push button to select it. Click the Next> button.

__ 15. On the Options panel, your Jar ID should be filled in. Click Finish. You will get a warning that the stored procedure already exists. Click Yes to drop and build it.

__ 16. Your stored procedure has been added to the project and you can test it. Specify an ID of 10 or 20 as the input.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-4 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 127: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 2: Import Previously Defined SQL Procedure Language Stored Procedure

This section will have you import a previously existing stored procedure, LAB6_2, written in SQL Procedure Language

The first thing that you must do in this simulation is to create the stored procedure outside of the Development Center. Once that is completed, you will then import it so that it can be maintained as part of your Development Center project.

__ 1. If you closed your DB2 Command Center, then open it and connect to the SAMPLE database.

__ 2. In the Command area, code a CREATE PROCEDURE statement to return the current time at the database server that is executing the stored procedure. Use the following information:

CREATE PROCEDURE CF71.LAB6_2 (OUT timeIs TIME)LANGUAGE SQL------------------------------------------------------------------------ -- SQL Stored Procedure-- This procedure returns the current time to the caller------------------------------------------------------------------------ SET timeIs = CURRENT TIME;

__ 3. Execute the CREATE PROCEDURE.

If your syntax is correct, you will see the message: DB20000I The SQL command completed successfully. in the information area.

__ 4. Return to the Development Center desktop.

Do you see procedure CF71.LAB6_2?

________________________________________________________________

________________________________________________________________

• Right-click Stored Procedures folder icon. Click Import. • Select Database and click OK. • Make sure that your database alias is Sample and click Next>. • On the Filter panel, only select SQL for the language and click Next>. • Listed on the left side should be all of your SQL stored procedures. Select

Lab6_2 and click the > button. Click the Next> button. • The Build and Replace options should be checked. Now click Finish. • Click Yes to the warning.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 6. Create Stored Procedures 6-5

Page 128: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Now do you see procedure CF71.LAB6_2?

________________________________________________________________

________________________________________________________________

__ 5. Execute the stored procedure and check your results.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-6 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 129: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 3: Import SQL Procedure Language Stored Procedure Source Code

Here you are to assume that some wrote an SQL stored procedure, Lab6_3, and sent you the source code. You would like to manage this code using the Development Center. The source code is located in the CF71 directory on your working drive. (For some this will be the C drive, for others, this will be the D drive)

__ 1. Return to the Development Center Desktop.

__ 2. Import a stored procedure.

__ 3. In the left pane, select File System and then in the right pane select Source file and click OK.

__ 4. Click the push button at the right side of the Name field. Navigate to the CF71 directory and select Lab6_3.db2 and click Choose.

__ 5. You can click Next> and step through the various panels and see the code, the parameters and other options and eventually click Finish, or you can just click Finish and bypass the other panels.

__ 6. One of the options that was selected by default is to build the stored procedure. That is why your stored procedure was built when you clicked Finish. If you would like to test the stored procedure, then enter an ID of 10 or 20.

Optional:

It is also possible to import a Java stored procedure using its source code as well.

__ 1. Import another stored procedure.

__ 2. In the left pane, select File System and then in the right pane, select Source file and click OK.

__ 3. Click the push button at the right side of the Name field. Navigate to the CF71 directory and select Lab6_4.java and click Choose. In Java, the name of the file that has the Java source code must be the same as the Java public class that is defined in the source. This is case sensitive. So in the next step, if you get an error indicating that the file name was correct, retype it and make sure that it is Lab6_4.java. You may have to view the source code for name verification.

__ 4. You can click Next> and step through the various panels until you get to the Stored Procedure Name panel. Type in a name of CF71.Lab6_4. Click Next> and make sure that Build is selected.

__ 5. Click Finish. Your stored procedure should have been built and you can test it by using an ID of 10 or 20.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 6. Create Stored Procedures 6-7

Page 130: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 4: Deployment of SQL Procedure Language Stored Procedure

Having created and tested your stored procedure in your ‘test’ database, now you need to deploy it to another database. First, you will need to create the target database.

__ 1. Open a DB2 command window and create a new database, TARGET.

__ 2. Return to the Development Center desktop. Select the Lab6_2 stored procedure and right-click. Click the Deploy menu item.

__ 3. On the Target Database panel, click the Alias drop-down box and select TARGET. Click Next>.

__ 4. Select Deploy source to database and click Finish.

__ 5. Now open the Control Center. You can do this by using the Tools menu item on the Development Center desktop.

__ 6. Display the stored procedures under Application Objects for the TARGET database. In your list of stored procedures, you should see your Lab6_2 stored procedure.

__ 7. You can close the Control Center.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-8 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 131: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise Solutions

Section 1: Register Previously Defined Java Stored Procedure

This section will have you import a previously defined Java stored procedure, CF71.LAB6_1, into your project. But first you will have to go through the steps required to manually define the stored procedure to DB2. After having done this, you might see how the Development Center simplifies things.

__ 1. The source for you stored procedure is found in the CF71 directory. Open a Windows command prompt, switch to the D drive if you have been working off of that drive, and then issue cd cf71 and press Enter.

__ 2. Compile your Java code. Type in javac Lab6_1.java. The file name is case sensitive.

__ 3. Create your jar file. Key in jar -cvf Lab6_1.jar Lab6_1.class and press Enter.

__ 4. Install your jar file in DB2. This must be done from a DB2 command prompt. So type in db2cmd and press Enter.

__ 5. Make sure that you replace the x with your proper drive letter. In your DB2 command window, type in db2 call sqlj.install_jar(‘file:x\cf71\lab6_1.jar’, ADMIN.lab6_1) and press Enter.

__ 6. Open the Command Center. You can do this using the Windows Start programs or under Tools on the Development Center desktop.

• Click Interactive tab once in the Command Center. • Enter CONNECT TO SAMPLE; in the Command area. • Click gears icon (top left of the toolbar) to execute the CONNECT statement. • You should see a message indicating that your are connected to the SAMPLE

database.

__ 7. Click the Script tab.

__ 8. In the Script area, type in the following:

CREATE PROCEDURE CF71.Lab6_1 ( IN id SMALLINT,OUT name VARCHAR(9),OUT job CHARACTER(5) )

NOT DETERMINISTIC LANGUAGE Java EXTERNAL NAME 'ADMIN.Lab6_1:Lab6_1.lab6_1' FENCED THREADSAFE PARAMETER STYLE JAVA

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 6. Create Stored Procedures 6-9

Page 132: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

__ 9. Click the Gears icon to execute. You should get a message:

DB20000I The SQL command completed successfully.

These are all of the steps that are required to install a Java stored procedure manually. So now you will want to import this stored procedure into your project.

__ 10. From your Development Center desktop, right-click the Stored Procedures icon and select Import.

__ 11. Select Database in the left pane and click OK.

__ 12. On the Source Database panel, your Alias SAMPLE should be selected so just click Next>.

__ 13. On the Filter panel, select Java as the language and click Next>.

__ 14. On the Objects panel, under Available, select Lab6_1 and click the > push button to select it. Click the Next> button.

__ 15. On the Options panel, your Jar ID should be filled in. Click Finish. You will get a warning that the stored procedure already exists. Click Yes to drop and build it.

__ 16. Your stored procedure has been added to the project and you can test it. Specify an ID of 10 or 20 as the input.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-10 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 133: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 2: Import Previously Defined SQL Procedure Language Stored Procedure

This section will have you import a previously existing stored procedure, LAB6_2, written in SQL Procedure Language

The first thing that you must do in this simulation is to create the stored procedure outside of the Development Center. Once that is completed, you will then import it so that it can be maintained as part of your Development Center project.

__ 1. If you closed your DB2 Command Center, then open it.

• Click Interactive tab once in the Command Center. • Enter CONNECT TO SAMPLE; in the Command area. • Click Gears icon (top left of the toolbar) to execute the CONNECT statement.

__ 2. In the Command area, code a CREATE PROCEDURE statement return the current time at the database server that is executing the stored procedure. Use the following information:

CREATE PROCEDURE CF71.LAB6_2 (OUT timeIs TIME)LANGUAGE SQL------------------------------------------------------------------------ -- SQL Stored Procedure-- This procedure returns the current time to the caller------------------------------------------------------------------------ SET timeIs = CURRENT TIME;

__ 3. Click Gears icon (top left of the toolbar) to execute the CREATE PROCEDURE.

If your syntax is correct, you will see the message: DB20000I The SQL command completed successfully. in the information area.

__ 4. Return to the Development Center desktop.

• Do you see procedure CF71.LAB6_2?

No, you have not imported it into your project.

• Right-click Stored Procedures folder icon. Click Import. • Select Database and click OK. • Make sure that your database alias is Sample and click Next>. • On the Filter panel, only select SQL for the language and click Next>. • Listed on the left side should be all of your SQL stored procedures. Select

Lab6_2 and click the > button. Click the Next> button. • The Build and Replace options should be checked. Now click Finish. • Click Yes to the warning.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 6. Create Stored Procedures 6-11

Page 134: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Now do you see procedure CF71.LAB6_2?

CF71.LAB6_2 should appear in list of stored procedures.

__ 5. Right-click CF71.LAB6_2 and select Run.

__ 6. Go to the Parameters tab. You should see your output parameter value having the current time.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-12 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 135: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Section 3: Import SQL Procedure Language Stored Procedure Source Code

Here you are to assume that some wrote an SQL stored procedure, Lab6_3, and sent you the source code. You would like to manage this code using the Development Center. The source code is located in the CF71 directory on your working drive. (For some this will be the C drive, for others, this will be the D drive)

__ 1. Return to the Development Center Desktop.

__ 2. Select the Stored Procedure icon, right-click and select Import.

__ 3. In the left pane, select File System and then in the right pane, select Source file and click OK.

__ 4. Click the push button at the right side of the Name field. Navigate to the CF71 directory and select Lab6_3.db2 and click Choose.

__ 5. You can click Next> and step through the various panels and see the code, the parameters and other options, and eventually click Finish, or you can just click Finish and bypass the other panels.

__ 6. One of the options that was selected by default is to build the stored procedure. That is why your stored procedure was built when you clicked Finish. If you would like to test the stored procedure, then enter an ID of 10 or 20.

Optional:

It is also possible to import a Java stored procedure using its source code as well.

__ 1. Select the Stored Procedure icon, right-click and select Import...

__ 2. In the left pane, select File System and then in the right pane, select Source file and click OK.

__ 3. Click the push button at the right side of the Name field. Navigate to the CF71 directory and select Lab6_4.java and click Choose. In Java, the name of the file that has the Java source code must be the same as the Java public class that is defined in the source. This is case sensitive. So in the next step, if you get an error indicating that the file name was correct, retype it and make sure that it is Lab6_4.java. You may have to view the source code for name verification.

__ 4. You can click Next> and step through the various panels until you get to the Stored Procedure Name panel. Type in a name of CF71.Lab6_4. Click Next> and make sure that Build is selected.

__ 5. Click Finish. Your stored procedure should have been built and you can test it by using an ID of 10 or 20.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 6. Create Stored Procedures 6-13

Page 136: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 4: Deployment of SQL Procedure Language Stored Procedure

Having created and tested your stored procedure in your ‘test’ database, now you need to deploy it to another database. First you will need to create the target database.

__ 1. Open a DB2 command window. You can do this from the Windows Start Program menus, or you can do a Start->Run, type in db2cmd and click OK.

__ 2. Enter the command db2 create database TARGET and press Enter.

__ 3. On the Target Database panel, click the Alias drop-down box and select TARGET. Click Next>.

__ 4. Return to the Development Center desktop. Select the Lab6_2 stored procedure and right-click. Click the Deploy menu item.

__ 5. On the Target Database panel, click the Alias drop down box and select TARGET. Click Next>.

__ 6. Select Deploy source to database and click Finish.

__ 7. Now open the Control Center. You can do this by using the Tools menu item on the Development Center desktop.

__ 8. Expand your instance, databases, and then the TARGET database. Expand Application Objects and select Stored Procedures. In your list of stored procedures, you should see your Lab6_2 stored procedure.

__ 9. You can close the Control Center.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-14 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 137: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Exercise 7. Debugging Stored Procedures

What This Exercise Is About

This exercise will have you debug stored procedures using the DB2 Development Center and the included debug capabilities.

What You Should Be Able to Do

At the end of the lab, you should be able to:

• Debug an SQL stored procedure using the DB2 Development Center

• Debug a Java stored procedure using the DB2 Development Center

Introduction

This exercise has several sections.

• Section 1: Debug an SQL Stored Procedure.

• Section 2: Debug a Java Stored Procedure.

In Section 1, you will debug an SQL Stored Procedure.

In Section 2, you will debug a Java Stored Procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 7. Debugging Stored Procedures 7-1

Page 138: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Exercise Instructions

The lab solutions can be found in “Exercise Solutions” on page 7-6.

Section 1: Debugging an SQL Stored Procedure

__ 1. You will be invoking the debug capabilities of the DB2 Development Center for a stored procedure you have previously created.

__ 2. Scroll to stored procedure CF71.LAB3_1 in the list of stored procedures.

__ 3. Right-click CF71.LAB3_1.

Click Build for Debug.

__ 4. What do you see in the Messages panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

__ 5. Right-click CF71.LAB3_1.

Select the Debug item or click Debug icon (in the toolbar).

Enter 555 for the employee ID (won't be found!).

Enter 2 for the rating.

__ 6. What two variable names do you see in the variables panel? What are the current values?

________________________________________________________________

__ 7. What is in the Call Stack panel?

________________________________________________________________

Note: This is CREATE PROCEDURE statement number.

__ 8. Click Step Into icon (on the toolbar) to proceed with the execution of the stored procedure.

What are the values of SQLSTATE and SQLCODE now?

________________________________________________________________

Note: This is CREATE PROCEDURE statement number.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-2 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 139: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

What other variables do you see in the Variables panel?

________________________________________________________________

________________________________________________________________

Note: Your variable names may have been different for the DECLAREd variables and parameters used for the procedure.

Note: Notice that all variable names have been folded to upper case. The values for the input parameters also show up in the panel.

__ 9. Click Run to Completion icon (on the toolbar) to proceed with the execution of the stored procedure.

The procedure should finish executing. Return to the Development Center desktop. What do you see in the Messages panel?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

Note: SQLSTATE=70444 because of our EXIT HANDLER in the stored procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 7. Debugging Stored Procedures 7-3

Page 140: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 2: Debugging a Java Stored Procedure

If you failed to start the idebug program before you run your stored procedure in debug mode, then the Distributed Debugger will not initialize. You need to reboot, or at a minimum, stop are restart DB2. I know that this is strange but it is the only way I could find to correct the problem.

__ 1. You have been asked to debug a Java stored procedure.

To set up for debugging, open a DB2 Command window.

Start -> Programs -> IBM DB2 -> DB2 Command window.

Set up the DB2ROUTINE_DEBUG registry variable to enable debugging on your DB2 UDB server instance. First, do a db2set -all. If the DB2ROUTINE_DEBUG is not ON, then ensure:

db2set DB2ROUTINE_DEBUG=ON

__ 2. Now you must verify that the environment variable DB2_DBG_PATH has been set. This should have been done during the lab setup. And it will point to your CF71_Project directory. If you did not follow the earlier instructions and did not specify CF71_Project as your project directory, then you will have to modify your environment variable and reboot your system.

__ 3. Start the IBM Distributed Debugger client from a Windows command prompt by using the following command:

idebug -qdaemon -quiport=8000

This starts the debugger user interface to run as a daemon and the listener is on listening on TCP/IP port 8000. On the DB2 server (which is also your machine), you will need to indicate that this is the port that the client machine will be using for debugging (this is actually the default port number).

You should see a small window for the IBM Distributed Debugger Daemon start and indicate that it is "Listening to port(s): 8000".

Note: To stop the daemon, press Ctrl-C on the DB2 Command window, rather than clicking the Stop button on the Daemon window.

__ 4. Start the Development Center, if necessary. Right-click your CF71.Lab4_1 stored procedure and select Properties.

__ 5. Click the Build tab and in the compile options field, type in -g. Click OK.

__ 6. Right-click your stored procedure and select Build for Debug.

__ 7. Click IBM Distributed Debugger on the Windows program taskbar. You should see that the debugger is being initialized.

__ 8. Double-click the statement number for sql = “SELECT”. A red dot will be displayed next to the statement number, indicating a breakpoint has been set.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-4 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 141: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 9. Click the icon on the toolbar for Run the program until a breakpoint... You should see that the processing stopped at the breakpoint.

__ 10. Set a breakpoint on the stmt = com.prepareStatement (sql);

__ 11. Execute to that statement.

__ 12. On the menubar, click File->Preferences. Click Debug and then select Add to Program Monitor on Double-Click. Click OK.

__ 13. Double-click the SQL variable. If things are working properly, then the SQL variable will be added to the Expression Monitors pane.

__ 14. You should be able to see the value for the SQL variable.

__ 15. Continue your execution to the end of the program.

__ 16. You can close the Debugger and see your results in the Development Center Desktop.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 7. Debugging Stored Procedures 7-5

Page 142: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Exercise Solutions

Section 1: Debugging an SQL Stored Procedure

__ 1. You will be invoking the debug capabilities of the DB2 Development Center for a stored procedure you have previously created.

__ 2. Scroll to stored procedure CF71.LAB3_1 in the list of stored procedures.

__ 3. Right-click CF71.LAB3_1.

Click Build for Debug.

__ 4. What do you see in the Messages panel?

CF71.LAB3_1 - Build started.

DROP SPECIFIC PROCEDURE CF71.SQLnnnnnnnnnnnnn

CF71.LAB3_1 - Drop stored procedure completed.

CF71.LAB3_1 - Create stored procedure completed.

CF71.LAB3_1 - Build successful

__ 5. Right-click CF71.LAB3_1.

Select the Debug item or click Debug icon (in the toolbar).

Enter 555 for the employee ID (won't be found!).

Enter 2 for the rating.

__ 6. What two variable names do you see in the variables panel? What are the current values?

SQLSTATE- 00000 SQLCODE - 0

__ 7. What is in the Call Stack panel?

LAB3_1 - Line 1

Note: This is CREATE PROCEDURE statement number.

__ 8. Click Step Into icon (on the toolbar) to proceed with the execution of the stored procedure.

What are the values of SQLSTATE and SQLCODE now?

SQLSTATE 00000 SQLCODE 0

Note: This is CREATE PROCEDURE statement number.

What other variables do you see in the Variables panel?

NEW_SALARY, OLD_SALARY, RATING, EMPLOYEE_NUMBER

Note: Your variable names may have been different for the DECLAREd variables and parameters used for the procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-6 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 143: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

Note: Notice that all variable names have been folded to upper case. The values for the input parameters also show up in the panel.

__ 9. Click Run to Completion icon (on the toolbar) to proceed with the execution of the stored procedure.

The procedure should finish executing. Return to the Development Center desktop. What do you see in the Messages panel?

CF71.LAB3_1 - Debug started.

CF71.LAB3_1 - Exception occurred while debugging:

A database manager error occurred. [IBM][CLI Driver][DB2/NT] SQL0438N Application raised error with diagnostic text: "". SQLSTATE=70444

CF71.LAB3_1 - Rolled back completed successfully.

CF71.LAB3_1 - Debug failed.

Note: SQLSTATE=70444 because of our EXIT HANDLER in the stored procedure.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 7. Debugging Stored Procedures 7-7

Page 144: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Section 2: Debugging a Java Stored Procedure

If you failed to start the idebug program before you run your stored procedure in debug mode, then the Distributed Debugger will not initialize. You need to reboot or at a minimum, stop are restart DB2. I know that this is strange but it is the only way I could find to correct the problem.

__ 1. You have been asked to debug a Java stored procedure.

To set up for debugging, open a DB2 Command window.

Start -> Programs -> IBM DB2 -> DB2 Command window.

Set up the DB2ROUTINE_DEBUG registry variable to enable debugging on your DB2 UDB server instance. First, do a db2set -all. If the DB2ROUTINE_DEBUG is not ON, then ensure:

db2set DB2ROUTINE_DEBUG=ON

__ 2. Now you must verify that the environment variable DB2_DBG_PATH has been set. This should have been done during the lab setup. And it will point to your CF71_Project directory. If you did not follow the earlier instructions and did not specify CF71_Project as your project directory, then you will have to modify your environment variable and reboot your system.

__ 3. Start the IBM Distributed Debugger client from a Windows command prompt by using the following command:

idebug -qdaemon -quiport=8000

This starts the debugger user interface to run as a daemon and the listener is on listening on TCP/IP port 8000. On the DB2 server (which is also your machine), you will need to indicate that this is the port that the client machine will be using for debugging (this is actually the default port number).

You should see a small window for the IBM Distributed Debugger Daemon start and indicate that it is "Listening to port(s): 8000".

Note: To stop the daemon, press Ctrl-C on the DB2 Command window, rather than clicking the Stop button on the Daemon window.

__ 4. Start the Development Center, if necessary. Right-click your CF71.Lab4_1 stored procedure and select Properties.

__ 5. Click the Build tab and in the compile options field, type in -g. Click OK.

__ 6. Right-click your stored procedure and select Build for Debug.

__ 7. Click IBM Distributed Debugger on the Windows program taskbar. You should see that the debugger is being initialized.

__ 8. Double-click the statement number for sql = “SELECT”. A red dot will be displayed next to the statement number, indicating a breakpoint has been set.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-8 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 145: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student ExercisesV2.0

EXempty

__ 9. Click the icon on the toolbar for Run the program until a breakpoint... You should see that the processing stopped at the breakpoint.

__ 10. Set a breakpoint on the stmt = com.prepareStatement (sql);

__ 11. Execute to that statement.

__ 12. On the menubar, click File->Preferences. Click Debug and then select Add to Program Monitor on Double-Click. Click OK.

__ 13. Double click on the SQL variable. If things are working properly, then the SQL variable will be added to the Expression Monitors pane.

__ 14. You should be able to see the value for the SQL variable.

__ 15. Continue your execution to the end of the program.

__ 16. You can close the Debugger and see your results in the Development Center Desktop.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1996, 2003 Exercise 7. Debugging Stored Procedures 7-9

Page 146: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-10 Stored Procedures © Copyright IBM Corp. 1996, 2003

Page 147: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

V2.0

backpg

Back page
Page 148: DB2 Stored Procedures Programming Workshop...DB2 Stored Procedures Programming Workshop (Course Code CF71) Student Exercises ERC 4.0 IBM Certified Course Material V2.0.0.1 cover Front

���®


Recommended