Sie sind auf Seite 1von 8

DB2 Stored Procedures

Typically, applications access the database across the network. This can result in poor performance if
a lot of data is being returned. A stored procedure runs on the database server. A client application
can call the stored procedure which then performs the database accessing without returning
unnecessary data across the network. Only the results the client application needs are returned by the
stored procedure.

You gain several benefits using stored procedures:

Reduced network traffic


Grouping SQL statements together can save on network traffic. A typical application
requires two trips across the network for each SQL statement. Grouping SQL statements
results in two trips across the network for each group of statements, resulting in better
performance for applications.

Access to features that exist only on the server

Stored procedures can have access to commands that run only on the server, such as
LIST DATABASE DIRECTORY and LIST NODE DIRECTORY; they might have the
advantages of increased memory and disk space on server machines; and they can
access any additional software installed on the server.
Enforcement of business rules
You can use stored procedures to define business rules that are common to several
applications. This is another way to define business rules, in addition to using constraints
and triggers.

When an application calls the stored procedure, it will process data in a consistent way
according to the rules defined in the stored procedure. If you need to change the rules,
you only need to make the change once in the stored procedure, not in every application
that calls the stored procedure.

_________________________________________________________________________________

Stored procedures have become an increasingly important component of IBM DB2 for OS/390 and
z/OS. Many shops are implementing and executing stored procedures in large mission-critical
applications. Some installations have large stored procedure-based workloads executing hundreds of
thousands of stored procedure calls per day. This is for a variety of reasons. Stored procedures offer
many benefits from an application development and DB2 performance perspective. As DB2 becomes
a database server platform for e-business applications, stored procedures are an optimal method to
access DB2. As the usage of stored procedures explodes, it is important that care be taken in their
implementation and deployment.

An effective implementation of stored procedures on DB2 for OS/390 and z/OS requires a variety of
skills and resources. The list includes a combination of component skills, including OS/390 and z/OS,
Workload Manager, the LE/370 language environment, networking and, of course, DB2. The challenge
in most shops is that some people will have some of these skills, but not all of them. This paper will
attempt to highlight the essential skills for effective stored procedure implementation.

Stored procedures defined

In its most basic form, a stored procedure is a set of SQL statements residing at a server that may be
executed via a single SQL call. Stored procedures may be classified into two main types: internal and
external. Internal stored procedures consist of proprietary code and are typical of implementations by
such vendors as Oracle and Sybase. External stored procedures are written in COBOL or some other
commonly used language, such as PL/1, C or Java. As implemented in DB2 for OS/390 and z/OS, a
stored procedure is an application program containing SQL statements that run in an allied address
space called a stored procedure address space (SPAS). Figure 1 shows an example of a typical
stored procedure flow

Story of stored procedures

Stored procedure support was added years ago in DB2 for MVS V4. The initial support had limitations.
Stored procedures were limited to one DB2-managed address space. There was no exploitation of
MVS Workload Manager (WLM). There was no ability to "nest" stored procedure calls (one stored
procedure calling another stored procedure) or to run multiple stored procedure address spaces.
Language choices were limited to commonly available mainframe languages, such as COBOL and
PL/I.

DB2 V5 took stored procedure architecture further by adding support for multiple stored procedure
address spaces. These allow for additional flexibility, priority control and scalability. However, to
support multiple stored procedure address spaces, it is necessary to use WLM-managed stored
procedure address spaces. WLM-managed address spaces provide the fullest support and features
for stored procedure implementation in a true production environment. The more current versions of
DB2 have expanded support and capabilities. Stored procedures are able to nest, and one stored
procedure may in turn call a second or more -- up to 16 levels deep. There is broader language
support in the form of SQL language and Java.
Initially, many shops were slow to adopt and deploy stored procedure technology. Most shops used
stored procedures in a limited manner or in a testing mode. Now the majority of DB2 shops on OS/390
and z/OS are using stored procedures to some extent, and many are running large stored procedure
workloads. Primarily, WLM-managed stored procedures are being used. WLM-managed stored
procedures provide scalability and flexibility through multiple address space support needed for true
production-worthy implementations.
Stored procedures are used in myriad applications. So-called legacy applications, along with newer e-
business and WebSphere applications, may all exploit stored procedure technology. Language
choices typically involve COBOL, C, PL/I, with SQL Procedure Language and Java used to a lesser
extent.

Why stored procedures?

