14
1 System i Stored Procedures What are Stored Procedures Uses for Stored Procedures Where can Stored Procedures be called from Why use Stored Procedures over other options How to create a Stored Procedure External Stored Procedures SQL Stored Procedures Good Practices On the CD Helpful Links And more ................ Presented by : Chuck Walker The System Solutions Group, llc Stored Procedures

Stored-Procedures-Presentation

Embed Size (px)

Citation preview

Page 1: Stored-Procedures-Presentation

1

System i Stored Procedures

What are Stored Procedures

Uses for Stored Procedures

Where can Stored Procedures be called from

Why use Stored Procedures over other options

How to create a Stored Procedure

External Stored Procedures

SQL Stored Procedures

Good Practices

On the CD

Helpful Links

And more ................

Presented by : Chuck Walker

The System Solutions Group, llc

Stored Procedures

Page 2: Stored-Procedures-Presentation

2

What are Stored Procedures ? Stored procedures offer a safe, portable and reliable way to build application-to-application

interfaces in many environments, including e-business WebSphere applications on the iSeries as well as MS-Dot-Net Web and Windows applications. A client program can CALL a server program using the database manager's support for stored procedures.

Stored Procedures are an excellent place to establish and enforce business rules as well as

calculations. It would not be uncommon to have some Windows applications being used as well as a

Web based application that use the same databases and same stored procedures. If your business

rules are maintained in the stored procedures instead of within the application code you would only

have one place to change if modifications need to be made.

Stored procedures allow SQL clients to call application logic using the CALL statement. The

procedure called can be defined in SQL procedure language or as an external program in any high

level language (RPG, COBOL, Java, C++ etc). For Java applications, JDBC (Java Database Connectivity) provides a stored procedure SQL escape

that allows stored procedures to be called in a standard way for all RDBMSs.

Uses for Stored Procedures

Sample uses for procedures include the following:

* Integrating client and host application execution across platforms.

* Accessing host data efficiently with a remote application and returning results to

the client.

* Updating, inserting or deleting rows in host tables easily.

* Run a simple CL program passing a command string to execute. (That eliminates need for using

Toolbox and Remote command calls in most cases.)

Page 3: Stored-Procedures-Presentation

3

Where can Stored Procedures be called from ?

System i Stored Procedures can be executed locally on a single system or from different applications across a network. JDBC drivers like the iSeries Java toolbox driver (type 4 JDBC drivers) can run anywhere in a network. Many JDBC drivers exist in the market for almost every need today. The one scenario where a JDBC driver is usually NOT the best solution is for a client application accessing a server application over the Web. The host database remote access support (IBM's DRDA ) usually runs on a specific port. Opening this port through a firewall for Internet access is NOT the best idea. Options include VPN or some other remote access method.

Web applications DO work very well WHEN the procedures are invoked by an application

running on a server. Often, a user is working in a Web browser using an application running in

WebSphere, WebLogic, etc.

In other words, call the stored procedures from a java servlet or from MS-Dot-Net server side code

instead of browser side code. All Stored procedure calls should come from within the network

proxy.

Why use Stored Procedures over other options? The DB2 stored procedure builder can CREATE stored procedure applications

easily. Stored procedures are the "portable" way to integrate existing server

applications. They can return result sets for applications that bring reports to a

browser, etc. Procedures execute in the stable database environment.

Procedures can be invoked anywhere in the network.

The majority of existing and server program stored procedure calls can be converted

to DB2 stored procedure calls with no more than a connection property changes.

Whenever possible Stored Procedures should be used to Insert. Update, or Delete records.

If all of your application programs use the same stored procedures for these functions then the

obvious place to enforce business rules restrictions is in the stored procedure.

If your applications are structured in this manner then there is only one place to make changes to

your business rules logic when needed.

The reason a Stored Procedure should be used is that it can be called from any platform (Web,

Windows, etc) as well as a static call from an RPG program.

Order Entry Manual Input

Telephone Sales

Incoming

Order – Web

Application

Stored Procedure Order validation

/ post

Order Header

Table

Order

Detail

Table

Incoming

Order

EDI Order

Page 4: Stored-Procedures-Presentation

4

External Stored Procedures There are 2 different types of DB2 stored procedures – External and Internal (SQL) stored

procedures. External Stored Procedures may be created using the high level languages we are

familiar with such as RPG, COBOL, CL, and C. All the same benefits of using SQL Stored

Procedures apply to External Stored Procedures. If you are more comfortable writing complex code

in one of these languages instead of SQL or if you want to use existing programs this may be a

preferable option.

System i doesn't create a Stored Procedure object for External Stored Procedures. Instead it takes

an existing program object and registers it so it may be used as a stored procedure. Although

Service programs may not be registered as stored procedures you may register a program object

that uses bound service programs. So if you have existing service programs you can still have

access to them through stored procedures. The program objects allowed are *PGM objects

compiled with an activation group of *CALLER.

To register a program as a stored procedure using Navigator:

1. Open Navigator 2. Expand the Database listing in the left panel

3. Expand your System Database Name 4. Highlight the Libraries listing

5. Right click on the Library to hold your Stored Procedure.

6. On the pop-up menu select New / Procedure / External. Within the SQL Procedure Window

there are 3 tabs:

General Procedure Name, Description, Read Only, etc

Parameters Define Stored Procedure Parameters External Program Program, Library and Language details for the program being

Registered

The General Tab:

Page 5: Stored-Procedures-Presentation

The Parameters Tab :

The External Program Tab:

New External Prxxedure 111 ORDAPPLIB - Monabo(naginacol

General Perentelers naernaf Program

Parameter N I Turrori 1 Anarl, [ CIS_. I IniOur I I. n I liraRryinMn

Year INTEGER IN Month INTEGER IN Calendar month 10 be scanner;

Supp lie r,,Narne CI-APACTER 2a OUT Supplier with the hi]hest sal as

finale DECIMAL 11,2 OUT Total 56105

11

Parameter styte:

SOL

r Simple, allow nuli values

Simple. verbree allowed

r Jaya

I n s e r t

Delete

New External Procedure in ORDAPPLIB -

MOnarber(Merneiba) General) Parameters Exlernel Pro gram

Program:

Library:

Lanyudge

C Java method

]Hs el e s

