DB2 9.5 SQL Procedure Developer Exam 735 Prep, Part 1
DB2 9.5 SQL Procedure Developer Exam 735 Prep, Part 1
25 Sep 2008
In this tutorial, learn about IBM® DB2® 9.5 SQL Procedural Language, including a
variable, condition and handler declaration, flow of control and iterative statements,
as well as an error handling mechanism. This is the first in a series of six tutorials you
can use to help prepare for the DB2 9.5 SQL Procedure Developer exam 735. The
material in this tutorial primarily covers the objectives in Section 1of the test, which is
entitled "SQL Procedural Language."
Objectives
In this tutorial, you will:
Prerequisites
To take the DB2 9.5 SQL Procedure Developer exam, you must have already
passed the DB2 9 Family Fundamentals exam (Exam 730). You can use the "DB2
Family Fundamentals tutorial series" to prepare for that exam (see Resources). It is
a very popular series that has helped many people understand the fundamentals of
the DB2 family of products.
For this tutorial to be useful, you should have background knowledge of how a
relational database works as well as basic knowledge of databases and database
programming constructs.
System requirements
You do not need a copy of DB2 9.5 to complete this tutorial. However, you will get
more out of the tutorial if you download the free trial version of DB2 Express-C to
work along with this tutorial.
Section 2. Introduction
DB2 SQL Procedural Language (SQL PL) is a subset of the SQL Persistent Stored
Module language standard. This standard combines the ease of data access with
SQL with the flow control you get from a programming language. The current set of
SQL PL statements and language features allows you to develop comprehensive,
high-level programs in SQL as functions, stored procedures, and triggers. It gives
you the ability to encapsulate the business logic into database objects that are easy
to maintain, thus improving the performance of your database application.
SQL PL supports local and global variables, including declaration and assignment,
conditional statements and iterative statements, transfer of control statements, error
management statements, and methods to return a result set. These topics are all
discussed in this tutorial.
.-,-----------------.
V |
|--DECLARE----SQL-variable-name-+------------------------------->
.-DEFAULT NULL------.
>--+-data-type--+-------------------+-+-------------------------|
| '-DEFAULT--constant-' |
SQL-variable-name defines the name of the local variable. The name cannot be the
same as another variable or as a parameter name. It also should not be the same as
a column name.
DEFAULT value – if it’s not specified, NULL will be assigned at declaration time.
An array type name should be qualified with schema and be unique on the current
server. LONG VARCHAR, LONG VARGRPAHIC, XML and user-defined types are
not supported data types for array elements.
Please note that the integer "constant" specifies the maximum cardinality of the
array and is optional. Array elements can be referenced as
ARRAY-VARIABLE(subindex) where subindex must be between 1 and the
cardinality of the array.
Now you can use this data type in your SQL procedure:
DB2 supports several methods to manipulate with arrays. For example, function
CARDINALITY(myarray) returns the number of elements of an array.
The variable name could be a name of a local variable, global variable, or an array
element.
VALUES INTO
SELECT (or FETCH) INTO
Special registers
A special register is a storage area that a DBA defines for use by an application
process. The value in a special register can be accessed by and referenced from an
SQL statement or an SQL PL statement. You can find all the special registers at the
IBM DB2 database for Linux, UNIX, and Windows Information Center (see
Resources).
All of these registers can be referenced with an underscore in the reference --- for
example, CURRENT_DATE.
Some of the special register values could be updated with the SET statement. For
example, to update the schema you are accessing, you would need to change
special register CURRENT SCHEMA as below.
To change the default function path, you need to update the special register
CURRENT PATH.
Section 5. Cursors
Declaration
SQL PL provides the DECLARE cursor statement to define a cursor and to support,
along with other statements, the return of the result set and cursor processing.
>>-DECLARE--cursor-name--CURSOR---------->
>--FOR--+-select-statement-+-------------><
.-WITHOUT HOLD-.
|--+--------------+---------------------------------------------|
'-WITH HOLD----'
.-WITHOUT RETURN-------------.
|--+----------------------------+-------------------------------|
| .-TO CALLER-. |
'-WITH RETURN--+-----------+-'
'-TO CLIENT-'
Select-statement is a valid SQL SELECT statement. You can specify the FOR
UPDATE clause to use the cursor for a positioned update or delete.
The WITHOUT HOLD/WITH HOLD option defines cursor status (open/close) after a
COMMIT operation. WITHOUT HOLD is the default. If a cursor has been defined
using the WITH HOLD option, the cursor remains OPEN after the COMMIT
operation. All cursors are closed after the ROLLBACK operation.
The following is an example of an explicit cursor declaration that can be used for
iterative processing later in the procedure:
While an SQL statement can not have a parameter marker, it can have a reference
to a local variable that is declared before the cursor. For example:
If you close the cursor, the result set will not be returned to the calling application.
Listing 10 demonstrates the declaration of the cursor to return a single result set
from a procedure:
Cursor processing
To process the results of a cursor with a procedure, you need to do the following:
3. Fetch the result of the cursor into local variables that have been
previously declared (except for implicit cursor processing that is explained
in FOR statement below)
4. Close this cursor (Note: if you do not close the cursor, it will be implicitly
closed when procedure is terminated)
IF statement
The IF statement allows you to branch your logic based on the status of a condition.
The IF statement supports the use of optional ELSEIF clauses and a default ELSE
clause. An END IF clause is required to indicate the end of the IF statement.
CASE statement
SQL PL also supports two types of the CASE statement to branch logic based on
the status of a condition:
Iterative statements
SQL PL supports several methods to repeatedly execute some logic, including a
simple LOOP, a WHILE LOOP, a REPEAT LOOP, and a FOR LOOP:
To demonstrate the use of these looping technique, let’s write a procedure that gets
the last name, year-of-service and age of each employee from an EMPLOYEE table
and inserts it into the new table REPORT_INFO_DEPT, declared as lname
varchar(15), hiredate date, birthdate date.
Please note that the same can be done using a simple SQL statement, but, in this
instance, we use three different loop statements.
The REPEAT loop is very similar to the WHILE loop, except that the condition is
checked at the end (thus, it is really an UNTIL loop).
Now, let’s fill up REPORT_INFO_DEPT table using a procedure with the FOR loop
statement.
Please note that the last procedure does not open, fetch or close the cursor — it is
all done implicitly by the FOR loop statement. Also, you can reference the values
implicitly fetched inside this loop, qualifying the column with name of the loop (for
example, dept_loop.lastname) — without the use of local variables to store these
values.
|--DECLARE--condition-name--CONDITION--FOR---------------------->
.-VALUE-.
.-SQLSTATE--+-------+-.
>--+---------------------+--string-constant---------------------|
|--DECLARE--+-CONTINUE-+--HANDLER--FOR-------------------------->
+-EXIT-----+
'-UNDO-----'
>--+-specific-condition-value-+--| SQL-procedure-statement |----|
'-general-condition-value--'
WHERE specific-condition-value
.-,----------------------------------------.
V .-VALUE-. |
|----+-SQLSTATE--+-------+--string-constant-+-+-----------------|
'-condition-name-----------------------'
Here are some examples to illustrate how it works. If the UPDATE statement fails in
the following procedure, control is transferred to the EXIT handler. As a result, the
procedure is terminated, but its output parameter contains the value for SQLCODE
and SQLSTATE.
Please note that SQLCODE and SQLSTATE should be explicitly declared as local
variables.
Listing 19 demonstrates a scenario when you do not want to exit the procedure, if a
given error occurs, but prefer to continue with some action. To understand this
example, please note the table TAB1 defined as (col1 int, col2 char(5)) and DB2
does not truncate a value by default, but raises SQLSTATE ‘22001’ if value overflow
occurs.
CREATE PROCEDURE
proc1 (IN num
int, IN
new_status
varchar(10))
P1: BEGIN
DECLARE
SQLCODE INTEGER
default 0;
DECLARE
SQLSTATE CHAR(5)
default ‘ ‘;
DECLARE
v_trunc INTEGER
default 0;
DECLARE
overflow
CONDITION FOR
SQLSTATE '22001';
DECLARE
CONTINUE HANDLER
FOR overflow
BEGIN
INSERT INTO tab1
VALUES (num,
substr
(new_sataus,1,5));
SET
v_trunc = 2;
END;
INSERT INTO
tab1 VALUES(num,
new_status);
RETURN
v_trunc;
END P1
If you call this procedure with the new_status input parameter ‘Too many’, the
SQLSTATE ‘22001’ is raised during INSERT statement execution and control is
passed to CONDITION HANDLER. As a result, the v_trunc indicator will be set up to
2, the new row will be inserted into the TAB1 table with a truncated value for COL2,
and your procedure will end successfully.
>>-SIGNAL------------------------------------------------------->
.-VALUE-.
>--+-SQLSTATE--+-------+--+-sqlstate-string-constant-+-+-------->
| '-variable-name------------' |
'-condition-name------------------------------------'
>--+------------------------+----------------------------------><
'|--+-SET MESSAGE_TEXT-- = --diagnostic-string-expression-+------|
You can also raise a specific condition name, which must be declared within the
compound statement that contains the SIGNAL statement as the listing below
illustrates.
Section 8. Conclusion
In this tutorial, you've learned about the SQL Procedural Language that is used to
code procedures, user-defined functions, and triggers. You've learned all the basic
element of SQL Procedure Language, including variable declaration and
assignment, syntax and use, conditional and iterative statements to control the flow
of procedure logic. You also have learned how to use error handling and result sets.
This allows you to build customized and complex business logic that can be
integrated into your overall database application.
Resources
Learn
• In Part 2 of the series, "DB2 SQL Procedures," learn about DB2 9.5 SQL
procedures, including an introduction to stored procedures, the advantages of
using stored procedures, and the differences between SQL procedures and
external procedures.
• Part 3 of the series, "DB2 SQL functions," introduces you to user-defined
functions and walks you through the basic steps used to construct user-defined
functions. This tutorial also introduces you to the structure of SQL functions and
covers the ins and outs of SQL function development.
• Part 5 of the series, "Advanced SQL features," learn about IBM DB2 temporary
tables, ADMIN_CMD procedure, savepoints and other advanced SQL features.
• Visit the Test 735: DB2 9.5 SQL Procedure Developer page to get
comprehensive resources related to the exam.
• The DB2 Family Fundamentals tutorial series gives you the resources you need
to ace the DB2 Family Fundamentals test.
• Visit the developerWorks resource page for DB2 for Linux, UNIX, and Windows
to read articles and tutorials and connect to other resources to expand your
DB2 skills.
• Learn about DB2 Express-C, the no-charge version of DB2 Express Edition for
the community.
• The DB2 9 for z/OS Stored Procedures: Through the CALL and Beyond IBM
Redbook contains information about SQL Procedures.
• DB2 v9.5 Information Center: Learn more about DB2 SQL procedures.
Get products and technologies
• Download IBM product evaluation versions and get your hands on application
development tools and middleware products from DB2®, Lotus®, Rational®,
Tivoli®, and WebSphere®.
• Download a free trial version of DB2 9 for Linux, UNIX, and Windows.
• Now you can use DB2 for free. Download DB2 Express-C, a no-charge version
of DB2 Express Edition for the community that offers the same core data
features as DB2 Express Edition and provides a solid base to build and deploy
applications.
Discuss
• Check out developerWorks blogs and get involved in the developerWorks
community.