Stored procedures are an excellent way to encapsulate business logic and complex interactions to and
from the DB2 database with a single SQL call to the database layer. Stored procedures reduce
network overhead by reducing the number of send-and-receive operations, and by the elimination of
redundant back-and-forth network traffic. Stored procedures support the ability to perform multiple
SQL statements with only one network interchange.
The notion of the reduction of back-and-forth traffic extends beyond network considerations.
Applications built on sophisticated architectures, such as WebSphere, and constructed around J2EE
standards consist of multiple layers and components. In the example of WebSphere, there are many
layers: an HTTP layer, a servlet layer an Enterprise JavaBean (EJB) layer and a database layer
(commonly DB2). Each layer has its own set of queues and APIs that must be traversed by the
application. Encapsulating more logic at the database layer offers the potential to reduce the amount
of interaction across the various layers.
Because stored procedures may be written in a variety of languages, and may perform multiple and
potentially complex SQL calls, they make it easy to encapsulate sophisticated business rules within
one set of SQL calls from the calling application to the database. Figure 1 shows an example of the
encapsulation of multiple SQL calls within a stored procedure.
Stored procedures offer insulation of the application from the specifics of the database layer. For
example, stored procedures may be called from Java Database Connectivity (JDBC) applications. By
encapsulating database access within a stored procedure, SQL calls within the procedure may be
optimized for better performance. And the application developer doesn't need to be an expert in SQL
access path performance.

Stored procedure life cycle

Stored procedure processing adds steps to the typical DB2 thread life cycle. Figure 2 shows the steps
in the life cycle. The application first must connect to DB2 and create a thread. Thread creation also
starts the DB2 accounting record process. Next, the application issues an SQL CALL statement,
providing stored procedure input and output parameters. DB2 queues the request to WLM, which
manages stored procedure requests and sends them to the appropriate application environment
address space as defined within WLM and DB2.

WLM searches for an available task control block (TCB) in which the procedure may run. Typically,
there will be multiple TCBs defined within each address space. The SPAS loads the application
module from DASD into memory, unless the application module is already resident.
Once loaded, the stored procedure issues SQL statements into the DB2 subsystem. The stored
procedure may also access non-DB2 data, depending upon the needs of the application. The stored
procedure manager places information returned by the procedure into the output parameters and
returns control of the thread to DB2. DB2 then returns the data to the calling application.
The execution time line of a stored procedure or user-defined function (UDF) is affected by several
components, as shown in Figure 3. Some of these components are measurable from DB2 trace
sources; others must be measured from other sources, including WLM information. The time
components include:

• Base cost of stored procedure or UDF call


• Package load of stored procedure or UDF code into the EDM pool
• Scheduling of stored procedure or UDF in a stored procedure address space for execution
• Module load of stored procedure or UDF code (if not preloaded)
• LE/370 execution environment options
• Execution of SQL within the stored procedure or UDF
• Potential access to non-DB2 resources
• Operating system and WLM workload delays

There is the potential for queuing time to/from WLM for the stored procedure requests and scheduling
delays as WLM attempts to find an appropriate address space and TCB to run the request.

About enclaves

Enclaves are an important but commonly misunderstood construct in the MVS operating system.
Enclaves were originally created for DB2. However, enclaves are now used by many facilities in
OS/390 and z/OS, including Web support and WebSphere MQ middleware. An enclave is a
transaction that can span multiple dispatchable units (service request blocks (SRBs) and tasks) in one
or more address spaces. The enclave is reported on and managed as a unit. The enclave is managed
separately from the server address space or spaces in which it runs. WLM assigns the priority for the
enclave. This governs how fast and how much resource the distributed request is assigned by the
system. Enclaves are different from TCBs or SRBs in that they may span more than one dispatchable
unit of work and more than one address space. In addition, enclaves may span multiple systems.
Enclaves were originally created to support DB2 distributed (DDF). DB2 DDF processing is a good
example of how enclaves are exploited by DB2. When a stored procedure is called from a DDF thread,
DB2 references the enclave created for the DDF request for stored procedure. The stored procedure
priority is the priority of the DDF request. This is an example of an independent enclave.
When a stored procedure is called from an application on z/OS or OS/390, DB2 creates an enclave for
use by the stored procedure. The stored procedure priority is the priority of the calling application
address space. In this example, this would be the priority of the calling CICS/IMS or batch application
running on z/OS or OS/390. This is a dependent enclave, dependent upon the priority of the calling
application on the system.

Conclusion
This article began the discussion on the essential skills for effective stored procedure implementation.
Part Two will continue with more on WLM, scheduling delays, NUMTCB and language considerations,
and monitoring and managing stored procedures.

_________________________________________________________________________________

When it comes to stored procedures, there seem to be three kinds of developers: those who love
them, those who hate them, and those who don't really know what the heck they are. DBAs usually fall
into the first category, coders in the second, scripters in the third (as a former scripter, I can say that).
But in honor of all three, I'll go through a brief overview of stored procedures in general, including when
and when not to use them. Then I'll introduce DB2's version. If you don't love them already, you will by
the time we're done

What Is a Stored Procedure?