IORD.APP_113

111111111111111111111

Page 6: Stored-Procedures-Presentation

6

Returning Recordsets :

One of the most common uses of stored procedures is to return a recordset (a collection of rows)

for display or other processing. Let’s take a look at an RPG program that does this. The following

example is a program written by Scott Klement that returns a list of dates and the corresponding day

of week for the next 10 working days. It is an ILE RPG with embedded SQL program written in RPG Free.

H DFTACTGRP(*NO)

D GetDOW PR 9A varying

D myDate D const

D count s 10I 0

D DayList ds occurs(10)

D Date 10A

D Name 9A varying

D x s 10I 0

D dayname s 9A varying

D NextDate s D datfmt(*ISO)

/free

// This gets the next 10 work days.

// (For this example, work days are

// Monday through Friday)

Count = 0;

NextDate = %date();

for x = 1 to 10;

dou dayname<>'Saturday'

and dayname<>'Sunday';

NextDate = NextDate + %days(1);

dayname = GetDOW(NextDate);

enddo;

%occur(DayList) = x;

Date = %char(NextDate:*ISO);

Name = dayname;

Count = Count + 1;

endfor;

/end-free

C/exec sql Set Result Sets Array :DAYLIST for :COUNT Rows

C/end-exec

c eval *inlr = *on

c return

*++++++++++++++++++++++++++++++++++++++++++++++++++++++++

* GetDOW(): Get the day of the week for a given date

*++++++++++++++++++++++++++++++++++++++++++++++++++++++++

P GetDOW B

D GetDOW PI 9A varying

D myDate D const

D SUN c const(d'2006-01-01')

D days s 10I 0

D dowk s 10I 0

/free

days = %diff(myDate: SUN: *DAYS);

dowk = %rem(days: 7);

select;

when dowk = 0;

return 'Sunday';

This embedded

SQL statement is

how the recordset

is returned to the

caller.

The DAYLIST multiple

occurring data structure is

where the result set is

held. It has 2 columns.

Date and day name.

Page 7: Stored-Procedures-Presentation

7

when dowk = 1;

return 'Monday';

when dowk = 2;

return 'Tuesday';

when dowk = 3;

return 'Wednesday';

when dowk = 4;

return 'Thursday';

when dowk = 5;

return 'Friday';

when dowk = 6;

return 'Saturday';

endsl;

/end-free

P E

A program could easily be written to accept search criteria in parameters, use SETLL / READE to

retrieve records and fill up a multiple occurring data structure from physical file data. Although this

program is written in RPG Free you can do the same thing in RPG IV or RPG III.

