Documente Academic
Documente Profesional
Documente Cultură
02 Oct 2008
This tutorial introduces the SQL procedure as it relates to DB2® V9.5. 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. Learn about different SQL procedure
statements and see how to invoke and share nested stored procedures. Test and
deploy stored procedures and discover how to secure SQL procedures. This tutorial
is the second in a series of six tutorials designed to help you prepare for the DB2 9.5
SQL Procedure Developer Certification Exam (735).
This is the second 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 2 of the test, which is entitled "SQL Procedures."
See Resources.
Prerequisites
This tutorial is written for Linux®, UNIX®, or Windows® database developers or
administrators, whose skills and experience are at a beginning to intermediate level.
You should have a general familiarity with using a UNIX or Windows command-line
shell and a working knowledge of DB2 and SQL commands.
System requirements
The examples in this tutorial are specific to DB2 9.5 running on a Windows operating
system. The concepts and information provided are relevant to DB2 running on any
distributed platform.
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 IBM DB2 9.5 to work
along with this tutorial.
logic and are executed directly on the database server. The business logic gets
encapsulated inside the stored procedure, and it can then be invoked from client
applications, other stored procedures, user-defined functions or from triggers via an
SQL statement. Stored procedures can accept parameter values to change the
behaviour of the business logic based on the input data. They can then return output
values back to the caller or they can return multiple result sets to the caller.
Stored procedures can be implemented using the SQL Procedure Language (SQL
PL) or a programming language such as Java™ or C.
• Enhanced capabilities:
• Since a stored procedure resides on the database server, it tends to
have more access to memory and disk space then the application
• Interoperability:
• Different code modules may be implemented in different programming
languages by different programmers. To help achieve code reuse with
the interoperability of logic, stored procedures themselves can be
written in different languages. A client application coded in a different
language can invoke a stored procedure written in a different
language (for example, a stored procedure written in Java can be
invoked from an application written in C++). Also stored procedures
written in different languages can invoke each other (for example, a
stored procedure written in C can invoke a stored procedure written in
Java). The operating system of the client and the operating system of
the server where the stored procedure is located can also be different
(for example, a Windows client application can invoke a stored
procedure running on AIX).
• The only SQL statement that can invoke a stored procedure is the CALL
statement. The CALL statement can be used from applications, stored
procedures, user-defined functions or triggers.
• SQL procedures are always defined as NOT FENCED. There is less risk
involved with these types of stored procedures since only SQL operations
can be performed by the stored procedure limiting the risk involved with
the database server.
• SQL procedures are more portable. Since they do not rely on a specific
programming language whose compiler or interpreter would be needed
on each database server, it would be easier to re-create these stored
procedures on each server that needs them.
The CREATE PROCEDURE statement defines the characteristics and logic of the
stored procedure which is stored in the DB2 system catalogs (for example,
SYSCAT.PROCEDURES).
CREATE PROCEDURE--procedure-name----------------------------->
>--+----------------------------------------------------+--?---->
'-(--+------------------------------------------+--)-'
| .-,------------------------------------. |
| V .-IN----. | |
'---+-------+--parameter-name--data-type-+-'
+-OUT---+
'-INOUT-'
>--+-------------------------+--?------------------------------->
'-SPECIFIC--specific-name-'
.-DYNAMIC RESULT SETS 0--------. .-MODIFIES SQL DATA-.
>--+------------------------------+--?--+-------------------+--->
'-DYNAMIC RESULT SETS--integer-' +-CONTAINS SQL------+
'-READS SQL DATA----'
.-NOT DETERMINISTIC-. .-CALLED ON NULL INPUT-.
>--?--+-------------------+--?--+----------------------+--?----->
'-DETERMINISTIC-----'
.-INHERIT SPECIAL REGISTERS-. .-OLD SAVEPOINT LEVEL-.
>--+---------------------------+--?--+---------------------+---->
'-NEW SAVEPOINT LEVEL-'
.-LANGUAGE SQL-. .-EXTERNAL ACTION----.
>--?--+--------------+--?--+--------------------+--?------------>
'-NO EXTERNAL ACTION-'
>--+------------------------------+--?-------------------------->
'-PARAMETER CCSID--+-ASCII---+-'
'-UNICODE-'
>--| SQL-procedure-body
|--------------------------------------><
The most commonly used components of this diagram are the procedure_name and
the parameters (IN/OUT/INOUT).
CONTAINS SQL, READS SQL DATA, MODIFIES SQL DATA indicates the level
of data access from stored procedure. If any data manipulation is performed within
the stored procedure, for example the use of GLOBAL TEMPORARY TABLES, then
the stored procedure need to be specified with the MODIFIES SQL DATA option. If
the BEGIN ATOMIC clause is used in a compound SQL procedure, the stored
procedure can only be created if it is defined with MODIFIES SQL DATA.
SQL procedure body is the main body of the stored procedure. At its core is a
compound statement. Compound statements are bounded by the keywords BEGIN
and END. These statements can be ATOMIC or NOT ATOMIC. By default they are
NOT ATOMIC. SQL Procedures requires particular order of declarations and
executable statements within compound statement.
Figure 2 illustrates the structured format of a compound statement within SQL
procedures:
NOT ATOMIC
If an unhandled error condition occurs, no SQL statements are rolled back. Listing 3
demonstrates how it works.
If INSERT (1) is executed successfully, then an error is enforced and the SQL
procedure is terminated without ever executing INSERT (2). Since this SQL
procedure was created with the NOT ATOMIC statement, the first INSERT
statement is not rolled back. If you query table T1 after the stored procedure
execution, it will return:
C1 C2
1 FIRST
ATOMIC
If INSERT (1) is executed successfully, then an error is enforced and the SQL
procedure is terminated without ever executing INSERT (2). Since this stored
procedure was created with the ATOMIC statement, the first INSERT is rolled back.
If you query table T1 after the SQL procedure executes, it still returns the only one
row that had been inserted by the previous example:
C1 C2
1 FIRST
Attempting to build this SQL procedure gives you the following error message:
DB2ADMIN.VAR_SCOPE: 12: "V_INNER2" is not valid in the context
where it is used.. SQLCODE=-206, SQLSTATE=42703,
DRIVER=3.50.152
Note that statement (1) passes successfully as v_outer1 and is declared outside of
the compound statement, but statement (2) fails because v_inner2 is not declared
outside of the compound statement.
>>-CALL--procedure-name--+--------------------------+----------><
| .-,--------------. |
| V | |
'-(----+-expression-+-+--)-'
'-NULL-------'
Note that DB2 is strongly typed and parameters types in the CALL statement need
to be compatible with parameters in the CREATE PROCEDURE statement of the
calling stored procedure. The nth argument of the CALL statement corresponds to
the nth parameter defined in the CREATE PROCEDURE statement for the
procedure.
Listing 7 demonstrates this relation:
In summary, here are the rules for passing parameters to stored procedure:
• Variables and parameters are strongly typed (they must match)
• Local variables are matched to the stored procedure by their position
• All parameters must have a value
• Overloaded procedures are determined by the number of parameters
The following examples illustrate how to use RETURN and the GET DIAGNOSTICS
statements.
For example, suppose you have two different stored procedures:
begin
set v1 = 10;
return;
end
CREATE PROCEDURE TEST2(out v1 int)
begin
set v1 = 5;
return 2;
end
If you execute the NEST_DIAGN stored procedure from the DB2 command line, you
get the following results:
Listing 11. Result of executing the NEST_DIAGN stored procedure from the
DB2 command line
Please note that you need to DECLARE a variable that will be accepting the value
from DB2_RETURN_STATUS.
For example, for department 51, you get the following result set:
Now you want to use the result set from this stored procedure (without storing it in
temporary or permanent table) in another stored procedure.
DB2 permits an outer stored procedure to use a result set from an inner one. Here is
what you need to do:
• Declare a result set locator using the following syntax:
• DECLARE rs_locator_var1 RESULT_SET_LOCATOR VARYING;
• Associate this result set locator with the calling procedure:
• ASSOCIATE RESULT SET LOCATOR( rs_locator_var1) WITH
PROCEDURE proc_called;
• Allocate the cursor that points to the result set from the calling procedure:
• ALLOCATE cursor1 CURSOR FOR RESULT SET
rs_locator_var1;
Now, if you execute this stored procedure with department "51" as the input
parameter, you get the total department commission:
The following diagram shows the syntax for the session global variable:
Please note that the session global variable is declared outside of a stored
The user building the stored procedure should satisfy the following requirements:
• Must have the privileges required to execute the CREATE PROCEDURE
statement
• Must have the privileges to execute all SQL statements in the stored
procedure
• All database objects (example, tables, views, functions, other procedures)
that are referenced in this SQL procedure should exist in the database
• A successful database connection must be established from the CLP (this
can be achieved by using the following db2 command : db2 connect
to sample user userid using password )
So now write a script that contains a simple SQL procedure and put the "@"
termination character at the end:
Note that the option -td indicates that the CLP terminator default is to be reset with
the corresponding terminating character. The -vf option indicates that the CLP's
optional verbose (-v) option is to be used, which causes each SQL statement or
command in the script to be displayed on the screen as it is executed, along with
any output that results from its execution. The -f option indicates that the target of
the command is a file.
Now it's time to execute (or test) this stored procedure from the CLP. To do that you
need to run the following command:
Please note that you need to put a value for each input parameter and place a "?"
(question mark) for each output parameter.
But how would you know that the return value of 5 is correct? As this stored
procedure is simple and only has one SQL statement, you can execute this
statement from the CLP by putting input parameters directly into the WHERE clause
as Listing 19 illustrates:
SELECT count(poid)
FROM PURCHASEORDER
WHERE ucase(status) = 'SHIPPED'
AND orderdate < CURRENT DATE;
As you can see, you get the same result. With more complex stored procedure
testing it could be a more time consuming task. You can use the IBM Data Studio
tool to help you debug stored procedures.
Authorizations
There are basically two types of authorization that needs to be considered for SQL
procedures:
• The stored procedure definer is the user who actually creates the stored
procedure.
• The stored procedure invoker is the user who invokes or calls the stored
procedure.
In order to create an SQL procedure, the userid performing the task needs to have
BINDADD authority on the database and either IMPLICIT_SCHEMA on the
database (if the schema for the stored procedure does not already exist), or
CREATE_IN on the schema (if the schema for the stored procedure does already
exist). They would also need to have all the necessary privileges to perform the SQL
that is defined in the stored procedure body.
In order to invoke or call an SQL procedure, the userid performing the task needs to
have EXECUTE privilege on the stored procedure.
The userid who created the SQL procedure implicitly gets EXECUTE privilege and
the GRANT EXECUTE privilege. Either DBADM or SYSADM authority also allows a
user to create or invoke an SQL procedure. It is generally recommended that a
database administrator (DBA) is the one who creates the stored procedure for an
application developer who may need to be able to invoke it.
• READS SQL: no SQL statement can modify data in the stored procedure
• MODIFIES SQL: SQL statements can both modify or read data in the
stored procedure
The SQL access level can also determine what kind of stored procedure can be
invoked from within that stored procedure. A stored procedure cannot call another
stored procedure that is set with a higher SQL data access level. As an example, a
stored procedure defined with CONTAINS SQL can invoke a stored procedure that
is defined with either CONTAINS SQL or NO SQL. That same stored procedure
cannot invoke another stored procedure that is defined with READS SQL DATA or
MODIFIES SQL.
The SQL access level can be specified during the CREATE PROCEDURE
statement.
GET ROUTINE is a DB2 command that extracts an SQL procedure from the
database and converts it into a SAR (SQL Archive) file, which can then be sent to
the client.
>>-GET
ROUTINE--INTO--file_name--FROM--+----------+------------->
'-SPECIFIC-'
>----PROCEDURE----routine_name--+-----------+------------------><
'-HIDE BODY-'
The HIDE BODY clause on the GET ROUTINE command ensures that the body of
the SQL procedure is not extracted, thus encrypting the stored procedure.
PUT ROUTINE is a DB2 command that creates the SQL procedure in the database,
given the SAR file that was extracted via GET ROUTINE.
>>-PUT
ROUTINE--FROM--file-name--------------------------------->
>--+-------------------------------------+---------------------><
'-OWNER--new-owner--+---------------+-'
'-USE REGISTERS-'
Section 7. Conclusion
This tutorial has introduced you to a number of ideas that you will see on the DB2
9.5 Database Developer Certification Exam (735). The material in this tutorial
primarily covers the objectives in Section 2 of the test, which is entitled "SQL
Procedures".
In this tutorial, you've learned about the DB2 stored procedure and how your
application can benefit from using the SQL procedure. You've seen how to design
your procedures using SQL PL and how to build and test them. This tutorial
introduced the idea of nested procedures and showd you how to invoke them and
share data between the procedures. Learning how to use these stored procedures
allows you to integrate complex business logic into your overall database
application.
Resources
Learn
• Read Part 1 of the series, "SQL Procedure Language," to learn about SQL
Procedure Languag, including a variable, condition, and handler declaration,
flow of control and iterative statements, as well as an error-handling
mechanism.
• 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
• Participate in the discussion forum for this content.
Shakeb Shere
Shakeb Shere is a certified IBM DB2 Universal Database Application Developer. He
has worked for the IBM DB2 technical support team for over 8 years, and has
in-depth knowledge in all forms of application development support for DB2 including
stored procedure support. He currently focuses his support in CLI, ODBC, .NET and
OLEDB, and currently works in the Advanced Support Common Client Technologies
team for DB2 Universal Database on Linux, UNIX, and Windows.