If a procedure is encapsulated logic that can be invoked from within your application, then a stored
procedure is simply a procedure that is stored on the database server. Usually written in SQL, the
stored procedure benefits from the power and proximity of the database from which it is managed.

If you've used a database at all in your applications, then you've most likely coded in SQL at some
point. To turn it into a stored procedure, you can include it within a CREATE PROCEDURE statement.
Technically, it would be a stored procedure and could thus be invoked from external applications. But
the true power of the stored procedure comes from its control syntax and ability to process multiple
statements. In other words, while you would rarely use a stored procedure for a single SELECT
statement, you could add INSERT, UPDATE, and DELETE statements, all controlled with IF/ELSE
logic, for example. Just about any database manipulation you're doing with your app code can be done
within a stored procedure instead, with all of its inherent benefits.

When Do I Use Stored Procedures?

Coders might argue that you never really need a stored procedure. All of your database calls can be
done programmatically. That's true, but somewhat limiting. Stored procedures can do a lot of things for
you that even the most elegant code cannot.

Chief among these, stored procedures save processor time by allowing you to offload database calls
to the database server itself. Most databases load the compiled procedures into memory the first time
they're called, or even before, dramatically reducing overhead when you're doing the same essential
process multiple times (such looping operations are very common in database manipulation).

Stored procedures offer you many other benefits, as well.

• They allow you to encapsulate code. In other words, the database operation appears once, in
the stored procedure, not multiple times throughout your application source. This improves
debugging as well as maintainability.
• Changes to the database schema affect your source code in only one place, the stored
procedure. Any schema changes then become a DBA task rather than a wholesale code
revision.
• Since the stored procedures reside on the server, you can set tighter security restrictions on
the client space, saving more trusted database permissions for the well-protected stored
procedures themselves.
• Since stored procedures are compiled and stored outside the application, they can use more
sensitive variables within the SQL syntax, such as passwords or personal data, that you
would avoid using in scripts or remote calls.
• Using stored procedures greatly reduces network traffic.

As a further illustration of this last point, suppose you want to update a customer record but you're not
sure if the record even exists. One way is (a) to SELECT the record to see if the customer exists, (b) to
UPDATE the record if it does, and (c) to INSERT a new record if it does not.

If you just put a series of SQL statements in your client code, each line is executed by sending a
message over the network to the server, usually getting a response in return. But a stored procedure
resides on the server. When called from the client application, it executes on the server and only has
to respond when returning the final result set to the client, saving lots of back-and-forth traffic.

One other benefit you'll find with DB2 stored procedures in particular, the distinction of which will be
explained in but a moment, is the Development Tooling support. The Enterprise edition of DB2 UDB
(Universal Database) ships with a set of developer tools that allow for fast, reliable creation of stored
procedures in both SQL and Java. Using the Wizards and Query Builders, you can create complex
procedures without typing a word of code.

When Would I Not Use Stored Procedures?

Whole discussion boards have been devoted to the pro/con debate on stored procedures. But when it
comes down to it, you have only a few occasions when it might not be possible or prudent to use them.

• You don't have the database permissions to create them. Or a cooperative DBA.
• You're only using a few SELECT statements in your application and can't really benefit from
the performance and organizational boosts offered by stored procedures (though you might
still profit from the other gifts of the stored procedure).
• Your organization is undergoing a major code migration and wants to avoid encapsulating
your source in external procedures. However, this is debatable as well since you may actually
benefit from the stability of SQL syntax.

What's Special About DB2's Stored Procedures?

DB2 expands on the definition of a stored procedure by allowing you to code them in just about any
language you may need. DB2 gives you two different kinds of stored procedures: a SQL procedure,
and an external procedure. In DB2, a stored procedure is a database object that encapsulates control-
flow logic, a mini application really, that runs in a "stored procedure address space." Going back to the
idea that a stored procedure is simply a chunk of compiled code, DB2 stored procedures can be
written in your language of choice, compiled, then referenced with SQL syntax.

The major difference between a SQL procedure and an external procedure is that SQL procedures
are, obviously, written in SQL. This means that the logic for the procedure is defined within the SQL
procedure body itself. By contrast, external procedures identify, load, and run a unit of code written in
an entirely different language. Early stored procedures were all essentially external, generally written
in C. Nowadays, when we talk about stored procedures, most people think of SQL procedures which
are written in easy to implement high-level SQL syntax. But DB2's external procedures provide a
handy option for the codernauts and those wanting to implement more complex logic than SQL can
support, using languages such as Visual Basic .NET, C, C++, C#, COBOL, Java, or REXX.

Huh?
How about an example?

The following external procedure demonstrates how Java can be used to control the logic of a
database operation. If you haven't used stored procedures before, then this type of code might look
familiar. It is essentially two SQL statements, one of which will be executed depending on a control-
flow condition. The difference here, though, is that the "application" in this case is the stored
procedure-body - the body in which the stored procedure functionality is defined.