Using these same methods you might write an RPG program that returns a single value, a single

record, updates your physical files, etc. It is a good practice to always return a value to the caller,

even if it is only a value that says all operations where performed successfully. Most platforms use

an integer value of zero to indicate success. Failure is 1 or possibly an error identifier value.

If you wanted to convert a Dot-Net application to use your DB2 files instead of SQL Server tables

and the Dot-Net application uses stored procedures to retrieve recordsets and update tables (as most

do) you could simply create equivalent DB2 stored procedures to replace the SQL Server stored

procedures using the same stored procedure names. Dot –Net uses a connection string (usually kept

in the WEB.CONFIG file) to connect to a database. You could then simply change the connection

string to use your System i files instead. Under this scenario no code changes or compiles are

necessary in your Dot-Net application.

Page 8: Stored-Procedures-Presentation

8

SQL / Internal Stored Procedures There is a DB2 stored procedure builder included in Client Access Navigator. To access it :

1. Open Navigator

2. Expand the Database listing in the left panel

3. Expand your System Database Name

4. Highlight the Libraries listing

5. Right click on the Library to hold your Stored Procedure. On System i the library is the

equivalent of what is referred to as a Schema on other platforms such as SQL Server.

6. On the pop-up menu select New / Procedure / SQL. Within the SQL Procedure Window

there are 3 tabs:

General Procedure Name, Description, Read Only, etc Parameters Define Stored Procedure Parameters

SQL Statements SQL statements for your Stored Procedure

Most of us are familiar with SQL Statements such as Select, Update and Insert. Some are familiar

with Cursors. All of the modern day SQL languages allow and support complex programming and

decision making just as your RPG programs do. If / Else statements, Do Loops, Case Statements,

etc. are all supported in DB2-400, DB2-UDB, SQL Server (T-SQL) Oracle (PLSQL), and more. So

it’s perfectly reasonable to incorporate complex business logic into a Stored Procedure.

Page 9: Stored-Procedures-Presentation

9

There is a file on the CD named Sample.SQL. This is an example of an RPG program that does a

Bill of Material Explosion that was converted to T-SQL (SQL Server). I am including it on the

CD as an example of a fairly complex program written in SQL, but it is too long to include

within this article.

There are some drawbacks to using Internal SQL stored procedures. Although there is some

extensions in ORACLE to support what we refer to as Sub Routines there is no such support in

most other versions of SQL including DB2 and T-SQL. So, that leaves limited possibilities of

how to accomplish this within SQL, none of which are preferable.

The first is to use GOTO’s and Tags, much like we used to do in CLP programs before IBM

included subroutines in their CL language. This is the method used in the Sample.SQL program

mentioned above.

The other option is to write separate stored procedures or user defined functions that are

executed from the initial stored procedure where you would normally execute a subroutine.

Obviously the downside with this method is that you have code spread out across different

objects.

The only other option is to duplicate code in a top down design within the initial stored

procedure. This is one of the drawbacks that may make an External Stored Procedure a

preferable option in some cases.

Page 10: Stored-Procedures-Presentation

10

This is an example of a DB2 SQL procedure from the DB2-StoredProcedures-Triggers-UDFs.pdf Redbook. Here is an example in which the procedure receives an input parameter, which is the percentage of increase for the customer credit limit. This increase is applied to all customers. The procedure returns the number of records that were updated to the calling program:

CREATE PROCEDURE CREDITP 1 (IN i_perinc DECIMAL(3,2), 2 OUT o_numrec DECIMAL(5,0)) 3 LANGUAGE SQL BEGIN ATOMIC 4

DECLARE proc_cusnbr CHAR(5); DECLARE proc_cuscrd DECIMAL(11,2); DECLARE numrec DECIMAL(5,0); DECLARE at_end INT DEFAULT 0; DECLARE not_found CONDITION FOR '02000'; DECLARE c1 CURSOR FOR SELECT cusnbr, cuscrd

FROM ordapplib.customer; DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1; SET numrec = 0; OPEN c1; FETCH c1 INTO proc_cusnbr, proc_cuscrd; WHILE at_end = 0 DO SET proc_cuscrd = proc_cuscrd +(proc_cuscrd * i_perinc);

UPDATE ordapplib.customer SET cuscrd = proc_cuscrd WHERE CURRENT OF c1; SET numrec = numrec + 1; FETCH c1 INTO proc_cusnbr, proc_cuscrd; END WHILE; SET o_numrec = numrec; CLOSE c1;