/**
* JDBC Stored Procedure ADMINISTRATOR.UPDATE_SAL
*/
package proc.useraccount;

import java.sql.*; // JDBC classes

public class MYJAVACLASS


{
public static void UpdateSal (String [] empNum, Double rating )
throws SQLException
{
int errorCode = 0;
boolean bFlag;
String sql;
PreparedStatement stmt = null;

try
{
Connection con = DriverManager.getConnection("jdbc:default:connection");

if ( rating = 1 ) {
sql = "UPDATE employee "
+ "SET salary = salary * 1.10, "
+ "bonus = 1500 "
+ "WHERE empno = '" + empNum + "'";
}
else {
sql = "UPDATE employee "
+ "SET salary = salary * 1.05, "
+ "bonus = 1000 "
+ "WHERE empno = '" + empNum + "'";
}
stmt = con.prepareStatement( sql );
bFlag = stmt.execute();
}
catch ( SQLException sqle)
{
errorCode = sqle.getErrorCode();
throw new SQLException ( errorCode + " : " + errorLabel + " FAILED" );
}
}

If you're using the DB2 Development Center tooling, then once the procedure is created, the following
chunk of code is automatically generated by DB2. It creates a handle for the above procedure in the
database. When you call this procedure from your application, the above code is then looked up,
identified, found, and run by DB2.

CREATE PROCEDURE ADMINISTRATOR.UPDATE_SAL


( IN empNum CHAR(6), IN rating SmallInt )
SPECIFIC ADMINISTRATOR.UPDATE_SAL
DYNAMIC RESULT SETS 0
NOT DETERMINISTIC
LANGUAGE JAVA
PARAMETER STYLE JAVA
EXTERNAL NAME 'MyJavaClass.UpdateSal'
FENCED
THREADSAFE

For comparison, here is the same basic operation written as a SQL procedure. You'll see that the
UPDATE statement remains the same, but control flow operations are now managed by SQL syntax
included in the CREATE PROCEDURE statement itself.

CREATE PROCEDURE ADMINISTRATOR.UPDATE_SAL


(IN empNum CHAR(6), IN rating SMALLINT)
LANGUAGE SQL
BEGIN
IF rating = 1 THEN
UPDATE employee
SET salary = salary * 1.10,
bonus = 1500
WHERE empno = empNum;
ELSE
UPDATE employee
SET salary = salary * 1.05,
bonus = 1000
WHERE empno = empNum;
END IF;
END
Once your stored procedure has been successfully created and you have the privileges to invoke it
(you will have these by default if you are the creator) then the procedure can be called.

As you can see, SQL procedures give you an easy-to-use syntax for handling multiple statements and
control flow within the procedure itself. External procedures give you the power and flexibility of using
your language of choice, opening up all new possibilities for straight coders and DBAs alike.

How Do I Use Stored Procedures in my Application?

Just as your favorite language has a way to talk to your database, it also has a way to invoke your
database's stored procedures. Below is some C# which invokes the above example. In fact, because
of the uniform interface of DB2 stored procedures, this code could be used with either example since
they have the same parameter list.

For this snippet, imagine a form with an "Employee Number" textbox that supplies the IN parameter for
the procedure.

conn = new DB2eConnection(connString);


conn.Open();
DB2eParameter p1 =
new DB2eParameter("@p1", DB2eType.Char,6);
p1.Value = txtEmpNum.Text;
DB2eParameter p2 =
new DB2eParameter("@p2", DB2eType.SmallInt);
p2.Value = 1;
DB2eCommand cmd =
new DB2eCommand("ADMINISTRATOR.UPDATE_SAL", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
DB2eDataReader reader = cmd.ExecuteReader();

How Do I Get Started?

As mentioned earlier, DB2 makes it easy to create stored procedures by giving you not one but two
different wizards, one for SQL procedures and one for Java procedures. These can both be found in
the DB2 Development Center. In creating your stored procedures, you can either code them directly or
use a Query Builder to help you assemble them without coding a single command.

In addition to this portal, you have several resources available for learning more. One excellent tutorial
shows you the basics of creating a stored procedure, then using it with Visual Studio .NET: "Build and
access DB2 stored procedures using mobile clients".

If you run into trouble, you can find extensive help in the DB2 Information Center: Stored Procedures.

Also be sure to check out "IBM DB2 Development Add-Ins for Visual Studio .Net" for more detailed
information on DB2's integration with VS.NET which allows you to make DB2 stored procedures right
within Visual Studio.

And of course, you'll want to download DB2 itself, if you haven't already. Look for DB2, Enterprise
Edition.

Das könnte Ihnen auch gefallen