END 5

Notes: 1 The name of the procedure is defined as CREDITP. 2 It has an input parameter, which is i_perinc (the percentage of increase for all customers). 3 It has an output parameter, which is o_numrec (the number of records that were updated). 4 The rest of the lines are the SQL procedure body that consists of a single compound SQL control

statement. This compound statement permits you to group other SQL control statements and SQL procedure statements together. Every compound statement starts with the clause BEGIN.

5 Every compound statement ends with an END clause.

Page 11: Stored-Procedures-Presentation

11

Another method of creating DB2 Stored Procedures from within iseries Navigator is the Run SQL

Scripts utility. After starting Navigator highlight the Databases icon in the left panel. Right click on

your database name in the right panel. In the pop-up menu select Run SQL Scripts. This utility will

allow you to create, edit and run SQL scripts. You can also save the scripts on your PC.

This utility has a syntax checker in the Run drop down menu.

When using the Procedure Builder the procedure name, parameters and Language are all taken care

of by entries under the General and Parameters tabs. So the only code needed is the body which is

between the BEGIN and END statements. When using the Run SQL Scripts utility the CREATE

PROCEDURE statements as well as the parameter declarations and LANGUAGE statements are

needed. You will also need to qualify your Library Name. Example – CREATE PROCEDURE

LIBNAME.CREDITP

Page 12: Stored-Procedures-Presentation

12

Although we have concentrated on using Navigator to register external stored procedures you may

also do so from an interactive SQL session. Simply key in STRSQL at a command line and strike

enter. When your SQL session is started key in CREATE PROCEDURE sand strike F4.

Page 13: Stored-Procedures-Presentation

13

Good Practices: For monitoring performance of stored procedures I would suggest creating a table (physical file) to

log stored procedure execution and performance. This table would include the stored procedure

name, start time, completion time, and execution duration in seconds. Each stored procedure would

have some standard code to retrieve the system time when it is initialized, retrieve the system time

again when it is completed, and calculate the duration in seconds. Then insert a record into the log.

This will allow an easy collection of data you may use to see what stored procedures need some

attention for performance reasons.

Select Statements:

Although it is easier to use Select * From XYZ instead of Select field1, field2, field3 From XYZ it

is almost never more efficient. Particularly in an environment where you may be passing data

through communications ports on different platforms and / or there is data conversion functions

happening under the covers (EBCDIC / ASCII). If you can shorten the recordset length to the 3 or

4 fields you actually need instead of the 50 fields that are in the record your performance will be

much better.

Other Documentation included on the CD :

Title Description

Stored-Procedures-

Presentation.PDF

A copy of this document in PDF format

DB2-StoredProcedures-Triggers-

UDFs.pdf

This is the IBM Red book for Stored Procedures, SQL Triggers, and User Defined Functions for DB2. This is a

well written, very informative Red Book.

DB2-for-i-SQL-Reference-

V6R1.pdf

IBM SQL Reference manual.

Sample.SQL This is an example of an RPG program converted to T-SQL

(SQL Server)

Retrieve an SQL Result Set with

RPG.PDF

This is a copy of an on-line article posted by Scott Klement.

Not only does he give examples of how to write an RPG

program to return a result set, he also gives some examples of

how to Call a stored procedure from an RPG program and use

the returned result set in RPG.

Return a result set from RPG

III.PDF

An example of how to write a program that returns a record set

with RPG III code

CallFromPHP-JAVA This folder contains several examples of how to call DB2

stored procedures from PHP and JAVA.

Page 14: Stored-Procedures-Presentation

14

Helpful Links :

The SQL Reference book. View an HTML online version of the book, or print a

PDF version, from the DB2 Universal Database for AS/400 books online AS/400 Information Center topic.

Stored procedures examples:

· Example: Stored procedure calls from C with return values

· Example: Stored procedure calls from C with result sets · Example: Host RPG source

· Example: Running CL commands using SQL stored procedures and ODBC · Example: Stored procedure calls from Visual Basic with return values

· Examples: Calling an AS/400 stored procedure by using Visual Basic

Additional resources for examples of calling stored procedures:

For more ODBC programming examples of calling stored procedures (Visual Basic 4.0,

Visual Basic 5.0, C++, and Lotus Script programming environments), see:

· Express ODBC programming examples

· IBM ftp Web site (select the vbODBCT3.zip directory to download the programming examples to your PC).