store procedure

254
Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder Patrick Dantressangle, Debra Eaton, Mark Leung, Ricardo D. Macedo, Ling Tay Maria Sueli Almeida, Jarek Miszczyk International Technical Support Organization SG24-5485-00 www.redbooks.ibm.com

Upload: omar-molina

Post on 28-Oct-2014

96 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Store Procedure

Developing Cross-Platform DB2 Stored Procedures:SQL Procedures and the DB2 Stored Procedure Builder

Patrick Dantressangle, Debra Eaton, Mark Leung, Ricardo D. Macedo, Ling TayMaria Sueli Almeida, Jarek Miszczyk

International Technical Support Organization

SG24-5485-00

www.redbooks.ibm.com

Page 2: Store Procedure
Page 3: Store Procedure

International Technical Support Organization SG24-5485-00

Developing Cross-Platform DB2 Stored Procedures:SQL Procedures and the DB2 Stored Procedure Builder

November 1999

Page 4: Store Procedure

© Copyright International Business Machines Corporation 1999. All rights reserved.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.

First Edition (November 1999)

This edition applies to DB2 for OS/390 Version 5 and Version 6 with applied service maintenance, for DB2 for AS/400V4R2 and beyond, and for DB2 for UNIX, Windows, and OS/2 for the release after Version 6, and other currentversions and releases of IBM products. Make sure you are using the correct edition for the level of the product. Thisedition is based on the latest beta version of SQL Procedures language support and IBM Stored Procedure Builder.

Comments may be addressed to:IBM Corporation, International Technical Support OrganizationDept. QXXE Building 80-E2650 Harry RoadSan Jose, California 95120-6099

When you send information to IBM, you grant IBM a non-exclusive right to use or distribute the information in anyway it believes appropriate without incurring any obligation to you.

Before using this information and the product it supports, be sure to read the general information in Appendix B,“Special notices” on page 223.

Take Note!

Page 5: Store Procedure

Contents

Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiThe team that wrote this redbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiComments welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Chapter 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11.1 DB2 stored procedures — evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11.2 Cross-platform support of stored procedures written entirely in SQL . . . . . .61.3 Building DB2 stored procedures from your workstation . . . . . . . . . . . . . . . .61.4 Concepts and terminology. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7

Chapter 2. The SQL Procedures language . . . . . . . . . . . . . . . . . . . . . . . . . .92.1 What is it?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .92.2 Planning to use the SQL Procedures language . . . . . . . . . . . . . . . . . . . . .10

2.2.1 Why use it? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102.2.2 When to use them? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13

2.3 Comparing SQL stored procedures and external stored procedures . . . . .162.3.1 Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .162.3.2 Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17

2.4 Current implementation of SQL Procedures language . . . . . . . . . . . . . . . .172.4.1 How does this work in general? . . . . . . . . . . . . . . . . . . . . . . . . . . . . .182.4.2 Declaring SQL local variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .192.4.3 Language Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .202.4.4 Returning result sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .292.4.5 Handling errors in an SQL stored procedure . . . . . . . . . . . . . . . . . . .332.4.6 Current restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .36

2.5 SQL Procedures portability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .362.6 New error messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .392.7 Migrating from OEM DBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40

2.7.1 Migrating the database structure . . . . . . . . . . . . . . . . . . . . . . . . . . . .402.7.2 Migrating the database data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .412.7.3 Migrating the business logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .412.7.4 Comparison with Sybase/Microsoft SQL Server Transact-SQL . . . . .432.7.5 Comparison with Oracle PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . .482.7.6 Comparison with Informix SPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55

Chapter 3. The DB2 Stored Procedure Builder . . . . . . . . . . . . . . . . . . . . . .573.1 DB2 Stored Procedure Builder — overview . . . . . . . . . . . . . . . . . . . . . . . .57

3.1.1 What is it? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .573.1.2 Programming languages supported . . . . . . . . . . . . . . . . . . . . . . . . . .58

3.2 Product Installation on Windows NT . . . . . . . . . . . . . . . . . . . . . . . . . . . . .603.2.1 Prerequisites for SPB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .603.2.2 Installing the SPB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61

3.3 Advanced configuring of the SPB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .653.3.1 Concepts and terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .753.3.2 What are its components? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .773.3.3 Working with SPB projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79

3.4 Using the Stored Procedure Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83

© Copyright IBM Corp. 1999 iii

Page 6: Store Procedure

3.4.1 Viewing existing stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . 833.4.2 Creating new stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . 853.4.3 Building stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1013.4.4 Modifying existing stored procedures . . . . . . . . . . . . . . . . . . . . . . . 1023.4.5 Copying and pasting stored procedures across connections . . . . . 1043.4.6 Debugging stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

Chapter 4. SQL Procedures for DB2 UDB for OS/390 . . . . . . . . . . . . . . . 1094.1 General considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1094.2 System requirements and planning . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

4.2.1 Requirements for DB2 for OS/390 Version 5 . . . . . . . . . . . . . . . . . 1094.2.2 Requirements for DB2 UDB for OS/390 Version 6 . . . . . . . . . . . . . 1114.2.3 Remote Debugger and Debug tool . . . . . . . . . . . . . . . . . . . . . . . . . 1124.2.4 Creating non-catalog DB2 tables . . . . . . . . . . . . . . . . . . . . . . . . . . 1124.2.5 WLM requirements for OS/390 Procedure Processor . . . . . . . . . . . 114

4.3 Coding considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1154.3.1 Length and size limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1154.3.2 Parameters and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1154.3.3 Handling SQLCODE and SQLSTATE values . . . . . . . . . . . . . . . . . 1174.3.4 SQL statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1174.3.5 Client application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

4.4 Stored procedure preparation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1184.4.1 Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1194.4.2 Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

4.5 Setting up DSNTPSMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1204.5.1 Using the SPB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1224.5.2 Using OS/390 Procedure Processor (DSNTPSMP) . . . . . . . . . . . . 1254.5.3 Using JCL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

4.6 Stored procedure debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1424.6.1 Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1434.6.2 If the debugger does not start . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Chapter 5. SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 . . . 1455.1 General considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1455.2 Supported platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1465.3 System requirements and planning . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

5.3.1 Requirements for the Windows NT platform . . . . . . . . . . . . . . . . . . 1465.3.2 Requirements for the UNIX platform . . . . . . . . . . . . . . . . . . . . . . . 1485.3.3 Changing compiler options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1495.3.4 Retaining intermediate files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

5.4 Coding considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1515.4.1 Recommendations for writing portable stored procedures . . . . . . . 1515.4.2 Structure of SQL stored procedures . . . . . . . . . . . . . . . . . . . . . . . . 1515.4.3 Coding the SQL stored procedures body . . . . . . . . . . . . . . . . . . . . 152

5.5 Stored procedures preparation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1595.5.1 Privileges required to prepare an SQL stored procedure . . . . . . . . 1615.5.2 Preparing an SQL stored procedure from the DB2 CLP . . . . . . . . . 1625.5.3 Preparing an SQL stored procedure from the DB2 tools. . . . . . . . . 1625.5.4 Preparing an SQL stored procedure from application programs . . . 1645.5.5 Preparing an SQL stored procedure from the SPB. . . . . . . . . . . . . 1645.5.6 Copying SQL stored procedures between DB2 UDB servers . . . . . 165

5.6 Stored procedure debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1665.6.1 Platforms supported for remote debugging . . . . . . . . . . . . . . . . . . 166

iv Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 7: Store Procedure

5.6.2 The DB2DBG.ROUTINE_DEBUG debugger table . . . . . . . . . . . . . .1665.6.3 DB2 environment variables for debugging . . . . . . . . . . . . . . . . . . . .1675.6.4 Starting the debugger client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1685.6.5 Debugging stored procedures through SPB. . . . . . . . . . . . . . . . . . .168

Chapter 6. SQL Procedures for DB2 UDB for AS/400 . . . . . . . . . . . . . . . .1696.1 General Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1696.2 System requirements and planning . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1696.3 System Catalog Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1696.4 Creating an SQL stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . .170

6.4.1 Creating an SQL SP with traditional tools . . . . . . . . . . . . . . . . . . . .1706.4.2 Creating an SQL SP with Operations Navigator GUI . . . . . . . . . . . .1746.4.3 Creating an SQL SP with the Run SQL Scripts utility. . . . . . . . . . . .1766.4.4 Verifying the stored procedure properties . . . . . . . . . . . . . . . . . . . .179

6.5 Deleting or replacing the SQL stored procedure . . . . . . . . . . . . . . . . . . .1806.6 Debugging SQL stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . .181

6.6.1 The ILE Source Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1816.6.2 Preparing the SQL stored procedure for debugging. . . . . . . . . . . . .1826.6.3 Testing the SQL stored procedure in traditional environment . . . . .1846.6.4 Testing the SQL stored procedure in client/server environment . . . .188

Appendix A. Sample SQL stored procedure programs . . . . . . . . . . . . . . . 195A.1 Naming convention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195A.2 OS/390 samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195

A.2.1 DSN8ES1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195A.2.2 SDK0LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197A.2.3 SDK1LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198A.2.4 SDK2LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199A.2.5 SDK3LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199A.2.6 SDK4LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200A.2.7 SDK5LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201A.2.8 SDK6LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201A.2.9 SDK7LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202A.2.10 SDK8LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203A.2.11 SDK9LMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204A.2.12 SMP0LMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204A.2.13 SMP1LMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205A.2.14 SMP2LMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205A.2.15 SMP3LMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206A.2.16 SMP4LMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206A.2.17 SMP5LMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207A.2.18 SMP5LMS2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207A.2.19 SMP7LMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207A.2.20 SMP8LMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208A.2.21 SMP8LMS2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

A.3 NT and AIX samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209A.3.1 SDK0LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209A.3.2 SDK1LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210A.3.3 SDK2LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211A.3.4 SDK3LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211A.3.5 SDK4LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212A.3.6 SDK5LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213A.3.7 SDK6LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

v

Page 8: Store Procedure

A.3.8 SDK7LNS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .214A.3.9 SDK8LNS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .215A.3.10 SDK9LNS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .216A.3.11 SDKALNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .216A.3.12 SMP1LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .217A.3.13 SMP2LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .218A.3.14 SMP3LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .218A.3.15 SMP4LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .219A.3.16 SMP5LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .219A.3.17 SMP7LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .219A.3.18 SMP8LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .220A.3.19 SMP9LNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .220A.3.20 SMPALNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .221

Appendix B. Special notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .223

Appendix C. Related publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227C.1 International Technical Support Organization publications . . . . . . . . . . . . . .227C.2 Redbooks on CD-ROMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227C.3 Other publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227

How to get ITSO redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229IBM Redbook Fax Order Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .230

List of abbreviations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

ITSO redbook evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

vi Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 9: Store Procedure

Figures

1. The usual SQL client, where the logic sends many SQL queries . . . . . . . . . . 122. SQL client using the same logic, but within an SQL stored procedure. . . . . . 123. An example of shielding tables from users . . . . . . . . . . . . . . . . . . . . . . . . . . . 134. Behavior summary of different condition handlers . . . . . . . . . . . . . . . . . . . . . . 345. SPB environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576. Invoking SPB through VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627. Specify Database Connection Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638. SPB main frame invoked through VA Java Workbench. . . . . . . . . . . . . . . . . . 649. Customizing Microsoft Visual Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6510. Stored Procedure Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6711. SPB: Previous Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6812. Environment Properties: Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6813. Environment Properties: Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6914. Environment Properties: Assistance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6915. Environment Properties: Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7016. Environment Properties: Debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7017. Environment Properties: OS/390 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7118. Environment Properties: SQL Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7119. Environment Properties: Type Mapping. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7220. SPB main panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7721. The New Stored Procedures SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7822. SQL Assistant window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7923. SPB projects (*.spp), connections and stored procedures. . . . . . . . . . . . . . . . 8024. Creating new project "ITSO SG245485" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8125. Tree view of existing stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8326. Detailed view of existing stored procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . 8427. Filtering the list of stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8428. The Filter dialog window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8529. Creating a new SQL stored procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8630. The Name panel of the New Stored Procedures SmartGuide . . . . . . . . . . . . . 8731. The Pattern panel of the New Stored Procedures SmartGuide . . . . . . . . . . . . 8832. The SQL Query panel of the New Stored Procedures SmartGuide . . . . . . . . . 9033. The Parameters panel of the New Stored Procedures SmartGuide . . . . . . . . 9134. The Define Parameter dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9135. The Options panel of the New Stored Procedures SmartGuide . . . . . . . . . . . 9236. The Advanced options for DB2 for OS/390 SQL stored procedures . . . . . . . . 9337. The Advanced build options for DB2 for OS/390 SQL stored procedures . . . . 9438. The Tables panel of the SQL Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9539. The Join panel of the SQL Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9640. Changing the type of Join created by SQL Assistant . . . . . . . . . . . . . . . . . . . . 9641. The Conditions panel of the SQL Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . 9742. Specifying a variable for a condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9743. The Columns panel of the SQL Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9844. The Sort panel of the SQL Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9945. The SQL panel of the SQL Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10046. Entering values for variables in the SQL statement . . . . . . . . . . . . . . . . . . . . 10147. Displaying the results of the SQL Statement . . . . . . . . . . . . . . . . . . . . . . . . . 10148. Modifying an existing stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10349. Copying one SQL stored procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10450. Paste the stored procedure at the target server. . . . . . . . . . . . . . . . . . . . . . . 105

© Copyright IBM Corp. 1999 vii

Page 10: Store Procedure

51. Debugging process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10652. IBM Distributed Debugger daemon. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10653. IBM Distributed Debugger main window . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10754. Monitoring variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10855. Multiple WLM environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11456. Three methods for preparing SQL stored procedures . . . . . . . . . . . . . . . . . .11957. Build Name field on OS/390 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12258. OS/390 Options from SPB — 1/2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12359. OS/390 Options from SPB — 2/2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12360. SQL Costing Information panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12561. Input / Output for SQL Procedures Processor . . . . . . . . . . . . . . . . . . . . . . . .12662. The BUILD process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13063. The DESTROY process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13164. DSNHSQL process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13765. Using the same name for variables and parameters . . . . . . . . . . . . . . . . . . .15466. Using variables with the same name as a column . . . . . . . . . . . . . . . . . . . . .15467. Assigning special registers to variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15568. Assigning results of built-in functions to variables. . . . . . . . . . . . . . . . . . . . . .15669. Setting both SQLCODE and SQLSTATE variables to program variables . . .15770. Nested compound statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15771. Setting a SAVEPOINT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15872. Ways to create SQL stored procedures in DB2 UDB . . . . . . . . . . . . . . . . . . .16073. Preparation steps for SQL stored procedures in DB2 UDB . . . . . . . . . . . . . .16174. STP.DB2 file containing SQL stored procedures using $ as a delimiter . . . . .16275. Changing the terminating character for the DB2 Command Center . . . . . . . .16376. Changing the termination character for DB2 tools . . . . . . . . . . . . . . . . . . . . .16477. Using SPB to prepare SQL stored procedures . . . . . . . . . . . . . . . . . . . . . . . .16578. Entering source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17279. Creating the SQL stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17280. Working with spool files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17381. Displaying SQL precompiler error messages . . . . . . . . . . . . . . . . . . . . . . . . .17482. Parameters definition for SQL stored procedure. . . . . . . . . . . . . . . . . . . . . . .17583. Entering SQL statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17684. Creating SQL SP with script utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17785. Job log window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17886. Saving SQL Script File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17987. Displaying the stored procedure properties . . . . . . . . . . . . . . . . . . . . . . . . . .18088. Deleting a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18189. RUNSQLSTM command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18390. Specifying the DBGVIEW and OUTPUT parameters . . . . . . . . . . . . . . . . . . .18491. Starting a debug session. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18592. Debug session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18693. INVDSK2LMS source code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18794. Running Java client. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18895. Finding the database server job . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18996. Job log for a database server job . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18997. Calling the stored procedure from Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19098. Naming convention for samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .195

viii Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 11: Store Procedure

Tables

1. SQL Procedures portability across DB2 platforms . . . . . . . . . . . . . . . . . . . . . . 362. RDBMS Stored Procedure language comparison . . . . . . . . . . . . . . . . . . . . . . 423. Comparison between SQL/PSM and T/SQL control statements . . . . . . . . . . . 444. Comparison between DB2 and Sybase SQL Server . . . . . . . . . . . . . . . . . . . . 455. Comparison between SQL/PSM and PL/SQL control statements . . . . . . . . . . 496. Comparison between DB2 and Oracle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507. Comparison between SQL/PSM and SPL control statements . . . . . . . . . . . . . 558. DB2SPB.INI file sections and keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729. SYSIBM.SYSPSM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11310. SYSIBM.SYSPSMOPTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11311. SYSIBM.SYSPSMOUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

© Copyright IBM Corp. 1999 ix

Page 12: Store Procedure

x Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 13: Store Procedure

Preface

This redbook is intended for DB2 application developers who are familiar withStructured Query Language (SQL) and stored procedures, and who want to learnabout developing stored procedures in the SQL Procedures language, as well asusing and exploring the Stored Procedure Builder (SPB). Our discussionparticularly applies to Version 6 of DB2 Universal Database Server for OS/390,for AS/400, and for distributed platforms, Version 5 of DB2 Server for OS/390,and other current versions and releases of IBM products.

First, we present the evolution of the IBM stored procedures support, describingin detail the new stored procedures language, SQL Procedures; and the new tool,Stored Procedure Builder.

In addition, we cover the implementation of these new features across platformssuch as OS/390, Windows, and UNIX. The sample SQL stored proceduresprograms implemented during this project are documented in detail. Most ofthose samples are delivered with the SPB product. The sample SQL storedprocedures programs illustrate the theory discussed in this redbook. Theseprograms are useful for getting started with the SQL Procedures language in yourown environment and gaining some hands-on experience on whatever platformyou may have.

The support for the SQL Procedures language provides the customer with thefacility for developing their stored procedures in a standard and portablelanguage across the DB2 family and OEM DBMSs.

The team that wrote this redbook

This redbook was produced by a team of specialists from around the worldworking at the International Technical Support Organization San Jose Center.

Patrick Dantressangle is an advisory software engineer working for IBM SantaTeresa Laboratory, San Jose, CA. He joined IBM in 1996 to work for the Net.Datadevelopment team, where he modified Net.Data V2 to perform flawlessly for allthe 645.9 millions hits of the Nagano Winter Olympic Games Web server. Since1998, he has been involved in DB2 UDB Stored Procedures enhancements.Since 1999, he has been working with Toronto teams on SQL Proceduresimplementation on DB2 UDB distributed platform version 6.1 and version 7.He has 15 years of experience in different fields such as client/server projectmanagement and application development, high performance Web development,and security software (smart cards).

Debra Eaton is a Field Technology Sales Specialist working at the IBM SoftwareMigration Project Office in Chicago, IL, USA. She has 10 years of experience in theapplication development field. She has worked at IBM for 10 years. Her areas ofexpertise include database management and application development. She haswritten extensively on migrating from non-DB2 databases to DB2 databases.

© Copyright IBM Corp. 1999 xi

Page 14: Store Procedure

Mark Leung is a systems specialist in Australia. He has 11 years of experience inthe OS/390 field, and has worked at IBM for 11 years. His areas of expertiseinclude application performance testing and DB2 connectivity. He is also aco-author of the redbook, Getting Started with DB2 Stored Procedures,SG24-4693.

Ricardo Darriba Macedo is a Senior DB2 Product Specialist, working at the IBMSoftware Business Unit, in Rio de Janeiro, Brazil. He joined IBM in 1987, andsince then has been responsible for supporting customers in the database andapplication development areas. Ricardo has helped implement DB2 for manylarge customers in Brazil. He is also a co-author of the redbooks Getting Startedwith DB2 Stored Procedures, SG24-4693 and DB2 DRDA Supports TCP/IP,SG24-2212.

Ling Tay is DB2 technical support in Australia. She has 6 years of experience inDB2, mainly working on the OS/390 platform. Her areas of expertise are inapplication development, as well as DB2 system and application tuning.

Maria Sueli Almeida is a Certified I/T Specialist - Systems Enterprise Data, andis currently a DB2 for OS/390 and Distributed Relational Database System(DRDS) specialist at the International Technical Support Organization, San JoseCenter. Before joining the ITSO in 1998, Maria Sueli worked at IBM Brazilassisting customers and IBM technical professionals on DB2, data sharing,database design, performance, and DRDA connectivity.

Jarek Miszczyk is an international Technical Support Organization specialist forthe AS/400 system at the International Technical Support Organization,Rochester Center. He writes extensively and teaches IBM classes worldwide onall areas of AS/400 database. Before joining the ITSO, he worked in IBM Polandas a Systems Engineer and AS/400 Sales Specialist. He has over 10 yearsexperience in the computer field and his areas of expertise include cross-platformdatabase programming, SQL, and object-oriented (OO) programming.

Thanks to the following people for their invaluable contributions to this project:

Bob CarrThomas EngMarion FarberGerry FisherGreg KimSusan MalaikaRick MandelBruce McAlisterClaire McFeelyJessica MignoneKatherine A MorganConnie NelinEugene PhuMarichu ScanlonJudy TobiasRonald TruebloodDirk Wollscheid

IBM Santa Teresa Laboratory

xii Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 15: Store Procedure

Gustavo ArocenaSerge BoivinJudy ChanSerge RielauDan Scott

IBM Toronto Laboratory

Mark AndersonKathy Passe

IBM Rochester

Luca Montini

IBM Italy

Paolo BruniJoerg Reinschmidt

IBM International Technical Support Organization, San Jose Center

Comments welcome

Your comments are important to us!

We want our redbooks to be as helpful as possible. Please send us yourcomments about this or other redbooks in one of the following ways:

• Fax the evaluation form found in “ITSO redbook evaluation” on page 237 to thefax number shown on the form.

• Use the online evaluation form found at http://www.redbooks.ibm.com/

• Send your comments in an Internet note to [email protected]

xiii

Page 16: Store Procedure

xiv Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 17: Store Procedure

Chapter 1. Introduction

In this chapter we discuss the evolution of DB2 cross-platform stored proceduressupport, leading up to the delivery of these two new features: SQL Procedureslanguage and the Stored Procedure Builder — which are the main content of thisredbook.

1.1 DB2 stored procedures — evolution

Stored procedures are user-written programs that are stored at the databaseserver and can be invoked by client applications using SQL statements.

Stored procedures are predefined processes that execute the DB2 server side ofapplications. They can be called locally, on the same system where theapplication runs, or remotely from a different system. The SQL CALL statement isused to invoke a stored procedure. A stored procedure can send and/or receiveparameters from the calling program.

The main goal of the stored procedure is the reduction of network message flowbetween the requester (the application) and the data server (DB2) in a distributedenvironment. Another usage of stored procedures is to have functions callablefrom any application on any platform.

Your programming productivity can be improved using stored procedures whenyou develop client/server applications. Stored procedures are the easiest way toperform a remote call and to distribute the logic of an application program.

Using stored procedures gives two main advantages to Information Technologydepartments:

• The application development department needs to maintain only one source ofeach function, even if applications calling the functions are executed in adifferent environment, such as transactional, distributed, batch, or distributedaccess. Source languages can be mixed between the calling application andthe stored procedures, which permits the applications designer to chose theright language at the right place.

• Management rules are enforced by the centralization and uniqueness offunction using stored procedures. In case of new application development, thedeveloper can call stored procedures already developed easily without theburden of integrating these functions into the new source.

Since the stored procedure support by the DB2 family has been available, it hasbeen enhanced to meet the pace of our customers and business. One of the mostimportant enhancements is the support for a new stored procedure programminglanguage: SQL Procedures. This support allows SQL-only stored proceduresbased on the ISO/ANSI standard SQL/PSM. This makes it possible to port thesame stored procedure to any member of the DB2 family. It also simplifies theprocess of migrating stored procedures between other DBMSs and the DB2family.

© Copyright IBM Corp. 1999 1

Page 18: Store Procedure

The implementation of SQL stored procedures is based on the SQL standard,and supports constructs that are common to most programming languages. Thissupport has been available on DB2 UDB for AS/400 for more than one year, andnow has been deployed for other members of the DB2 family, which will becovered in this book.

This is part of what has been known as SQL 3, and will shortly be called SQL 99 as itbecomes a formal international standard. DB2 has adopted this SQL Procedureslanguage from the SQL standard. We believe that customers will find value in using astandard compliant stored procedures language rather than proprietary storedprocedures languages invented by other database vendors.

It is important to emphasize that the Database Language SQL - Part 4:Persistent Stored Modules of ISO/IEC 9075 specifies the syntax and semantics ofa database language for declaring and maintaining persistent database languageroutines in SQL-server modules. The scope of the current implementation islimited to SQL Procedures and does not include support for SQL functions andFeature P01, "Stored Modules". See 2.4, “Current implementation of SQLProcedures language” on page 17.

The following sections describe the evolution of the stored procedure support bythe DB2 family.

DB2 for OS/390Stored procedures support was introduced in DB2 for OS/390, Version 4.In this first deployment, stored procedures support was focused on applicationprogramming; for example:

• Improving the application security

• Sensitive business logic run on DB2 server

• End users do not need to have table privileges

• Improving application maintenance

• Business logic is centralized

• Online changes to application code

• Client systems not sensitive to underlying tables

• Good integration with desktop tools

• Improving performance

In DB2 for OS/390 Version 5, stored procedures take advantage of the DRDArelated enhancements introduced in this version of DB2, such as: native TCP/IPsupport, which improves the connectivity for workstation users; direct connectionto DB2 for Windows through DB2 Connect for Windows; and many otherperformance improvements. From the stored procedures point of view, the mainenhancements in this version were:

• Returning one or more query result sets

• Multiple DB2 stored procedure address spaces, managed by OS/390Workload Manager (WLM)

• Ability to invoke utilities from a stored procedure, which means you can invokeutilities from an application that uses the SQL CALL statement

2 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 19: Store Procedure

• Support to IMS Open Database Access (ODBA), which means that a DB2stored procedure can directly connect to IMS DBCTL and access IMS data.

DB2 for OS/390 Version 6 deploys considerable enhancements for storedprocedures, such as:

• SQL capability

• CREATE and ALTER SQL statements and enhancements to the DROPstatement for creating, modifying, and deleting stored procedure definitions

• GRANT and REVOKE SQL statements to manage execution privileges forstored procedures

• CURRENT PATH special register and PATH bind option to implicitly qualifystored procedures names in CALL statements

• Improved data transfer, allowing the DRDA server to send multiple DRDAquery blocks

• Support for nested calls for stored procedures, so a stored procedure can callanother stored procedure

• CALL SQL statement embedded in application programs or dynamicallyinvoked from IBM’s ODBC and CLI drivers

• Support for new data types on CALL SQL statement

DB2 for UNIX, Windows, and OS/2The history of DB2 on the PC and UNIX platforms starts with DB2 CommonServer Version 2, then DB2 Universal Database Version 5, and then DB2Universal Database Version 6. The following paragraphs describe thedevelopment of stored procedures for DB2 Universal Database Version 6.

Below is a list of the stored procedures features supported in DB2 CommonServer, Version 2:

• The external stored procedure programming technique can be used fordatabase manager applications running in a client/server environment.

• Stored procedures invoked through DB2 CLI provide the capability to returnone or more result sets to the client applications.

• The stored procedure must be written in one of the supported languages(C, C++, COBOL, Fortran, REXX) for that database server.

• A special table, DB2CLI.PROCEDURES (a pseudo-catalog table), which isdefined by DB2, lists and describes the available stored procedures, alongwith the associated parameters of those stored procedures.

• Stored procedures stored at the location of the database are invoked from theclient application via the SQL CALL statement.

• The SQL CALL statement can accept a series of host variables or an SQLDAstructure.

• The SQL_API_FN macro is required when you write stored procedures.

• The client procedure should set the indicator for output-only SQLVARs to -1.

• The server procedure should set the indicator for input-only SQLVARs to -128.

Introduction 3

Page 20: Store Procedure

Below is a list of the stored procedures features supported in DB2 UniversalDatabase, Version 5 (see DB2 UDB Version 5 Embedded SQL ProgrammingGuide, S10J-8158):

• The external stored procedure programming technique can be used fordatabase manager applications running in a client/server environment.

• Stored procedures invoked through DB2 CLI provide the capability to returnone or more result sets to the client applications.

• The stored procedure must be written in one of the supported languages(C, C++, Java, COBOL, Fortran, REXX) for that database server.

• When creating a stored procedure in the Java language, the CREATEPROCEDURE statement is used to register the procedure to the systemcatalog table SYSCAT.PROCEDURES.

• The SYSCAT.PROCEDURES table is defined by DB2, and it lists anddescribes available stored procedures, along with the associated parametersof those stored procedures.

• Stored procedures stored at the location of the database are invoked from theclient application via the SQL CALL statement.

• The SQL CALL statement can accept a series of host variables or an SQLDAstructure.

• The SQL_API_FN macro is required when you write stored procedures.

• The client procedure should set the indicator for output-only SQLVARs to -1.

• The server procedure should set the indicator for input-only SQLVARs to -128.

Below is a list of the stored procedures features supported in DB2 UniversalDatabase, Version 6 (see DB2 UDB Version 6 Application Development GuideEmbedded SQL, SC09-2845):

• The external stored procedure and SQL stored procedure programmingtechniques can be used for database manager applications running in aclient/server environment.

• Stored procedures invoked through DB2 CLI, ODBC, JDBC and SQLJ clientsprovide the capability to return one or more result sets to the clientapplications.

• The stored procedure must be written in one of the supported languages(C, C++, Java, COBOL, Fortran, REXX) for that database server.

• Stored procedures stored at the location of the database are invoked from theclient application via the SQL CALL statement.

• The parameter style with which you register the stored procedure in thedatabase manager with the CREATE PROCEDURE statement determineshow the stored procedure receives data from the client application. Theparameter styles are GENERAL, GENERAL WITH NULLS, JAVA, DB2SQL,DB2DARI and DB2GENERAL.

• For LANGUAGE C stored procedures with a PARAMETER TYPE ofGENERAL, GENERAL WITHNULLS, or DB2SQL, you have the option ofwriting your stored procedure to accept parameters like a main function in aC program (MAIN) or like a subroutine (SUB).

4 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 21: Store Procedure

• You must declare every parameter passed from a client application to thestored procedure, and from the stored procedure back to the client application,as either an IN, OUT, or INOUT parameter.

• For Fortran or REXX stored procedures, you must write the stored procedureas a DB2DARI stored procedure.

• The SQL Procedures language is used to create the SQL stored procedureCREATE PROCEDURE statement with a procedure body.

• The two ways to create an SQL stored procedure are to use the IBM DB2Stored Procedure Builder or to write a CREATE PROCEDURE statement forthe SQL stored procedure manually.

• The SQL CALL statement can accept a series of host variables or an SQLDAstructure.

• The SQL_API_FN macro is required when you write C/C++ stored procedures.

• The CREATE PROCEDURE statement is used to register the procedure to thesystem catalog table SYSCAT.PROCEDURES.

• A SYSCAT.PROCEDURES table, is defined by DB2, and lists and describesavailable stored procedures, along with the associated parameters of thosestored procedures.

• The C/C++ client procedure should set the indicator for output-only SQLVARsto -1.

• The C/C++ parameter style DB2DARI server procedure should set theindicator for input-only to -128.

DB2 UDB for AS/400From the AS/400 point of view, there are two ways to implement storedprocedures:

• External stored procedures

When stored procedure support was delivered in V3R1, the SQL standards forprocedural extensions were still unclear and not well defined. Thus, DB2 forAS/400 first delivered support for external stored procedures. An externalstored procedure can be written in any high level language available on theAS/400 platform, including CLI and REXX. This approach gives you theflexibility to use a programming language you are most comfortable with. Theexternal stored procedure may contain SQL statements (embedded SQL), or itmay perform only native access to the database. The following steps illustratethe typical scenario for using external stored procedure in your client SQLapplication:

• Code your business logic in the high level language of your choice.

• Define the store procedure through the DECLARE PROCEDURE orCREATE PROCEDURE SQL statement.

• Invoke the stored procedure using the SQL CALL statement, passingparameters.

• Check the completion status of the stored procedure.

Introduction 5

Page 22: Store Procedure

• SQL stored procedures:

In the years that have passed since V3R1, the SQL standards have matured,and now include an entire addendum defining the procedural languageextensions for SQL. Starting with V4R2, the AS/400 programmers have theoption of writing an entire program in SQL. Some SQL programmers new tothe AS/400, were not comfortable learning how to use AS/400 compilers andhow to embed SQL in a C program. The SQL procedural language gives thema way to produce DB2 for AS/400 stored procedures without having to learnthese system-specific operations.

The SQL procedural language also makes it easier to port stored proceduresfrom other databases to the AS/400. For example, Oracle and Microsoft havecreated their own proprietary languages (PL/SQL and T/SQL) for SQL storedprocedures.

The SQL procedural language should not be considered a new language forthe AS/400 like RPG or COBOL. Stored Procedures can be leveraged themost in network computing environments where processing is dividedbetween the client and the server. They provide an easy way to packagerelated database operations into a single object to reduce network traffic.

To create a SQL stored procedure on the AS/400 system you can use eithernative interface using the RUNSQLSTM command or the GUI interfaceprovided by the Operations Navigator.

1.2 Cross-platform support of stored procedures written entirely in SQL

With SQL Procedures, you can now write stored procedures consisting entirely ofSQL statements. SQL Procedures functionality has been supported by DB2 UDBfor AS/400 for more than one year, and support has recently been rolled outacross all members of the DB2 Universal Database Family, as well as to DB2Server for OS/390 Version 5.

SQL Procedures functionality provides you the benefit of writing storedprocedures in a standard, portable language. An SQL stored procedure consistsof a CREATE PROCEDURE statement to define the procedure and a single orcompound SQL statement. A compound SQL statement can include declarations(of variables, conditions, cursors, and handlers), flow control, assignmentstatements, and traditional SQL for defining and manipulating relational data.These extensions provide a procedural language for writing stored procedures,and they are consistent with the Persistent Stored Modules (PSM) portion of theSQL standard.

1.3 Building DB2 stored procedures from your workstation

The IBM DB2 Stored Procedure Builder (SPB) provides an easy-to-usedevelopment environment for creating, installing, and testing stored procedures.With the DB2 SPB, you can focus on creating your stored procedure logic ratherthan on the details of registering, building, and installing stored procedures on aDB2 server.

With DB2 Stored Procedure Builder, you can develop stored procedures on oneoperating system, such as Windows NT, Windows 98, or Windows 95, and deploy iton any DB2 platform on any operating system that supports DB2, such as DB2 for

6 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 23: Store Procedure

AIX, DB2 for Sun Solaris, or DB2 for OS/390.

The Stored Procedure Builder allows you to create stored procedures in Java(dynamic SQL through JDBC support, or Static SQL through SQLJ support) andthe SQL Procedures language. Creating stored procedures in Java and entirely inSQL produces stored procedures that are highly portable among operatingsystems.

Using the Stored Procedure Builder, you can perform a variety of tasks that areassociated with stored procedures, such as:

• Viewing existing stored procedures

• Modifying existing stored procedures

• Creating new stored procedures

• Running existing stored procedures

• Copying and pasting stored procedures across connections

• One-step building of stored procedures on target databases

• Customizing the settings to enable remote debugging of installed storedprocedures

1.4 Concepts and terminology

This section describes the terms and concepts used during the development ofthis book.

Stored procedure, or external stored procedureThis is a program developed in embedded SQL or in CLI, using host programminglanguage such as C, C++, COBOL, Fortran, Java or REXX. The executable aswell as the source code is stored as files in the file system.

SQL stored procedureThis is a program developed using the SQL Procedure language, according to thestandard definition of SQL3. SQL stored procedures programs are made of acollections of SQL statements and control-of-flow language written by programdevelopers. They are stored at the database and can be invoked by clientapplications.

SQL functionThis is a program for user-defined-function, developed entirely using the SQLProcedure language. The SQL function is not supported by this first delivery ofSQL Procedure language support on DB2 across platforms.

SQL/PSMPSM means Persistent Stored Module. It is the SQL3 definition of a procedurallanguage for relational databases.

The following chapters of this book cover in detail the SPB and SQL Procedureslanguage support across platforms.

Introduction 7

Page 24: Store Procedure

8 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 25: Store Procedure

Chapter 2. The SQL Procedures language

The SQL Procedures language is a common programming language across theDB2 family for writing stored procedures. The use of SQL Procedures provides tocustomers the benefit of writing their stored procedures in a standard andportable language. This chapter describes in detail the SQL Proceduresprogramming language.

Any differences in current releases are due to differences in how we roll out featuresfor a given platform. However, DB2 will be continuing to enhance the SQLProcedures language on all platforms and reduce any current platform differences.

2.1 What is it?

The SQL Procedures language is based on SQL extensions as defined by theSQL/PSM (Persistent Stored Modules) standard. SQL/PSM (an ISO/ANSIstandard for SQL3) is a high level language — similar to other RDBMS languagessuch as Transact SQL (T/SQL) from Sybase, and Procedural Language (PL/SQL)from Oracle — that extends SQL to procedural support.

The ISO/ANSI SQL3 is an open solution for SQL among database managementsystem vendors that support the SQL ISO/ANSI standard.

Modules are collections of SQL stored procedure and function declarations thatare stored “persistently” inside the database (more likely, inside the SQL systemfor a possible dependency checking between the procedures and functions andthe database objects). Inside SQL/PSM modules, one can specify the characterset, the default schema name to be prepended to unqualified names in SQLstatements in the module, the search path within schemas, and temporary tabledeclarations.

Following is an example of a CREATE MODULE statement:

CREATE MODULE mymoduleCHARACTER SET "latin-1"SCHEMA MYSCHEMAPATH ’SCHEMA1,SCHEMA2’create procedure mySQLprocedure1(out parm1 integer)

beginSET parm1 = select max(id) from mytable;

end;create function mySQLfunction1 returns integer

beginreturn( select max(id) from mytable);

end;END MODULE;

Where:

• "latin-1" is the character set.

• MYSCHEMA is a default schema name to be prepended to unqualified names inSQL statements in the module.

• ’SCHEMA1,SCHEMA2’ is the search path within schemas SCHEMA1 andSCHEMA2.

© Copyright IBM Corp. 1999 9

Page 26: Store Procedure

In the first releases of DB2 UDB SQL Procedures support, SQL/PSM modulesand SQL functions are not implemented. Only SQL stored procedures areimplemented.

A DB2 UDB SQL stored procedure can be created without being part of a module.The SQL stored procedure source code, that is the CREATE PROCEDUREstatement, is stored in the database after a successful compilation andregistration of the SQL stored procedure in the appropriate DB2 tables (seechapter for specific platform).

As explained later, SQL stored procedures are different from external storedprocedures that are written in a third generation language like C, COBOL, orJava.

Local client as well as remote client applications, connected to the DB2 serverthrough network stacks (for example, TCP/IP), can invoke an SQL storedprocedure by executing the SQL CALL statement. The SQL CALL statement isalso part of ISO/ANSI SQL3.

The ability to write stored procedures greatly enhances the power, efficiency, andflexibility of SQL. The client program can pass parameters to the SQL storedprocedure and receive parameters from it, as well as result sets. The SQL CALLstatement can be executed as either static or dynamic SQL. Parameters in theCALL statement, including the stored procedure name, can be supplied atexecution time. The SQL CALL statement can be used to invoke dynamically anySQL stored procedure supported by DB2.

The following DB2 servers currently support SQL stored procedures:

• DB2 UDB for UNIX, Windows, and OS/2

• DB2 UDB for AS/400

• DB2 UDB for OS/390

2.2 Planning to use the SQL Procedures language

This section contains information about planning for the use of DB2 storedprocedures, and provides specific information to help you develop storedprocedures using the SQL Procedures language. For more information aboutspecific hardware and software requirements, see the chapter in this book thatcovers the specific platform you are planning to use.

2.2.1 Why use it?This section describe the benefits of using SQL stored procedures.

Consistency with the dataIn theory, SQL stored procedures are fully SQL, which means that they arewritten using only SQL statements. Like other SQL objects, and because they arepart of module statements, they are always stored in the database system inwhich they are used and for which they were developed. Storing SQL storedprocedures within the database system allows dependencies to be checkedbetween the SQL schema objects (tables, views, and so on) and the procedure,as soon as a manipulation is done (like dropping or altering an object). An SQL

10 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 27: Store Procedure

stored procedure must not get out of sync with the SQL schema objects it workswith.

On the other hand, this out of sync status can happen with external storedprocedures, where the executable is stored at the system level, away from thedatabase data management system. The backup and restore operations could bedone out of sync with the backup and restore of the data, leading toinconsistencies in the processing.

The actual DB2 UDB support for SQL Procedure translates an SQL storedprocedure into an external stored procedure, allowing potential inconsistencies.However, the source code of each stored procedure is stored inside the databaseitself, making possible to recreate the correct executable of the procedure.

Modular programmingAn SQL stored procedure can be created once and then stored in the database.Any userid with the necessary authorization can access the stored procedurethrough the CALL SQL statement. For instance, an SQL stored procedure couldbe created or modified by a specialist in SQL stored procedure languageprogramming, and be called by client programs developed by other programmers.This allows the DBA to control the development of the business logic at theserver, which is a very sensitive area.

Faster executionIf an operation requires a large number of SQL statements or is performedrepetitively, an SQL stored procedure can be faster than an SQL query sentdirectly from a client program, because it may be already loaded in memory (orcached) after the first execution.

The benefit of SQL stored procedures is even greater if the client expects to senddynamic SQL to the server. The compilation of the dynamic SQL statements in anSQL stored procedure would be done at the first execution and would stay in theDB2 cache as long as the memory space is not needed.

In addition, the fact that SQL stored procedures are translated to C is anotherperformance advantage.

Network traffic reductionAn operation requiring many SQL statements can be performed through a singleCALL statement that executes the same SQL code inside a procedure, ratherthan sending every individual SQL query over the network. For instance, Figure 1shows what a client application written in C or CLI or any other embedded SQLlanguage has to send and receive through the network to execute two SQLstatements.

Figure 2 shows the same logic embedded in an SQL stored procedure. The clienthas to send one SQL CALL statement to the server. The results sent back are thesame. As you can see, the two SQL statements from Figure 1 are reduced to oneSQL CALL statement.

The savings can be important. The SQL CALL statement is a very short networkmessage. On the contrary, a single SQL statement with many synchronizedqueries could be a few kilobytes long, up to 32k or 64k, depending of the versionof DB2 UDB installed, and this could result in many network messages sent to theserver. The savings are greater if the logic you want to execute requires many

The SQL Procedures language 11

Page 28: Store Procedure

SQL statements or many network messages, like the FETCH operation withcursors. The network transfer time between the client and the server couldbecome longer than the execution of the SQL statement themselves, dependingon network availability.

Figure 1. The usual SQL client, where the logic sends many SQL queries

Figure 2. SQL client using the same logic, but within an SQL stored procedure.

Another point to be considered is that, while the client based query must returnevery row across the network, a stored procedure can return only a subset of therows, or potentially none at all, and can return values derived from subsequentlogic.

Can be used as a security/shield mechanismIt is often useful to shield the data and the tables from developers and databaseusers. This can be done by restricting access to tables to only a few trustedusers, and by granting the right to execute specific stored procedures, developedfor updating, inserting or deleting rows to less trusted users. This can ensure thatapplications cannot execute direct SQL statements against important data, butmust make modifications only through the filter of stored procedures.

These stored procedures can even have more complex logic than just basic SQLstatements. One stored procedure that deletes one customer could also updateother tables related to that customer to keep information for audit or furtherreferences. Referential integrity should be able to do this, but sometimes, it iseasier and faster to use a stored procedure, because depending on the context ofthe modification, different actions will have to be executed. Triggers or referentialintegrity constraints on a table are not context sensitive, because only the data inthe rows are available. There is no possibility to have a specific DELETE,UPDATE or INSERT operation according to the current context of the application.

12 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 29: Store Procedure

For example, for the following SQL statement:

DELETE CUSTOMER WHERE CUSTID=11111

You may want to take one of the following actions:

• Delete this customer, but insert a log record of it in the custlog table for auditlater

• Delete this customer, but keep the statistics in the custstats table until end ofyear

• Delete this customer, but also delete corresponding rows in custlog andcuststats tables

Note: The custlog and custstats tables mentioned here are tables you created foryour application design.

The delete trigger on the customer table will not be able to choose one of thesedifferent actions because it has to be generic. When you delete the customer, youcannot specify another action along with the delete SQL statement. A storedprocedure would be able to decide what to do, according to an input parametervalue.

Another example is shielding tables from users. Figure 3 shows that thedeveloper shielded the tables A, B and C from the client applications Cl1, Cl2,

Cl3 and Cl4 by inserting a layer of SQL stored procedures SP1, SP2 and SP3.

These SQL stored procedures can execute complex SQL queries like insert,update and delete on one or more tables. When called, SP1 will modify only tableA, SP2 will modify table A and table C, and SP3 will modify table B and table C.

Figure 3. An example of shielding tables from users

2.2.2 When to use them?In general, SQL stored procedures can be used as soon as a client applicationneeds to send dynamic SQL statements, or multiple SQL operations, like FETCH,to the server. Grouping the same functional SQL statements in an SQL storedprocedure allows performance and network bandwidth improvement. It alsosimplifies programming, improves maintainability, and facilitates deployment ofapplications.

Table A Table B Table C

SP3SP2SP1

Cl 1 Cl 2 Cl 3 Cl 4

DB

2U

DB

Ser

ver

LO

GIC

DA

TA

The SQL Procedures language 13

Page 30: Store Procedure

The following sections describe in more detail why SQL stored procedures arereally useful:

• Easier and faster to program than external stored procedure

SQL stored procedures are very similar to SQL. The control-flow statementsare really simple, and the programmer does not need to understand C orCOBOL.

SQL stored procedures are the perfect solution for business logic, since theycan be totally developed with SQL statements and control-flow logic. That is,you do not need to access any other external resource besides the RDBMS.They are fast to develop and maintain.

• No use of specific system services or resources

If the business logic needs to access system services or external resources,or call other external programs, SQL stored procedures may not beapplicable. In fact, there is no possibility yet, in the SQL/PSM standard, to calla shared library, execute a system command, or send e-mail.

For the time being, the only solution is to use external stored procedureswritten in C or COBOL. For instance, a stored procedure that has to send ane-mail to the credit manager every time a credit limit is exceeded, or execute asystem command when a threshold is reached, has to be an external storedprocedure developed in C or COBOL.

Note: This is true except for the Windows platforms. DB2 UDB for Windowsallows OLE stored procedures which can invoke operating system and otherplatform capabilities like email through the use of OLE services. Refer to theDB2 UDB for Windows manuals for more details on use of OLE automation. Soyou can use more than C or COBOL stored procedures when you need systemservices and are running on Windows.

• No vital performance needed

Due to the actual implementation of SQL stored procedures, the executionperformance may not be as fast as an optimized external stored procedurewritten in C or COBOL. Although the difference is very small for most of thebusiness logic functionality, some applications may need the extra timedifference that can be gained only by using an optimized procedureprogrammed in C or COBOL language.

How do we choose, then? Usually, only a few parts of a company businesslogic application needs real performance. The designer of the applicationshould find the right compromise between development time andmaintainability versus execution performance.

• Lots of business logic

The more business logic you have, the more you will save in development,maintenance, and execution time. The modularity allowed by stored

SQL stored procedures are not interpreted. They are translated to C, so thebuild process has more steps, but the resulting procedure is compiled. Thepreprocessors and translators also add optimization.

Important:

14 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 31: Store Procedure

procedures is certainly a gain in maintenance, especially when the clientprograms are developed in different languages.

Changing some business logic does not mean changing all the differentCOBOL and C or Visual Basic (VB) clients that were executing these SQLstatements. Only the stored procedure involved in this business logic needs tobe changed, assuming that the signature — which means the list ofparameters and types of the stored procedure — is still the same.

• Highly distributed application (deployment)

Deployment of clients having business logic embedded is hard to maintain.Every time the business logic change or an error is fixed, all the clients have tobe updated again. This can lead to out of sync clients accessing good data inthe wrong way.

However, fixing one stored procedure fixes all the clients at once. Themaintenance is faster, and problems arise less often.

• What partition of business logic should reside on the server?

Lots of documents have been written on this subject, and not everybodyagrees on the conclusions. But let us consider the two major solutions that areseen most often.

Usually, the two rules of 80% on client 20% and on server, or 20% on clientand 80% on server, could apply for most applications, depending on the levelof risk the developers and company expect.

• 80%-20% client to server ratio:

This corresponds to applications that do not want to rely too heavily onspecific stored procedure languages. The 20% consists mainly of SQLstatements. This is typically the case for most independent softwarevendors (ISVs) that want to deal with a minimum of different storedprocedures languages (T/SQL or PL/SQL ,or even DB2 SQL Procedureslanguage) because their programs will have to be ported on differentRDBMSs. They are usually constrained to a subset of SQL, portable acrossall the RDBMSs. The counterpart of this solution is that this kind ofapplication cannot use the full possibilities of an RDBMS, and wouldusually not perform as well as a 20%-80% solution (because of using morenetwork bandwidth, for instance).

• 20%-80% client to server ratio:

This kind of application is tuned to access business logic on the server,mainly as stored procedures. This application will rely heavily on RDBMSfeatures, and should hopefully be more efficient than an 80%-20% solutio,nby optimizing bandwidth, deployment, and development time. This istypically the kind of application developed by a company for itself. Thedrawback of this type of application is that the company relies on oneRDBMS, which could be troublesome for future migrations.

Of course, all kind of partitions can be seen, and the company’s final choicewill depend only on the evaluation between level of risk/RDBMS dependencyversus application performance/savings during the development andmaintenance phase.

The SQL Procedures language 15

Page 32: Store Procedure

2.3 Comparing SQL stored procedures and external stored procedures

External stored procedures are stored procedures developed using hostprogramming language such as C, C++, COBOL, Fortran, Java, and REXX. Thiswas the original way to develop stored procedures with DB2, which means thatstored procedures could not be written totally in SQL, on all platforms (except forDB2 UDB on AS/400). Such stored procedures are stored in files on the machinewhere the database server is located and not in the database itself. That is whythey are named external stored procedures.

2.3.1 DevelopmentSQL stored procedures are stored procedures written in the SQL Proceduresprogramming language. An SQL stored procedure is developed totally in SQL,and its source code is stored in the database, so it can be executed directly withinthe DBMS environment.

2.3.1.1 Lower the development costExternal stored procedures are developed in a procedural language such as C,Java or COBOL. Using programming languages for database programmingrequires much experience and a deep understanding of how the SQL data typesand database engine features are mapped to the host language.

For example, in the C language, an SQL VARCHAR variable called myvar wouldhave to be represented as a structure like the following:

struct {

short len;char data[31];} myvar;

You would represent the same VARCHAR variable like this, using SQLProcedures language:

DECLARE myvar VARCHAR;

As you can see, it is simpler in SQL Procedures language to declare variables ofan SQL type.

The conceptual differences between SQL and host languages adds complexity tothe programming of external stored procedures, making them longer in thenumber of lines, with more possibilities for mistakes, and making them moredifficult to debug. Programmers of external stored procedures must be welltrained database SQL programmers as well as having extensive experienceworking with third generation languages.

On the other hand, SQL Procedures rely on SQL. Variable handling is fully SQL(no structures to deal with VARCHAR) and the procedural extensions use aneasy common syntax very close to BASIC or PASCAL. The benefit ofprogramming with SQL Procedures language is immediate. Once you know SQL,you can learn the SQL Procedures language in a matter of hours. You do nothave to deal with obscure representation and manipulation of your variables, butcan just use them directly.

16 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 33: Store Procedure

For example, assuming that two VARCHAR variables v1 and v2 are declared, thecode in SQL Procedures language is as follows to assign v2 to v1:

/* in SQL Procedures language*/SET v1 = v2;

The same code in C is as follows:

/* in C */memcpy(v1.data, v2.data, v2.len);v1.len=v2.len;

As you can see, you need to know the internal representation of a VARCHARvariable in C, to be able to copy it into a C program.

Another advantage of using SQL Procedures is that you can develop themanywhere, as soon as you have a DB2 UDB connection ready. The source codeis stored in the database, allowing the programmer to fetch it back formodification. Unlike external stored procedures, there is no need to access thefile system. This simplifies the development by focusing only on the DB2 UDBfunctionality, that is, programmers do not have to learn system tools such as filetransfer protocols, system specific editors or compiler options. They just learnSQL and its procedural extensions.

The Stored Procedure Builder, provided with DB2 UDB, relies on this feature,allowing the same easy, graphical interface to build SQL or Java storedprocedures on any DB2 UDB platforms with nothing more needed than a DB2UDB connection. (See Chapter 3, “The DB2 Stored Procedure Builder” on page57 for details.)

2.3.1.2 Leverage programming skillsBy using SQL Procedures, you leverage the programming skills needed in yourcompany, lowering the cost of development of application. For example, the sameperson that knows SQL can also be the programmer.

It also makes things easier for porting, maintaining the source code, anddeployment (same code everywhere). This can be an important saving forcompanies that have many programmers.

2.3.2 RuntimeCalling an SQL stored procedure is no different than calling an external storedprocedure. The same SQL CALL statement works for both of them.

Because the SQL Procedures language is higher level, it may have to do moretasks for the programmer (like checking for exception condition after every SQLstored procedure statement). Also, it may be slower to execute than the usual Cor COBOL stored procedure written by a specialist or expert (which may bypasssome error checking). But the cost performance is justified because of thesavings that can be obtained during development and maintenance.

2.4 Current implementation of SQL Procedures language

The actual choice made by IBM is to translate an SQL Procedures languageprogram into an external C stored procedure. This is done under-the-covers bythe engine, and the programmer does not need to understand how it is done. The

The SQL Procedures language 17

Page 34: Store Procedure

only thing needed is a C or C++ compiler to be installed along with the DB2 UDBserver on the server machine.

2.4.1 How does this work in general?Once you send the SQL stored procedure source code (the CREATEPROCEDURE statement) to the DB2 UDB engine from the Stored ProcedureBuilder or from the DB2 UDB command line, the DB2 UDB engine processes it,creates a C file with embedded SQL, compiles it and installs it in the right placefor its first execution. The implementation is slightly different on OS/390, ascompared to AS/400 and distributed platforms due to platform differences.For details on each platform, see Chapter 4, “SQL Procedures for DB2 UDB forOS/390” on page 109; Chapter 5, “SQL Procedures for DB2 UDB for UNIX,Windows, OS/2” on page 145; and Chapter 6, “SQL Procedures for DB2 UDB forAS/400” on page 169.

Note: When you build your SQL stored procedures with the DB2 Stored ProcedureBuilder, of course, all the application developer needs to do is press the "Build"button. All the work is done for you, and any differences in processing betweenplatforms is handled for you. We recommend that approach for building storedprocedures in the SQL Procedures language.

2.4.1.1 Statements supportedThe Database Language SQL - Part 4: Persistent Stored Modules of ISO/IEC9075 specifies the syntax and semantics of a database language for declaringand maintaining persistent database language routines in SQL-server modules.The scope of the current implementation is limited to SQL stored procedures anddoes not include support for SQL functions and Feature P01, "Stored Modules".The following stored database language capabilities are supported:

• Statements to direct flow control:

• CASE statement

• IF statement

• ITERATE statement

• FOR statement

• LEAVE statement

• LOOP statement

• REPEAT statement

• WHILE statement

• Compound statement:

• BEGIN

• END

• Assignment statement:

• SET

• Specification of condition handlers:

• DECLARE.....HANDLER.....FOR.....

• DECLARE.....CONDITION.....

18 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 35: Store Procedure

• Specification of statements to signal and resignal conditions:

• SIGNAL

• RESIGNAL (on Workstation only)

• Declaration of SQL local variables

• DECLARE.....DEFAULT.....

• SQL statements

• Dynamic SQL (Extension to the SQL/PSM language standard)

• PREPARE

• EXECUTE

• EXECUTE IMMEDIATE

2.4.2 Declaring SQL local variablesTo store data that you use only within an SQL stored procedure, you can declareSQL local variables. The SQL local variables can have the same data types andlengths as DB2 table columns. The general form of an SQL variable declarationis:

DECLARE SQL-variable-name data-type;

DB2 folds all SQL variable names to uppercase. Thus, you cannot declare twoSQL variables named varx and VARX. You cannot declare an SQL variable with aname that is the same as a parameter name or an SQL reserved word. However,you can declare an SQL variable name that is the same as a DB2 column name.

If a name in an SQL statement can be either a column name or an SQL variablename, DB2 UDB will verify first if it is a column name, and then verify if it is a SQLvariable name. You can also specify which scope, that is, the compoundstatement label the variable was declared into, by qualifying the variable namewith the scope name. This is useful for nested scopes, where it may be needed torefer to variables declared in a "higher" scope, or to avoid conflicts betweenvariables and column names in SQL statements.

In the SQL Procedures language there are no host variables; all variables areconsidered SQL variables. So, you cannot put colons in front of variables in theSQL Procedures language.

Another important remark about SQL variables declaration is the order that theyare declared. All variable and condition declarations must precede handlerdeclarations.

Below is an example of declarations for the most common data type supported.

CREATE PROCEDURE p1()LANGUAGE SQLBEGINdeclare c1 integer;declare c2 CHAR(30);declare c3 VARCHAR(30);declare c31 VARCHAR(30);declare c34 LONG VARCHAR default'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxa';

The SQL Procedures language 19

Page 36: Store Procedure

declarecdate DATE default '03/01/1999';declare ctime TIME default '11:11:22';declare cstamp TIMESTAMP default '1990-01-01-12.01.00.000000';declare c4 REAL default 12345.456;declare c5 DECIMAL(9,2) default 12345.456 ;declare c6 BIGINT default 1234567890123456789;declare LOC1 result_set_locator varying;

SET c1 = (select count(*) from employee);SET c2 = (select max(empno) from employee);SET c3 = (select min(empno) from employee);insert into result(proc,res)values ( 'exec P1','C1='||CHAR(C1)||' C2='||C2||' C3='||C3);insert into result(proc,res)values ( 'exec P1','date='|| CHAR(cdate));insert into result(proc,res)values ( 'exec P1','time='|| CHAR(ctime));insert into result(proc,res)values ( 'exec P1','timestamp='|| CHAR(cstamp));insert into result(proc,res)values ( 'exec P1','REAL='|| CHAR(c4));insert into result(proc,res)values ( 'exec P1','decimal(9,2)='|| CHAR(c5));insert into result(proc,res)values ( 'exec P1','LONG VARCHAR='||c34);insert into result(proc,res)values ( 'exec P1','BIG INT='||CHAR(c6));END

2.4.3 Language ElementsThe following sections describe and show examples of each type of statementand language element.

The examples shown assume that a table result is created in the database thatkeeps an execution trace of the SQL stored procedure. The following is the DDLused to create the table result:

create table result ( proc char(22), res varchar(128))

Note that, because the SQL Procedures language is SQL, names (variables,labels, etc.) are not case sensitive.

2.4.3.1 Assignment statementThe assignment statement assigns a value to an output parameter or to an SQLvariable, which is a variable that is defined and used only within a procedurebody.

CREATE PROCEDURE B(OUT var1 INTEGER,OUT var2 INTEGER)LANGUAGE SQL

OS/390 does not have a BIGINT data type, or RESULT SET LOCATOR.

The example shows SET varname = (SELECT ...) - which is not yet supported onOS/390.

Important:

20 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 37: Store Procedure

BEGINSET var1 = 10;SET var2 = (SELECT count(*) FROM customer);

END

2.4.3.2 CASE statementThe CASE statement selects an execution path based on the evaluation of one ormore conditions. This statement is similar to the CASE expression, which isdescribed in the SQL Reference of DB2 UDB, Chapter 3, Language Elements,topic CASE expression.

CREATE PROCEDURE I1(IN var1 CHAR(3) )LANGUAGE SQLBEGINCASE var1

WHEN 'AAA' THENinsert into result(proc,res) values ('exec of I1','AAA found.');

WHEN 'BBB' THENinsert into result(proc,res) values ('exec of I1','BBB found.');

WHEN 'CCC' THENinsert into result(proc,res) values ('exec of I1','CCC found.');

ELSEinsert into result(proc,res) values ('exec of I1','default case

value=' || CHAR(tt) );END CASE;

END

Here is another example of a CASE statement:

CREATE PROCEDURE I6(IN var1 CHAR(3),IN var2 CHAR(3))LANGUAGE SQLBEGIN

CASEWHEN var1='AAA' THEN

INSERT INTO result(proc,res) VALUES ('exec of I6','var1=AAA');WHEN var2=’AAA’ THEN

INSERT INTO result(proc,res) VALUES ('exec of I6','var2=AAA');END CASE;

END

2.4.3.3 IF statementThe IF statement selects an execution path based on the evaluation of acondition.

CREATE PROCEDURE B1(IN v CHAR(1))LANGUAGE SQL

BEGINIF (v >'F') THEN

INSERT into result(proc,res) VALUES ('exec of B1',' v > F v='|| v);ELSEIF (v >'D') THEN

INSERT INTO result(proc,res) VALUES ('exec of B1',' v > D v='|| v);ELSEIF (v >'B') THEN

INSERT INTO result(proc,res) VALUES ('exec of B1',' v > B v=' || v);

The assignment statement: SET var2 = (SELECT count(*) FROM customer);

shown in the example above is not yet supported on the OS/390 platform.

Important:

The SQL Procedures language 21

Page 38: Store Procedure

ELSEIF (v >'A') THENINSERT INTO result(proc,res) VALUES ('exec of B1',' v > A v=' || v);

ELSEINSERT INTO result(proc,res) values ('exec of B1','Else branch

done.');END IF;

END

Here is another example of an IF statement:

CREATE PROCEDURE MM (in PA INTEGER)LANGUAGE SQLBEGIN

IF ( PA in (12,13,10)) THENINSERT INTO result(proc,res) VALUES ('exec of MM',' PA='|| CHAR(PA)

|| ' found in (12,13,10)');ELSE

INSERT INTO result(proc,res) VALUES ('exec of MM',' PA='|| CHAR(PA)|| ' not found in (12,13,10)');

END IF;END

2.4.3.4 LEAVE statementThe LEAVE statement transfers program control out of a loop or a block of code(see statement LEAVE myloop in the sample below). When a LEAVE statementtransfers control out of a compound statement, all open cursors in the compoundstatement, except cursors that are used to return result sets, are closed.

In addition, the LEAVE statement can be used to exit the stored procedure (seestatement LEAVE PP in the sample below).

CREATE PROCEDURE F (IN ASSEMBLY_NUM CHAR(10) )LANGUAGE SQLPP:BEGINDECLARE a INTEGER DEFAULT 0;

myloop:LOOPINSERT INTO result(proc,res) VALUES ( 'proc F', 'LOOP '|| CHAR(a) );IF (a> integer(assembly_num) ) THEN

LEAVE myloop;/* exit the loop */ELSE

SET a = a + assembly_num;IF (a> 1000) ) THEN

LEAVE PP;/* exit the procedure*/END IF;

END IF;END LOOP myloop;

END

2.4.3.5 ITERATE statementThe ITERATE statement causes the flow of control to return to the beginning of alabelled loop.

CREATE PROCEDURE E()LANGUAGE SQLBEGIN

DECLARE zz INTEGER DEFAULT 11;xx1: while ( zz < 5) do

22 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 39: Store Procedure

INSERT INTO result(proc,res) VALUES ('proc E','ascending='||CHAR(zz) );

SET zz = zz +1;ITERATE xx1;INSERT INTO result(proc,res) VALUES ( 'proc E', 'iterate not done=

'||CHAR(zz) );end while;

END

2.4.3.6 FOR statementThe FOR statement executes a group of statements repeatedly. It must beassociated with a query expression and terminates after the group of statementsis executed for every row in the result of query expression.

The FOR statement is a labelled statement. The following example shows FORusage in SQL stored procedures:

DECLARE X INTEGER DEFAULT 0;FOR L1 AS SELECT balance FROM accounts DO

SET X = X + balance;END FOR;

The body of a FOR statement is not allowed to contain a LEAVE statement thatrefers to L1. But cursor columns can be prefixed with the name of the FORstatement L1. This is also valid.

SET X=X+L1.balance.

It is very useful to refer to variables in nested FOR loops that access the sametable, as in this example:

DECLARE X INTEGER DEFAULT 0;FOR L1 AS SELECT balance FROM accounts WHERE DEP > ’C02’ DO

FOR L2 AS SELECT balance FROM accounts WHERE DEP<’D01’ DOSET X = L2.balance + L1.balance;

END FOR;/* do something here with X*/END FOR;

A cursor is implicitly opened at the beginning of execution; closed automaticallyat the end of execution. In the preceding example, a cursor is created for the SQLstatement SELECT balance FROM accounts and for each line of the result setinstruction SET X= L2.balance + L1.balance is executed.

It is also possible to specify a name for the implicit cursor as in the followingexample:

FOR L1 AS curs1 CURSOR FORSELECT * FROM accounts WHERE balance = 0 DO

DELETE FROM accounts WHERE CURRENT OF curs1;END FOR;

The body of a FOR statement is not allowed to contain an OPEN, FETCH, orCLOSE statement that refers to curs1.

The FOR statement is not yet supported on the OS/390 platform.

Important:

The SQL Procedures language 23

Page 40: Store Procedure

2.4.3.7 LOOP statementThe LOOP statement executes a group of statements repeatedly until a LEAVEstatement transfers program control out of the loop. The ITERATE statementcauses the flow of control to return to the beginning of the loop.

CREATE PROCEDURE F (IN ASSEMBLY_NUM CHAR(10) )LANGUAGE SQLBEGINDECLARE a INTEGER DEFAULT 0;

myloop:LOOPINSERT INTO result(proc,res) VALUES ( 'proc F', 'LOOP '|| CHAR(a) );IF (a> integer(assembly_num) ) THEN

LEAVE myloop;ELSE

SET a = a +1;END IF;

END LOOP myloop;END

2.4.3.8 REPEAT statementThe REPEAT statement executes a group of statements until a search conditionis true.Within the group of statement of a REPEAT statement, a LEAVE statementtransfers program control out of the REPEAT and an ITERATE statement causesthe flow of control to return to the beginning of the REPEAT.

CREATE PROCEDURE F (IN ASSEMBLY_NUM CHAR(10) )LANGUAGE SQLBEGIN

DECLARE b INTEGER DEFAULT 0;REPEAT

INSERT INTO result(proc,res) VALUES ('proc F','REPEAT '|| CHAR(b) );SET b = b +1;

UNTIL (b>5)END REPEAT;

END

2.4.3.9 WHILE statementThe WHILE statement repeats the execution of a statement or group ofstatements while a specified condition is true. The LEAVE statement transfersprogram control out of the WHILE. The ITERATE statement causes the flow ofcontrol to return to the beginning of the WHILE.

CREATE PROCEDURE E()LANGUAGE SQLBEGIN

DECLARE aaa char(30);DECLARE zz INTEGER DEFAULT 11;--------------------------------------------------------- THIS WHILE LOOP WILL TEST THE WHILE STATEMENT ITSELF-------------------------------------------------------while ( zz > 0) do

INSERT INTO result(proc,res) VALUES('proc E','descending ='||CHAR(zz));

SET zz = zz -1;end while;---------------------------------------------------- THIS WHILE LOOP WILL TEST THE LEAVE STATEMENT

24 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 41: Store Procedure

--------------------------------------------------xx:while ( zz < 5) do

INSERT INTO result(proc,res) VALUES ('proc E','ascending='||CHAR(zz));

SET zz = zz +1;LEAVE xx;INSERT INTO result(proc,res) VALUES ('proc E','leave not done=

'||CHAR(zz));end while;---------------------------------------------------- THIS WHILE LOOP WILL TEST THE ITERATE STATEMENT--------------------------------------------------SET zz = 0;xx1: while ( zz < 5) do

INSERT INTO result(proc,res) VALUES ('proc E','ascending='||CHAR(zz) );

SET zz = zz +1;ITERATE xx1;INSERT INTO result(proc,res) VALUES ( 'proc E', 'iterate not done=

'||CHAR(zz) );end while;

INSERT INTO result(proc,res) VALUES ( 'proc E', 'end ' );END

2.4.3.10 Dynamic SQL statementsThe dynamic SQL statements, that is, PREPARE, EXECUTE and EXECUTEIMMEDIATE, are allowed in an SQL stored procedure code. The following is anexample of the use of those statements:

CREATE PROCEDURE H1()LANGUAGE SQL

BEGINdeclare stmt varchar(254);declare v1 varchar(20) default 'foofoo';insert into result(proc,res) values('exec H','Start');

SET stmt = 'insert into result (proc,res) values (''exec H'', ''this isthe parameter marker ''||? )';prepare s2 from stmt;execute s2 using v1;

SET stmt = 'create table mytab (c integer) ';execute immediate stmt;set stmt='insert into mytab values ( 1 )';execute immediate stmt;insert into result(proc,res) select 'exec H',CHAR(c) from mytab;insert into result(proc,res) values('exec H','End');SET stmt = 'drop table mytab ';execute immediate stmt;

END

2.4.3.11 SIGNAL statementThe SIGNAL statement signals an exception condition:

• If at least one handler in all the nested compound statements is defined tohandle this exception, it will be called immediately by the SIGNAL statement,as in the example below:

The SQL Procedures language 25

Page 42: Store Procedure

CREATE PROCEDURE G10()LANGUAGE SQLBEGIN

DECLARE C1 CONDITION FOR SQLSTATE '04000';DECLARE EXIT HANDLER FOR C1

INSERT INTO result(proc,res) VALUES ('exec of G','EXIT handler fired’);

BEGIN /* nested compound statement*/INSERT INTO result(proc,res) VALUES ('exec of G','This line should stay here');SIGNAL SQLSTATE '04000';/*the handler will be fired here*/INSERT INTO result(proc,res) VALUES ('exec of G','This line shouldn’t be

here');END;

INSERT INTO result(proc,res) VALUES ('exec of G','This lines is executed after thehandler is fired’);

INSERT INTO result(proc,res) VALUES ('exec of G','aEND of Proc');END

• If no handler is defined to catch the SQLSTATE in the SIGNAL statement, theexception will be propagated to the caller, as in the example below:

CREATE PROCEDURE G11()LANGUAGE SQLBEGINDECLARE C1 CONDITION FOR SQLSTATE '04000';INSERT INTO result(proc,res) VALUES ('exec of G', 'START: This line should stayhere');SIGNAL C1;/*exit the procedure with SQLSTATE=C1=04000*/

INSERT INTO result(proc,res) VALUES ('exec of G', 'END of Proc');END

2.4.3.12 RESIGNAL statementThe RESIGNAL statement resignals an exception condition, and it can only becoded as part of a condition handler.

The use of a RESIGNAL statement without an operand causes the identicalcondition to be passed outwards, while a RESIGNAL statement with an operandcauses the original condition to be replaced with the new condition you havespecified.

Following is an example using the RESIGNAL statement:

CREATE PROCEDURE G8 ()LANGUAGE SQLBEGIN

DECLARE not_found condition for SQLSTATE '02000';DECLARE found condition for SQLSTATE '01000';

DECLARE CONTINUE HANDLER FOR SQLSTATE '12345' BEGINRESIGNAL SQLSTATE '22345';RESIGNAL ;RESIGNAL not_found;

END;

insert into result(proc,res) values ( 'exec of G8','Start');SIGNAL SQLSTATE '12345';insert into result(proc,res) values ( 'exec of G8','After signal 123245');SIGNAL found;insert into result(proc,res) values ( 'exec of G8','After signal Found');insert into result(proc,res) values ( 'exec of G8','End');

END

26 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 43: Store Procedure

2.4.3.13 Compound statementRoughly, we can say that a compound statement is a set of one or more SQLstatements between the BEGIN and END keywords.

A compound statement may contain SQL variable declarations, conditionhandlers declaration, or cursor declarations. The order of statements in acompound statement is:

1. SQL variable and condition declarations

2. Cursor declarations

3. Handler declarations

4. Assignment statements, control-flow statements such as CASE, IF, LOOP,REPEAT, and WHILE, and SQL statements such as SELECT, INSERT,UPDATE, DELETE, CALL, CREATE TABLE, etc.

A compound statement may be declared as:

• ATOMIC, which means that all actions performed by the compound statementmust succeed, or the entire set of database modifications made by thoseactions are rolled back. The following is an example of an ATOMIC compoundstatement:

CREATE PROCEDURE D(PARM1 char(10) )LANGUAGE SQLBEGINSC:BEGIN ATOMICDECLARE zz iNTEGER DEFAULT 11;INSERT INTO result(proc, res)

VALUES('exec of D','In atomic block before error test:'||PARM1);

IF (Parm1 = '1') THENSET aaa = (select job from employee );

ELSESET aaa = (SELECT job FROM employee WHERE empno = '000020');

END IF;INSERT INTO result(proc, res)

VALUES('exec of D','In atomic block after error test:'|| aaa);END;

END

• NOT ATOMIC, which means that an error occurring within the compoundstatement does not cause all actions performed by the compound statement tobe rolled back. The NOT ATOMIC string is optional. It is the default for acompound statement. The following is an example of a NOT ATOMICcompound statement:

CREATE PROCEDURE D(PARM1 char(10) )LANGUAGE SQLBEGIN

The SIGNAL and RESIGNAL statements are not yet supported on the OS/390platform.

Important:

The SQL Procedures language 27

Page 44: Store Procedure

SC:BEGIN NOT ATOMICdeclare zz integer default 11;insert into result(proc, res)

values ('exec of D', ' In non atomic block before error test:' || PARM1);

if (Parm1 = '1') thenset aaa = (select job from employee );

elseset aaa = (select job from employee where empno = '000020');

end if;insert into result(proc, res)

values ('exec of D', ' In non atomic block after error test :'|| aaa);END;

END

2.4.3.14 SQL statementsFollowing is a list of SQL statements that may be used in an SQL storedprocedure body. Refer to the SQL Reference Guide for your platform for a moredetailed explanation of these SQL statements. Keywords are not case sensitive.

• ALLOCATE

• ASSOCIATE

• CALL

• CLOSE

• COMMENT ON

• CREATE

• DECLARE CURSOR

• DECLARE GLOBAL TEMPORARY TABLE

• DELETE

• DROP

• EXECUTE

• EXECUTE IMMEDIATE

• FETCH

• GRANT

• INSERT

• LABEL ON

• LOCK TABLE

• OPEN

• PREPARE FROM

ATOMIC compound statements are not yet supported on the OS/390 platform.

Important:

28 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 45: Store Procedure

• RELEASE

• RENAME

• RELEASE SAVEPOINT

• REVOKE

• ROLLBACK TO SAVEPOINT

• ROLLBACK

• SAVEPOINT

• SELECT INTO

• UPDATE

• VALUES INTO

2.4.4 Returning result sets

2.4.4.1 Creating result sets in an SQL stored procedurePassing back a result set to a calling application (an embedded SQL applicationor an SQL stored procedure) is done by declaring with a SELECT statement acursor on the rows that are to be passed back. Many result sets can be returned,but each requires an independent DECLARE CURSOR statement.

If the caller is an application, the cursor declaration has to use a "WITH RETURNTO CLIENT" clause, as in the following example:

CREATE PROCEDURE sp_called_from_appLANGUAGE SQLBEGIN

DECLARE result_set_1 cur1 CURSOR WITH RETURN TO CLIENT FORSelect empno,firstnme from employee ;

OPEN result_set_1;END

If the result set has to be passed back to another stored procedure, the cursordeclaration has to specify a "WITH RETURN TO CALLER" clause, as in theexample below:

CREATE PROCEDURE sp_called_from_spLANGUAGE SQLBEGIN

DECLARE result_set_1 cur1 CURSOR WITH RETURN TO CALLER FORSelect empno,firstnme from employee ;

OPEN result_set_1;END

ASSOCIATE, ALLOCATE, ROLLBACK (except ROLLBACK TO SAVEPOINT),VALUES INTO are not yet supported on the OS/390 platform.

REVOKE is supported on the OS/390 platform.

LABEL ON is supported on the OS/390 platform.

Important:

The SQL Procedures language 29

Page 46: Store Procedure

2.4.4.2 Retrieving result sets in the callerTo retrieve the result sets properly, the caller (embedded SQL application oranother SQL stored procedure) must perform certain operations. We will focus onthe SQL stored procedure syntax only, but the steps are similar in embeddedSQL or CLI applications using host variables.

Here is a high level view for retrieving a result set in the caller:

• Declare a result set locator for each result set expected (DECLARE RESULTSET LOCATOR...).

• CALL the stored procedure.

• ASSOCIATE each locator to the procedure.

• ALLOCATE each cursor for each result set locator.

• FETCH the data for each cursor.

• CLOSE each cursors opened with the ALLOCATE statement.

Every step is detailed below.

Following is an example of an SQL stored procedure Y4 that retrieves one resultset from a SQL stored procedure Y41.

CREATE PROCEDURE Y41 (IN parm1 INTEGER )LANGUAGE SQLBEGIN

DECLARE cur1 CURSOR WITH RETURN TO CALLERFOR Select empno,firstnme from employee ;

OPEN cur1 ;END

In the following procedure Y4, note the use of the CONTINUE HANDLER declarationto detect the end of the result set using the NOT FOUND condition. When thishandler is fired, it sets the RESULT_SET_END variable to 1. After the executionof this handler, execution resumes after the FETCH statement, and the loop willfinally terminates.

CREATE PROCEDURE Y4(IN parm1 INTEGER)LANGUAGE SQLBEGIN

DECLARE LOC_RES1 RESULT_SET_LOCATOR VARYING;DECLARE rc1,rc2 CHAR(20);DECLARE RESULT_SET_END integer default 0;DECLARE CONTINUE HANDLER FOR NOT FOUNDBEGIN

SET RESULT_SET_END = 1;END;

WITH RETURN TO CLIENT or TO CALLER syntax in DECLARE CURSOR arenot yet supported on the OS/390 platform.

Important:

30 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 47: Store Procedure

CALL Y41(parm1);ASSOCIATE RESULT SET LOCATOR( LOC_RES1) WITH PROCEDURE Y41;ALLOCATE RES1 CURSOR FOR RESULT SET LOC_RES1;SET RESULT_SET_END = 0;WHILE(RESULT_SET_END = 0) DOFETCH FROM RES1 INTO rc1,rc2;IF(RESULT_SET_END=0) THEN

insert into result(proc,res)values('exec Y4','rc1='||rc1||'rc2='||rc2);END IF;

END WHILE;CLOSE RES1;

END

2.4.4.3 CALL statementThis statement is the regular CALL SQL statement, which calls a stored procedure. Itcan be an external stored procedure (C, Java, COBOL) or a SQL stored procedure.

CREATE PROCEDURE F (IN ASSEMBLY_NUM CHAR(10) )LANGUAGE SQLBEGIN

CALL MYSP2( ASSEMBLY_NUM);END

The CALL statement accepts only parameters that are variables or constants.Expressions are not allowed.

2.4.4.4 ASSOCIATE statementThe ASSOCIATE LOCATORS statement gets the result set locator value for eachresult set returned by a stored procedure. One result set locator variable isrequired for each result set that the stored procedure will return.

When the ASSOCIATE LOCATORS statement is executed, the procedure nameor specification must identify a stored procedure that the requester has alreadyexecuted using the CALL statement. The procedure name in the ASSOCIATELOCATORS statement must be specified in the same way that it was specified onthe CALL statement. For example, if a two-part name was specified on the CALLstatement, you must use a two-part name in the ASSOCIATE LOCATORSstatement. If the CALL statement was made with a three-part name and thecurrent server is the same as the location in the three-part name, you can omitthe location name and specify a two-part name.

In the following example, two result sets locators (LOC1,LOC2) are associatedwith the stored procedure P1.

DECLARE LOC1 RESULT_SET_LOCATOR VARYING;DECLARE LOC2 RESULT_SET_LOCATOR VARYING;CALL P1;ASSOCIATE RESULT SET LOCATORS (LOC1, LOC2) WITH PROCEDURE P1;

2.4.4.5 ALLOCATE statementThe ALLOCATE CURSOR statement defines a cursor and associates it with aresult set locator variable. The cursor name must not identify a cursor that hasalready been declared in the source program.

The result set locator variable must contain a valid result set locator value, asreturned by a ASSOCIATE LOCATOR statement.

The SQL Procedures language 31

Page 48: Store Procedure

The following rules apply when you use an allocated cursor:

• You cannot open an allocated cursor with the OPEN statement.

• You can close an allocated cursor with the CLOSE statement. Closing anallocated cursor closes the associated cursor in the stored procedure.

• You can allocate only one cursor to each result set.

The life of an allocated cursor is: a rollback operation, an implicit close, or anexplicit close that destroys allocated cursors.

For example, define and associate cursor C1 with the result set locator variableLOC1 for the first result set returned by the stored procedure, cursor C2 withresult set locator LOC2 for the second result set returned by the storedprocedure:

DECLARE LOC1 RESULT_SET_LOCATOR VARYING;DECLARE LOC2 RESULT_SET_LOCATOR VARYING;CALL P1;ASSOCIATE RESULT SET LOCATORS (LOC1, LOC2) WITH PROCEDURE P1;ALLOCATE C1 CURSOR FOR RESULT SET LOC1;ALLOCATE C2 CURSOR FOR RESULT SET LOC2;

2.4.4.6 Processing the result setOnce the ASSOCIATE and ALLOCATE statements are done, processing a resultsset in the stored procedure is achieved by FETCHing the result set rows into anSQL variable until the end of the result set is reached. After a result set isprocessed, a CLOSE cursor statement must be executed.

In the example below, the SQL stored procedure processes two result sets byinserting each row into the result table.

CREATE PROCEDURE P1()LANGUAGE SQL

BEGINDECLARE LOC1 RESULT_SET_LOCATOR VARYING;DECLARE LOC2 RESULT_SET_LOCATOR VARYING;DECLARE AT_END INTEGER DEFAULT 0;DECLARE column1,columns2 VARCHAR(30);DECLARE CONTINUE HANDLER FOR NOT FOUND

SET AT_END = 1;

CALL P1;/*retrieve 2 results sets,both of them with 2 varchar(30)columns*/

ASSOCIATE RESULT SET LOCATORS (LOC1, LOC2) WITH PROCEDURE P1;ALLOCATE C1 CURSOR FOR RESULT SET LOC1;ALLOCATE C2 CURSOR FOR RESULT SET LOC2;SET AT_END=0;

WHILE (AT_END = 0 ) DO /* processing result set #1 */FETCH C1 INTO column1, columns2;INSERT INTO RESULT(proc,res) VALUES (’result

1’,column1||columns2);END WHILE;

CLOSE C1;

SET AT_END=0;

32 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 49: Store Procedure

WHILE (AT_END = 0 ) DO /* processing result set #1 */FETCH C2 INTO column1, columns2;INSERT INTO RESULT(proc,res) VALUES (’result

1’,column1||columns2);END WHILE;CLOSE C2;

END

2.4.5 Handling errors in an SQL stored procedureYou cannot use the WHENEVER statement in an SQL stored procedure body.Instead, you can declare handlers to tell the SQL stored procedure what to dowhen an SQL error or an SQL warning occurs, or when no more rows arereturned from a query. In addition, you can declare condition handlers for specificSQLSTATE values like ’22000, ’2300’ or whatever you like.

You can refer to an SQLSTATE by its number in a condition handler, or you candeclare a name for the SQLSTATE, then use that name in the condition handler.

A condition handler must specify:

• A set of conditions it is prepared to handle.

• Action to perform to handle the condition.

• Where to resume the execution after handling the condition.

The action specified in a condition handler can be any SQL statement, including acompound statement.

A condition handler gets executed automatically when a condition it is preparedto handle is detected anytime during the execution of the containing compoundstatement.

The general form of a handler declaration is:

DECLARE handler-type HANDLER FOR condition SQL-procedure-statement;

Conditions specified in a condition handler can be:

• SQLSTATE value

• Condition name ( user defined)

• SQLEXCEPTION (all SQLSTATE values with class other than 00, 01, or 02)

• SQLWARNING (all SQLSTATE values with class 01)

• NOT FOUND (all SQLSTATE values with class 02)

From sections 2.4.4.2, “Retrieving result sets in the caller” on page 30to 2.4.4.6, “Processing the result set” on page 32:

The OS/390 platform does not support result set locators yet(DECLARE xx RESULT SET LOCATOR, ASSOCIATE, ALLOCATE).

The example shown in section 2.4.4.2, “Retrieving result sets in the caller” on page30 with CONTINUE HANDLER shows a compound statement in the handler,which is not supported on OS/390.

Important:

The SQL Procedures language 33

Page 50: Store Procedure

In general, the way that a handler works is that when an error occurs thatmatches the condition, the SQL-procedure-statement executes. WhenSQL-procedure-statement completes, DB2 performs the action that is indicatedby the handler-type.

There are three types of handlers:

• CONTINUE

Specifies that after SQL-procedure-statement completes, execution continueswith the statement after the statement that caused the error.

• EXIT

Specifies that after SQL-procedure-statement completes, execution continuesat the end of the compound statement that contains the handler.

• UNDO

Specifies that all the SQL statements done from the beginning of thecontaining compound statement, until the error point, are rolled back, andthen, after the SQL-procedure-statement completes, execution continues atthe end of the compound statement that contains the handler.

Figure 4 shows the behavior of each condition handler, when the statement-2

reaches the condition:

• CONTINUE: after the execution of the handler-action is successful, theexecution of the stored procedure will resume at the next statement (theCONTINUE point) which in this case is statement-3.

• EXIT: after the execution of the handler-action is successful, the execution ofthe stored procedure will resume at the end of the continuing compoundstatement (EXIT point).

• UNDO: after the execution of the handler-action is successful (including therollback of statement 1), the execution of the stored procedure will resume atthe UNDO point, the end of the continuing compound statement.

Figure 4. Behavior summary of different condition handlers

The following is a short example that will trigger an exception handler becausethe variable mydate is not correct (missing the ’/’ character).

34 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 51: Store Procedure

CREATE PROCEDURE G3()LANGUAGE SQLBEGIN

declare mydate DATE;DECLARE C1 condition for SQLSTATE '22007';DECLARE C2 condition for SQLSTATE '22017';DECLARE EXIT HANDLER FOR SQLEXCEPTION

insert into result(proc,res)values ('exec of G3','EXIT HANDLER fired:SQLSTATE='||SQLSTATE||'SQLCODE='||CHAR(SQLCODE));

DECLARE EXIT HANDLER FOR C1, SQLSTATE '22008', SQLSTATE '22006', C2insert into result(proc,res) values ('exec of G3','EXIT HANDLER

fired:SQLSTATE='||SQLSTATE||' SQLCODE='||CHAR(SQLCODE));

insert into result(proc,res)values ('exec of G3','start of procedure');

SET mydate = '12' || '13' || '99';

END

The following is another example that uses exception handlers.

CREATE PROCEDURE PSM031 (IN NUM_PARTS CHAR(10) )LANGUAGE SQLBEGIN

DECLARE lc1,i, nb, lc2,lc1c2 integer default 0;DECLARE CONTINUE HANDLER FOR NOT FOUND BEGIN

insert into result(proc,res)values ( 'exec from PSM031', 'NOT FOUND Handler fired');

END;DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN

insert into result(proc,res)values ( 'exec from PSM031', 'SQLEXCEPTION handler fired

SQLCODE='||CHAR(SQLCODE));END;DECLARE CONTINUE HANDLER FOR SQLWARNING BEGIN

insert into result(proc,res)values ( 'exec from PSM031', 'SQLWARNING handler fired');

END;

DECLARE cur1 CURSOR FOR Select c1,c2 from t1;delete from t1;insert into t1(c1,c2) values (1,1);insert into t1(c1,c2) values (1,2);set nb = (select count(*) from t1);OPEN cur1;set i = 0;while (i < nb) do

FETCH FROM cur1 INTO lc1,lc2;insert into result(proc,res) values ( 'exec from PSM031',

'row:'||CHAR(i)||' c1='|| CHAR(lc1) || ' c2='|| CHAR(lc2));set i=i+1;

end while;CLOSE cur1;

END

The SQL Procedures language 35

Page 52: Store Procedure

2.4.6 Current restrictionsThe first release of SQL Procedures support on all DB2 platforms does notimplement the following SQL/PSM features:

• Persistent modules

• Nested condition handlers

• Nested ATOMIC compound statements

• SQL functions

2.5 SQL Procedures portability

It is our intention to provide SQL Procedures support across the DB2 UniversalDatabase family of products using a common SQL Procedures language and acommon application development tool, the DB2 Stored Procedure Builder on everyplatform. We also expect that a significant number of customers will want to developtheir stored procedures on an individual workstation, for example, a PC runningWindows NT, using a local database, for example, DB2 for Windows NT; and as theymove that application and its stored procedures into production, they will deploy it onDB2 for Windows NT on a different server or a DB2 for OS/390 platform.

Some customers will initially use their stored procedures against a departmentalserver running DB2 for AIX or DB2 for Sun Solaris, and then as usage scales up andmore capacity is needed, they will consider moving their stored procedures to DB2for OS/390. We will support these development and usage scenarios by providingcommon SQL Procedures language and Stored Procedure Builder support across allplatforms.

Because of differences in release cycles and platform priorities, it is not alwayspossible (or desirable) to deliver the same functionality on all platforms at exactlythe same time. To help application developers identify and use the very large setof SQL Procedures language features that are common across all of the DB2platforms, we have produced the following portability matrix (see Table 1). It isimportant to emphasize, however, that DB2 will be continuing to enhance the SQLProcedures language on all platforms and reduce any current platformdifferences.

Table 1 shows the potential differences between each of the IBM platforms.

Table 1. SQL Procedures portability across DB2 platforms

Functional Item Windows, UNIX, andOS/2

OS/390 AS/400

Savepoint Named savepoints.single, non-nested

Not supported in V5Supported in V6(Multiple)

Not yet supported

Source code size limit 64K size limit in 12/99 32K 32K

UNDO handlers are not yet supported on the OS/390 platform.

Important:

36 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 53: Store Procedure

Authorization behavior withdynamic SQL statements;will use Executor's authorityfor both DML and DDL

Supported Supported Supported only throughRUNSQLSTM command

Nested NOT ATOMICcompound statement

Supported Not yet supported Not yet supported

Nested ATOMIC compoundstatements

Not yet supported Not yet supported Not yet supported

Nested stored procedurecalls

Supported Not supported in V5Supported in V6

Supported

Returning result sets Supported Supported Supported

ALLOCATE CURSORstatement for processingresult sets from nestedprocedures

Supported Not yet supported Supported

Dynamic SQL statementwithin an SQL storedprocedure

Supported(CALL statementsupported in V8)

Supported Supported

Multi-rowed result sets Supported Supported Supported from a client viaClient Access ODBC and JavaToolbax JDBC.

Supported from the serverthrough CLI and JDBC.

COMMIT Not yet supported Not yet supported Supported(only allowed for NOT ATOMICprocedures that are NOTinvoked through DRDA)

ROLLBACK Supported Not yet supported Supported(only allowed for NOT ATOMICprocedures that are NOTinvoked through DRDA)

CONNECT Not yet supported Not Supported in V5Supported in V6

Supported

FOR Supported Not yet supported Supported

GRANT statement inprocedure

Supported Supported Supported

REVOKE statement inprocedure

Not yet supported Supported Supported

SIGNAL Supported Not yet supported Not yet supported

RESIGNAL statement Supported Not yet supported Not yet supported

Stand-aloneSQLCODE/SQLSTATE

Supported Supported Supported

Functional Item Windows, UNIX, andOS/2

OS/390 AS/400

The SQL Procedures language 37

Page 54: Store Procedure

CREATE PROCEDUREstatements

Not yet supported Supported Supported

Static DDL Supported Supported Supported

Single statement procedure Supported Supported Supported

ITERATE statement(not in PSM-96)

Supported Not yet supported Not yet supported

GOTO (extension to thestandard)

Not yet supported Not yet supported Not yet supported

C comment Supported Not yet supported Supported

Overriding of PREP andcompile options

Supported Supported Supported via options in ClientAccess. Supported on theRUNSQLSTM interface

New line stored in the catalog- consistency

Supported Newline markers arestored inSYSIBM.SYSPSM forSPB to recover the initial"look" of the SP.The debugger willdisplay PSM source as80 byte wide lines (aDB2 OS/390precompiler restriction)

Currently strip out all extrablanks and control characters.This is partially because thecatalog column isVARCHAR(18432), but aprocedure body can be largerthan that.

Ambiguous names resolvedin the following sequence:1) Check if it is a columnname (table exists),2) Check if it is a SQLvariable/parameter name;3) Assume to be a columnname (table does not existand VALIDATE RUN option isused).

Supported Not yet supported Supported

Parameter names 128 8 characters in V518 characters in V6

128

Max length of charactervariable

254 bytes for VARCHAR32 Kbytes for LONGVARCHAR

255 bytes 32 Kbytes

DATE arithmetic(for example:mydate+5 days)

Supported Supported Supported

SELECT statement on righthand side of SET statement

Supported Not yet supported Supported

DECIMAL data types Not yet supported Supported Supported

Functional Item Windows, UNIX, andOS/2

OS/390 AS/400

38 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 55: Store Procedure

2.6 New error messages

Below we provide a short description of the new error messages that will beprovided by the precompiler when errors occur during the SQL stored procedureprogram preparation.

The error messages will be prefixed with the specific platform precompileridentification. For example, for error code -775, DB2 for OS/390 will sendDSNH29775I.

-060 Data-type was specified in the definition of object-name. object-type in anSQL stored procedure parameter or variable. data-type is not supported for SQLstored procedure parameters or variables.

-061 One unexpected reason code was returned from Language Environment.

-775 In an SQL stored procedure, compound SQL statement contains an SQLstored procedure statement that is not allowed.

-776 In an SQL stored procedure, a FOR statement contains an OPEN, FETCH,or CLOSE statement for cursor cursor-name. Cursor operations are no allowed inFOR statement.

-777 An SQL stored procedure contains nested compound statements, whichare not allowed.

-778 An SQL stored procedure statement contains an ending label and abeginning label that do not match.

-779 In an SQL stored procedure, the label on a LEAVE statement does notmatch the label for a block of code or loop that contains the LEAVE statement.

-780 An SQL stored procedure specifies an UNDO statement for a handler, andthe ATOMIC statement was not specified.

-781 In an SQL stored procedure, a handler is declared for conditioncondition-name, but the SQL stored procedure does not contain a conditiondeclaration statement that defines condition-name.

-782 In an SQL stored procedure, a condition handler is not valid for one of thefollowing reasons:

• The handler specifies an SQLSTATE value that is not valid.• The handler specifies duplicate conditions.• The handler specifies SQLWARNING, SQLEXCEPTION, or NOT FOUND with

other condition.

-783 An SQL stored procedure contains a FOR in which the select list in thecursor declaration has a column that is not valid. That column is a duplicate ofanother column in the select list, or the column is not named.

-785 In an SQL stored procedure, the name SQLCODE or SQLSTATE is used inone of the following invalid ways:

• An SQLCODE is declared as an SQL variable with a data type other than anINTEGER.

The SQL Procedures language 39

Page 56: Store Procedure

• An SQLSTATE is declared as an SQL variable with a data type other thanCHAR(5).

• An SQLCODE or SQLSTATE is declared as an SQL variable with DEFAULTNULL.

• An SQLCODE or SQLSTATE is assigned the value NULL in an assignmentstatement.

• An SQLCODE or SQLSTATE is the same as an SQL stored procedureparameter.

2.7 Migrating from OEM DBMS

The SQL Procedures language is at the same conceptual level as the T/SQL ofSybase/Microsoft SQL Server, PL/SQL of Oracle, or SPL from Informix. Migratingthe business logic, programmed in stored procedures language from anotherdatabase vendor, to DB2 UDB SQL Procedures, should be easy. Most of the time,every stored procedure statement in the Oracle, Sybase, and Informix storedprocedure language has an equivalent in the DB2 stored procedure language.Some differences in concepts, like error handling or result sets processing, maybe the most difficult things to migrate.

But migration from another RDBMS implies many phases, not only businesslogic. The following sections briefly discuss all of these considerations beforefocusing on the business logic and stored procedures migration.

Note: Refer to the URL http://www.ibm.com/solutions/softwaremigration, forassistance with migrations.

2.7.1 Migrating the database structureThis is usually the easiest part. The data definition language between RDBMSs isquite similar. A few differences exist, though, most often on referential integrityconstraint declarations, domain declarations, and storage managementdirectives. There are tools that actually that convert structures rather well, with aminimum need for the DBA to intervene.

Some of these tools are:

• Platinum ERwin ERX v3.5. This one appears to be the favorite in this area.

• InfoModelers InfoModeler v3.1.

• DataJunction v6.5, which is primarily a data movement tool, but also providessupport for DDL.

. Error code -061 is specific for OS/390 platform.

. -775 is not defined for distributed platforms because they support nestedcompound statements.

. -780 is not defined for OS/390 because UNDO is not currently supported onOS/390 platform.

Important:

40 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 57: Store Procedure

2.7.2 Migrating the database dataThis can be pretty complex if transformation or conversion of the data is needed,because certain data types do not exist in the target RDBMS. This could result incomplex and expensive operations, for instance on Binary Large Objects (BLOB).Another problem is the format of the export or import files. Every vendor usesdifferent ones, and an extra conversion of the data files may be needed. Most ofthe time, import/export files have binary proprietary formats that allow fastload/unload of data for the same kind of RDBMS. They have to win load/unloadbenchmarks, and any trick is valuable. These binary files are usually incompatiblebetween different RDBMS.

Fortunately, most of the actual RDBMSs can usually create SQL scripts, whichmeans files with SQL statements, or tabulated text files, to transfer data to disk.This method is slower and requires more space on disk, but usually will workwithout too many manipulations. Some tools exists on the marketplace thathandle data migration for you. Some of them even allow you to transfer andtransform the data before saving it to disk. This can be really helpful if you have tochange data types or format between the two RDBMS.

Some of these tools are:

• DataJunction v6.5.

• IBM DataJoiner allows you to copy data from any RDBMS (Sybase, Oracle,Informix) seamlessly into your DB2 UDB, exactly as if all the other databaseswere all on the same machine. Using it can be a good solution for longprojects, where customers have to deal with different RDBMS for a long periodof time.

• SQL Conversion Workbench (SQL-CW), from Mantech Systems SolutionsCorporation, allows you migrate database objects and contents.

2.7.3 Migrating the business logicThis is the most complex part, depending on how much business logic has beenis developed in a language different from the target one.

2.7.3.1 The client applicationsIf the client application relies on a 4GL tool such as PowerBuilder or SQLWindows, which accepts different RDBMSs, it is usually enough to change thedata source in the project, recompile the application, and fix the errors that showup. But sometimes, differences in the SQL syntax, incompatibilities between datatypes for parameters and variables, transaction control, and locking model maybe difficult issues to solve, and may require longer investigations to find solutionsthat work on the new RDBMS.

There are some migration processing tools available that accept one language suchas T/SQL and generate stored procedures in another language such as SQLProcedures. These tools generally perform some significant percentage of the workautomatically but typically require some manual effort for conversion as well.

Proprietary 4GL tools do not usually connect to other databases, such as OracleFORMS, and migrating that kind of application may require more manual effort forconversion.

The SQL Procedures language 41

Page 58: Store Procedure

If the client application uses a 3GL tool like C with ODBC (standard API) it willprobably be relatively easy to migrate to DB2 UDB. That is because DB2 UDBsupports ODBC as well as supporting IBM CLI (an IBM ODBC layer that has thesame APIs as ODBC, but is optimized for DB2 UDB). In fact, ODBC was designedto be insensitive to different RDBMSs. Unfortunately, because of the differentimplementations by the ODBC resellers, most ODBC flavors have minorportability issues.

If the client application was developed using Oracle proprietary APIs, orproprietary Sybase APIs (CT-LIB) or some other proprietary API on otherRDBMSs, then more work will have to be done, that is, the part of the applicationthat deals with those API will have to be rewritten, because the API calls willprobably not have any corresponding calls in DB2 UDB APIs.

Because this is a lot of work, tools should be available to ease the process ofconverting client applications. Unfortunately, no tools really do this kind ofconversion automatically. It is really too difficult, and human intervention isrequired.

2.7.3.2 The stored proceduresOther RDBMS vendors did not choose the SQL Procedures language, which is astandard. Since each database vendor has a different implementation of storedprocedure programming languages, migration of stored procedures can becomean important issue, depending on the extent of them in the application. The futureof stored procedures in the area of relational databases is currently at a turningpoint, as Java is being considered as a possible solution to the portability andflexibility. Java is a full programming language, and people who are familiar withwriting in simple languages such as PL/SQL or T/SQL prefer to move to anotherlanguage like SQL procedures language that is much easier to learn. For manycustomers, Java is an interesting programming language for experiencedprogrammers, but is not necessarily for developers who only know T/SQL, forexample.

It is still much easier and faster to migrate to SQL stored procedures from otherRDBMS than migrating to C or Java external stored procedures. Not only will thetraining cost of the teams involved in development be reduced (a few hours areenough to learn the SQL Procedures language if you know T/SQL or PL/SQL),but also, the development cost itself will go faster by reducing the amount of codewritten.

To ease the migration, some help can be found with tools like the SQLConversion Workbench (SQL-CW) from Mantech Systems Solutions Corporation,that can translate most simple procedures from other RDBMSs. For morecomplex stored procedures, which often rely heavily on engine features, it maysometimes be necessary to redesign the application itself, instead of spendingtime to mimic a behavior that cannot be created on the new DB2 UDB engine.(See Table 2.)

Table 2. RDBMS Stored Procedure language comparison

RDBMS Vendor Language Benefits Drawbacks

Oracle V7.x / V8.x PL/SQL ease of useused in Adtools (Forms)

proprietary, flexibility

42 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 59: Store Procedure

Migrating the control statements from other RDBMS stored procedureslanguages manually is usually not that difficult. The most difficult part of this isdealing with engine-specific features not available on the target platform.

For example, until recently, temporary tables like those found in Sybase andInformix (check DECLARE GLOBAL TEMPORARY TABLE statement) were notsupported in any version of DB2 UDB on any platform, and simulating them withbase tables can lead to poor performance in the migrated applications because ofthe catalog contention. This can also lead to expensive development costs duringthe migration phase, sometimes requiring a thorough redesign of the businesslogic itself, and resulting in a slower implementation of the new application.

To lower the cost of migration from other RDBMSs, DB2 UDB version 7.x willimplement a full set of new features in the engine, such as temporary tables,savepoints, identity columns, and nested stored procedure calls, which will beincorporated in the new releases.

Although all these new features will ease migration, some stored procedureslogic will have to be redesigned to fit in the new engine. That is, there may bechanges needed in naming conventions or reengineering what modules workbest for a given RDBMS.

2.7.4 Comparison with Sybase/Microsoft SQL Server Transact-SQLThe SQL Procedures language is very similar to T/SQL, and in fact, most of theT/SQL control flow statements represent a subset of the SQL Procedureslanguage control flow statements. However, there are some differences; forexample, T/SQL does not have support for:

• Error handler statements

• LOOPs

• FOR loops

• REPEAT UNTIL

• ELSEIF

• ATOMIC blocks

Sybase SQL Server V10.x & V11.x

Transact SQL ease of use proprietary, flexibility

Microsoft SQL ServerV6.5 / V7.0

Transact SQL ease of use proprietary, flexibility

Informix v7.x Informix SPL ease of use proprietary, flexibility

DB2 UDB V6.x / DB2Server for OS/390 V5SQL stored procedure

SQL Procedureslanguage

ease of use,standardcompliant

flexibility

DB2 UDB V5.x / V6.xexternal SP

C, COBOL, Java flexibility,power

skill require, complex

RDBMS Vendor Language Benefits Drawbacks

The SQL Procedures language 43

Page 60: Store Procedure

Table 3 shows the SQL/PSM (standard) control statements and Sybase/MicrosoftT/SQL control statements.

Table 3. Comparison between SQL/PSM and T/SQL control statements

SQL/PSM control statements Sybase/Microsoft SQL Server T/SQL controlstatements

CALL EXECUTE

Result set processing after a CALL statement No equivalent

LEAVE <procedure-body-name> RETURN

BEGIN (Compound statements)END

BEGINEND

Handler declaration No equivalent

Condition declaration No equivalent

SQL variable declarationdeclare <var-name> <datatype> default <defvalue>

declare <var-name> <datatype>

Assignment declarationSET <var-name> = <expression>

SELECT <var-name> = <expression>

IF <expression> THEN...ELSEIF...ELSE...END IF; IF <expression> ...ELSE...(no THEN, no ELSE IF, no END IF)

CASE statement No equivalent

LEAVE statement BREAK

LOOP No equivalent

WHILE statement WHILE statement

REPEAT No equivalent

FOR statement No equivalentequivalent done by tricks with WHILE, temporary table andset rowcount=1 and 0.

SIGNAL <sqlstate> statement RAISERROR <error-number>

RESIGNAL statement No equivalent

ITERATE Continue

GET DIAGNOSTICS <varname>=ROWCOUNT SELECT <varname>=rowcount

No equivalent goto <label>

No equivalent waitfor DELAY ’time’waitfor TIME ’time’

No equivalent SET options

44 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 61: Store Procedure

Table 4 shows a quick comparison between DB2 and Sybase/Microsoft SQLServer.

Table 4. Comparison between DB2 and Sybase SQL Server

DB2 Sybase/Microsoft SQL Server

ATAN ATAN

-- comment -- comment

/* comment */ /* comment */

ABS ABS

ABSVAL ABS

ACOS ACOS

AND AND

ASCII ASCII

ASIN ASIN

ATAN2 ATAN2

AVG AVG

BLOB CONVERT(IMAGE, ... )

CALL statement execute

CEILING CEILING

CHAR CONVERT(CHAR,...)

CLOB CONVERT(TEXT, ...)

CLOSE CLOSE

COALESCE ISNULL(...,...)

COMMIT (no nested commits) COMMIT savepoint_name

Compound ATOMIC statement Begin tran xx.... commit tran xx

Compound SQL statement Begin ... End block

COS COS(:1P)

COT COT(:1P)

COUNT COUNT

COUNT DISTINCT COUNT DISTINCT

Create temporary table *** Select <expression> into table

cursor with hold HOLDLOCK

DATE CONVERT(DATETIME, ...)

DAY DATEPART(DAY,CONVERT(DATETIME,...))

DAYNAME DATENAME(DAY, CONVERT(DATETIME,...))

DAYOFWEEK DATEPART(DAY,CONVERT(DATETIME,...))

The SQL Procedures language 45

Page 62: Store Procedure

DAYOFYEAR DATEPART(YEAR, CONVERT(DATETIME,...))

DB2 allows setting transaction isolation level to RR, RS,CS, UR at package bind

SET TRANSACTION isolation level <n>

DB2 ordinarily runs under transaction control BEGIN Transaction <transaction name> or <savepointname>

DDL for create table, create index, grant, revoke, .....* DDL for create table, create index, grant, revoke, .....

DECIMAL CONVERT(DECIMAL(..,..),..)

DECIMAL CONVERT(DECIMAL(...,..),...)

DECLARE Cursor DECLARE Cursor

DEGREES DEGREES(...)

DELETE DELETE

DELETE WHERE CURRENT OF cursor delete where current of

DIFFERENCE DIFFERENCE(...,...)

DOUBLE_PRECISION CONVERT(FLOAT(2),...)

EXP EXP(...)

FETCH FETCH

FLOOR FLOOR(...)

GROUPBY (ROLLUP(...)) COMPUTE

HOUR DATEPART(HOUR, CONVERT(DATETIME,...))

IDENTITY COLUMN IDENTITY COLUMNS

IF cd1 THEN St1 ELSE St2 END IF IF cd1 THEN st1 ELSE st2

INSERT INSERT

INT CONVERT(INT,...)

IS NOT NULL IS NOT NULL

IS NULL IS NULL

ITERATE continue

LCASE LOWER(...)

LEAVE statement break

LENGTH DATALENGTH(...)

LIKE LIKE

LN LOG(...)

LOCATE PATINDEX(...,...)

LOG LOG(...)

LOG10 LOG10(...)

DB2 Sybase/Microsoft SQL Server

46 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 63: Store Procedure

LTRIM LTRIM(...)

MAX MAX

MICROSECOND DATEPART(MILLISECOND, ...)

MIN MIN

MINUTE DATEPART(MINUTE, CONVERT(DATETIME, ...))

MOD %

MONTH DATEPART(MONTH, CONVERT(DATETIME,...))

MONTHNAME DATENAME(MONTH,CONVERT(DATETIME,...))

NOT NOT

OPEN OPEN

OR OR

POSSTR CHARINDEX(...,...)

QUARTER DATEPART(QUARTER,CONVERT(DATETIME,...))

RADIANS RADIANS(...)

REPEAT REPLICATE(...,...)

RETURN statement RETURN integer

RIGHT RIGHT

ROLLBACK TO SAVEPOINT <savepoint-name> ROLLBACK <savepoint-name>

ROLLBACK WORK ROLLBACK WORK

RTRIM RTRIM

SAVEPOINT <savepoint-name>** SAVE transaction savepoint-name

SECOND DATEPART(SECOND, CONVERT(DATETIME,...))

SELECT SELECT

SET statement(into many vars) SELECT var1=column1,var2=columns2,....

SET var=statement SELECT var = statement

SIGN SIGN

SIGNAL sqlstate RAISERROR error-number

SIN SIN

SMALLINT CONVERT(SMALLINT, ...)

SOUNDEX SOUNDEX

SPACE SPACE

SQL variable declaration declare @variable-name data-type

SQRT SQRT

STDDEV No equivalent

DB2 Sybase/Microsoft SQL Server

The SQL Procedures language 47

Page 64: Store Procedure

2.7.5 Comparison with Oracle PL/SQLThe SQL Procedures language is also very similar to PL/SQL. But, just as withT/SQL, there are some differences between SQL Procedures and PL/SQL; forexample:

• PL/SQL does not have the same error handling, although it does haveexceptions

• Does not support compound atomic

• Does not have result sets, although can still use the dbms_output package tosend information back to the client application

• PL/SQL has features such as:

• %TYPE,

• %ROWTYPE,

• %TABLE,

• SQL%ROWCOUNT,

• SQL%FOUND,

• SQL%NOTFOUND,

SUM SUM

TAN TAN

TIME CONVERT(DATETIME, ...,108)

UCASE UPPER

UNION UNION

UPDATE UPDATE

UPDATE WHERE CURRENT OF cursor update where current of

VARCHAR CONVERT(VARCHAR, ...)

VARIANCE No equivalent

WEEK DATEPART(WEEK, CONVERT(DATETIME,...))

WHILE statement while expression statement

YEAR DATEPART(YEAR, CONVERT(DATETIME,...))

|| — (string concat) +

No equivalent @@rowcount

No equivalent bitwise operations ( ^ & | ~ )

No equivalent deallocate

No equivalent goto label

No equivalent LIKE 'regular_expression'

No equivalent PRINT ...

No equivalent SET ROWCOUNT

DB2 Sybase/Microsoft SQL Server

48 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 65: Store Procedure

• ROWID

• Packages (that should look similar to SQL PSM modules)

Table 5 shows the SQL/PSM (standard) control statements and Oracle PL/SQLcontrol statements.

Table 5. Comparison between SQL/PSM and PL/SQL control statements

SQL/PSM control statements Oracle PL/SQL control statements

CALL No equivalent

result set processing after a CALL statement No equivalent

LEAVE <procedure-body-name> RETURN

BEGIN (Compound statements)END

BEGINEND

Handler declaration EXCEPTION (differences)

Condition declaration exception-name EXCEPTIONPRAGMAEXCEPTION_INIT(exception-name,error-number)(no SQLSTATE values)

SQL variable declarationdeclare <var-name> <datatype> default <defvalue>

declare <var-name> <datatype>

Assignement declarationSET <var-name> = <expression>

<var-name> = <expression>

IF <expression> THEN ...ELSEIF...THEN ...ELSE...END IF;

IF <expression> THEN..ELSIF...THEN...ELSE...END IF;

CASE statement No equivalent

LEAVE statement EXIt <label>

LOOP LOOP

WHILE statement WHILE statementorFOR <indx-name> IN lowerbound..upperboundLOOP.....END LOOP

REPEAT No equivalent

FOR statement FOR <record-name> IN <cursor-name> LOOP....END LOOP

SIGNAL <sqlstate> statement RAISE <error-number>

RESIGNAL statement RAISE

ITERATE continue

GET DIAGNOSTICS <varname>=ROWCOUNT <varname>=SQL%ROWCOUNT

No equivalent goto <label>

The SQL Procedures language 49

Page 66: Store Procedure

Table 6 shows a comparison between DB2 and Oracle:

Table 6. Comparison between DB2 and Oracle

DB2 Oracle

-- comment -- comment

/* comment */ /* comment */

ABS ABS

ABSVAL ABS

ACOS ACOS

AND AND

ASCII ASCII

ASIN ASIN

ATAN ATAN

ATAN2 ATAN2

AVG AVG

AVG AVG

BLOB LONG()

BLOB RAW()

CALL statement CALL statement

CASE (expr) WHEN..THEN..ELSE..END DECODE( expr,...,...,...)

CEILING CEIL

CHAR() CHAR()

CHAR() TO_CHAR()

CLOB LONG()

CLOSE CLOSE

COALESCE ISNULL(..., ...)

COMMIT (no nested commits) COMMIT savepoint_name

Compound ATOMIC statement Begin tran xx.... commit tran xx

Compound SQL statement Begin ... End block

CONTINUE/EXIT/UNDO handlers EXCEPTION

COS COS

COT COT

COUNT COUNT

COUNT DISTINCT COUNT DISTINCT

cursor with hold HOLDLOCK

DATE TO_DATE()

50 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 67: Store Procedure

DAY TO_CHAR(....,DD)

DAYNAME TO_CHAR(....,DAY)

DAYOFWEEK TO_CHAR(....,D)

DAYOFYEAR TO_CHAR(....,DY)

DB2 allows setting transaction SET TRANSACTION

DB2 ordinarily runs under transaction control BEGIN Transaction <transaction name> or <savepointname>

DDL for create table, create index, grant, revoke, .....* DDL for create table, create index, grant, revoke, .....

DECIMAL () DECIMAL()

DECIMAL () NUMBER()

DECIMAL() DEC()

DECLARE Cursor DECLARE Cursor

DEGREES DEGREES

DELETE DELETE

DELETE WHERE CURRENT OF cursor delete … where current of

DOUBLE() DOUBLE_PRECISION()

EXP EXP

FETCH FETCH

FLOAT() FLOAT()

FLOOR FLOOR

FOR rec IN csr LOOP ...END LOOP FOR rec IN csr LOOP ...END LOOP

GENERATE_UNIQUE (slightly different) ROWID

GROUPBY (ROLLUP(...)) No equivalent

HOUR TO_CHAR(....,HH)

IDENTITY COLUMN CREATE SEQUENCE xx START WITH yy

IF cd1 THEN St1 ELSE St2 END IF IF cd1 THEN st1 ELSE st2 END IF

INSERT INSERT

INT BINARY_INTEGER()

IS NOT NULL IS NOT NULL

IS NULL IS NULL

isolation level to RR,RS,CS,UR at No equivalent

LCASE LOWER

LEAVE EXIT

LEAVE statement EXIT WHEN ...

DB2 Oracle

The SQL Procedures language 51

Page 68: Store Procedure

LENGTH LENGTH()

LIKE LIKE

LN LN

LOCATE INSTR()

LOG LOG

LOG10 LOG10

LOOP..... END LOOP LOOP..... END LOOP

LTRIM LTRIM

MAX MAX

MIN MIN

MINUTE TO_CHAR(....,MI)

MOD MOD

MONTH TO_CHAR(....,MM)

MONTHNAME DATENAME(MONTH,CONVERT(DATETIME,...))

NOT NOT

OPEN OPEN

OR OR

package bind No equivalent

POWER **

POWER POWER

QUARTER DATEPART(QUARTER,CONVERT(DATETIME,...))

RADIANS RADIANS

REPLACE REPLACE

RESIGNAL RAISE

RETURN statement return integer

RIGHT RIGHT

ROLLBACK TO SAVEPOINT <savepoint-name> ROLLBACK <savepoint-name>

ROLLBACK WORK ROLLBACK WORK

ROUND(m,n) ROUND(m,n)

RTRIM RTRIM

SAVEPOINT <savepoint-name>** SAVE transaction savepoint-name

SECOND TO_CHAR(....,SS)

SELECT SELECT

SET var=(statement) var := (statement)

DB2 Oracle

52 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 69: Store Procedure

SIGN SIGN

SIGNAL RAISE exception_name

SIN SIN

SINH SINH

SMALLINT SMALLINT

SOUNDEX SOUNDEX

SPACE SPACE

SQL variable declaration declare variable-name data-type

SQRT SQRT

STDDEV(exp) STDDEV(exp)

SUBSTR SUBSTR

SUM SUM

TAN TAN

TANH TANH

TIME TO_DATE()

TRANSLATE() TRANSLATE()

UCASE UPPER

UNION UNION

UPDATE UPDATE

UPDATE WHERE CURRENT OF cursor update … where current of

USER UID

VALUE(exp1,exp2) NVL(exp1,exp2)

VARCHAR() VARCHAR2()

VARIANCE VARIANCE

WEEK DATEPART(WEEK, CONVERT(DATETIME,...))

WHILE statement WHILE expression statement

YEAR TO_CHAR(....,IYY), TO_CHAR(.....,YYYY)

|| — (string concat) || ( string concat)

No equivalent %ISOPEN

No equivalent %TYPE

No equivalent BOOLEAN()

No equivalent COSH()

No equivalent COUNT

No equivalent CREATE PACKAGE .....

DB2 Oracle

The SQL Procedures language 53

Page 70: Store Procedure

No equivalent CURRVAL

No equivalent dbms_output_package.print()

No equivalent deallocate

No equivalent define RECORD Type

No equivalent DELETE

No equivalent EXISTS

No equivalent FIRST

No equivalent GREATEST or GREATEST_LB

No equivalent HEXTORAW()

No equivalent INITCAP()

No equivalent LAST

No equivalent LAST_DAY

No equivalent LEAST or LEAST_UB

No equivalent LEVEL

No equivalent LPAD

No equivalent MONTHS_BETWEEN

No equivalent nested RECORD

No equivalent NEW_TIME

No equivalent NEXT

No equivalent NEXT_DAY

No equivalent NEXTVAL

No equivalent NLSSORT

No equivalent PRINT ...

No equivalent PRIOR

No equivalent ROUND(date)

No equivalent RPAD()

No equivalent SINH()

No equivalent SQL%FOUND

No equivalent SQL%NOTFOUND

Get DIAGNOSTIC <varname> = ROWCOUNT SQL%ROWCOUNT

No equivalent TANH()

No equivalent CONVERT()

DB2 Oracle

54 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 71: Store Procedure

2.7.6 Comparison with Informix SPLTable 7 shows the SQL/PSM (standard) control statements and Informix SPLcontrol statements.

Table 7. Comparison between SQL/PSM and SPL control statements

SQL/PSM control statements Informix SPL control statements

CALL CALLEXECUTE

result set processing after a CALL statement No equivalent

LEAVE <procedure-body-name> RETURN

BEGIN (Compound statements)END

BEGINEND

Handler declaration ON EXCEPTION (but differences)

Condition declaration No equivalent

SQL variable declarationdeclare <var-name> <datatype> default <defvalue>

define <var-name> <datatype>

Assignement declarationSET <var-name> = <expression>

LET <var-name> = <expression>

IF <expression> THEN ...ELSEIF...THEN ...ELSE...END IF;

IF <expression> THEN..ELIF...THEN...ELSE...END IF;

CASE statement No equivalent

LEAVE statement EXIt <loop-type>

LOOP No equivalent

WHILE statement WHILE statementorFOR <indx-name> IN <criteria> .... END FOR

REPEAT No equivalent

FOR statement FOREACH <cursor-name> FOR <select-stmt>....END FOREACH

SIGNAL <sqlstate> statement RAISE EXCEPTION <error-number>

RESIGNAL statement RAISE

ITERATE CONTINUE

No equivalent SYSTEM

No equivalent goto <label>

The SQL Procedures language 55

Page 72: Store Procedure

56 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 73: Store Procedure

Chapter 3. The DB2 Stored Procedure Builder

This chapter describes the new DB2 Stored Procedure Builder (SPB) tool, andexplains how it can be used to help with the development and maintenance ofstored procedures for both DB2 for OS/390 and DB2 Universal Database (UDB)environments.

3.1 DB2 Stored Procedure Builder — overview

This section describes the DB2 SPB, its main components, prerequisites,installation, and customization.

3.1.1 What is it?The DB2 SPB is a graphical tool designed to help with the development of DB2stored procedures. It provides all the functions required to create, build, test, anddeploy new stored procedures. It also provides functions to work with existingstored procedures.

The SPB provides a single development environment that supports the entireDB2 family ranging from the workstation to System/390. Figure 5 shows theenvironment for development and deploy stored procedures with SPB. With theSPB you can focus on the logic of your stored procedure rather than on theprocess details of creating stored procedures on a DB2 server.

Figure 5. SPB environment

The SPB supports two languages for the development of new stored procedures:Java, and SQL Procedures language.

It is important to notice that the SPB is not a prerequisite to write storedprocedures for DB2 servers. The support for stored procedures, even for the SQLProcedures language, is built-in to the DB2 base code. For more details on thenew SQL Procedures language, refer to Chapter 2, “The SQL Procedureslanguage” on page 9. For details on the implementation of SQL storedprocedures in different DB2 servers, refer to Chapter 4, “SQL Procedures for DB2UDB for OS/390” on page 109, Chapter 5, “SQL Procedures for DB2 UDB forUNIX, Windows, OS/2” on page 145, and Chapter 6, “SQL Procedures for DB2UDB for AS/400” on page 169.

D eve lop D ep loy

D B 2S erver

N T ,95 ,98 ,A IX , S olarisO S /2...O S /39 0

N T ,95 ,9 8 F ro m :M icroso ft V isua l Bas icM icroso ft V isua l S tud ioS tand-a lone

IB M V isua lA ge fo r Java

jd bc

© Copyright IBM Corp. 1999 57

Page 74: Store Procedure

In summary, using the SPB you can perform a variety of tasks associated withstored procedures, such as:

• Creating new stored procedures

• Listing existing stored procedures

• Modifying existing stored procedures (Java and SQL stored procedures)

• Running existing stored procedures

• Copying and pasting stored procedures across connections

• One-step building of stored procedures on target databases

• Customizing the settings to enable remote debugging of installed storedprocedures

3.1.2 Programming languages supportedThe SPB supports both Java and SQL Procedures languages to create, build,and debug stored procedures on DB2 UDB servers. For Java stored procedures,SPB allows the use of both supported Java interfaces: JDBC and SQLJ. The maindifference between JDBC and SQLJ is that JDBC stored procedures execute as adynamic SQL program, while SQLJ stored procedures execute as a static SQLprogram.

Following are examples of the same stored procedure written in SQL Procedureslanguage, Java with JDBC, and Java with SQLJ.

Procedure STP using SQL Procedures language:

CREATE PROCEDURE DRDARES1.STP ( IN v_id int )SPECIFIC DRDARES1.S5521448RESULT SETS 1LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.STP------------------------------------------------------------------------P1: BEGIN

-- Declare cursorDECLARE cursor1 CURSOR WITH RETURN FOR

SELECTDRDARES1.STAFF.ID,DRDARES1.STAFF.NAME,DRDARES1.STAFF.DEPT,DRDARES1.STAFF.JOB,DRDARES1.STAFF.YEARS,DRDARES1.STAFF.SALARY,DRDARES1.STAFF.COMM

FROMDRDARES1.STAFF

WHERE(

(DRDARES1.STAFF.ID > v_id

));

-- Cursor left open for client applicationOPEN cursor1;

58 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 75: Store Procedure

END P1

Procedure STP using JDBC:

/*** JDBC Stored Procedure DRDARES1.STP*/import java.sql.*; // JDBC classes

public class STP{

public static void sTP ( short v_id,ResultSet[] rs ) throws SQLException, Exception

{// Get connection to the databaseConnection con =

DriverManager.getConnection("jdbc:default:connection");PreparedStatement stmt = null;String sql;

sql = "SELECT"+ " DRDARES1.STAFF.ID,"+ " DRDARES1.STAFF.NAME,"+ " DRDARES1.STAFF.DEPT,"+ " DRDARES1.STAFF.JOB,"+ " DRDARES1.STAFF.YEARS,"+ " DRDARES1.STAFF.SALARY,"+ " DRDARES1.STAFF.COMM"+ " FROM"+ " DRDARES1.STAFF"+ " WHERE"+ " ("+ " ( "+ " DRDARES1.STAFF.ID > ? "+ " )"+ " )";

stmt = con.prepareStatement( sql );stmt.setShort( 1, v_id );rs[0] = stmt.executeQuery();if (con != null) con.close();

}}

Procedure STP using SQLJ:

/*** SQLJ Stored Procedure DRDARES1.STP*/import java.sql.*; // JDBC classesimport sqlj.runtime.*;import sqlj.runtime.ref.*;

#sql iterator Stp_Cursor1 ( short, String, short, String, short,java.math.BigDecimal, java.math.BigDecimal );

public class Stp{

public static void stp ( short v_id,

The DB2 Stored Procedure Builder 59

Page 76: Store Procedure

ResultSet[] rs ) throws SQLException,Exception

{Stp_Cursor1 cursor1 = null;#sql cursor1 ={

SELECTDRDARES1.STAFF.ID,DRDARES1.STAFF.NAME,DRDARES1.STAFF.DEPT,DRDARES1.STAFF.JOB,DRDARES1.STAFF.YEARS,DRDARES1.STAFF.SALARY,DRDARES1.STAFF.COMM

FROMDRDARES1.STAFF

WHERE(

(DRDARES1.STAFF.ID > :v_id

))

};rs[0] = cursor1.getResultSet();

}}

Note: For DB2 for OS/390 servers, SPB supports only the SQL Procedureslanguage. SPB does not yet support Java stored procedures for DB2 for OS/390,and it does not yet support SQL Procedures for DB2 UDB for AS/400.

Existing stored procedures written in any supported language, and registered inthe DB2 server, are also listed. However, stored procedures written in otherlanguages can only be executed from SPB. You will not be able to modify, build,get source for, or debug these procedures.

3.2 Product Installation on Windows NT

The following sections describe the prerequisites and the steps required to installSPN in the Windows NT environment.

3.2.1 Prerequisites for SPBThere are a few requirements to run the SPB in your workstation. If you plan todevelop stored procedures for remote DB2 servers, you have to define theconnection to the server. To access DB2 UDB servers, you only need to catalogthe remote database in your workstation.

To access a DRDA server (only DB2 for OS/390 is supported at this time), youneed to install the DB2 Connect product in your workstation or in a gateway, andcatalog the remote database. To work with SPB and DB2 Server for OS/390Version 5, you must also ensure that APARs PQ29866, PQ24199, and PQ29706are installed in your system.

60 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 77: Store Procedure

SPB is implemented in Java, and all database connections are managed by usingJava Database Connectivity (JDBC). To write stored procedures with SPB, youonly need to be able to connect to a local or remote DB2 database alias.

3.2.2 Installing the SPBThe SPB is included with the DB2 Software Developer’s Kit (SDK) and isavailable for the Windows 95, 98, and NT environments. The DB2 SDK isincluded with DB2 UDB server editions (Workgroup Edition, Enterprise Edition,and Enterprise-Extended Edition), DB2 Developers editions (Personal Edition,and Universal Edition), and DB2 Connect. You can install SDK together with DB2UDB server or in a separate client workstation.

DB2 for OS/390 users can also get the SPB from the DB2 Management ToolsPackage.

Although the SPB executes only in Windows systems, it can be used to developstored procedures for any DB2 UDB platform and for DB2 for OS/390. Support forthe development of DB2 UDB for AS/400 stored procedures should be availablesoon.

If you are using SPB to develop stored procedures for a DB2 UDB server, beforeyou run SPB, you must configure the DB2 UDB server in the following ways:

• Set the path for the Java Development Kit (JDK) by entering the followingcommand from the DB2 Command Window:

DB2 UPDATE DATABASE MANAGER CONFIGURATION USING JDK11_PATHx:\sqllib\java\jdk

where x: is the drive on which you installed DB2 UDB

• We recommend that you set the Java heap size to 4096 bytes. From the DB2Command Window, enter the following command:

DB2 UPDATE DATABASE MANAGER CONFIGURATION USING JAVA_HEAP_SZ 4096

• We recommend that you set the application heap size to 1024 bytes. From theDB2 Command Window, enter the following command:

DB2 UPDATE DATABASE MANAGER CONFIGURATION FOR database_name USINGAPPLEHEAPSZ 1024

• Set the DB2 parameter KEEPDARI to NO if you are frequently rebuilding andtesting stored procedures. In the DB2 Command Window, enter the followingcommand:

DB2 UPDATE DATABASE MANAGER CONFIGURATION USING KEEPDARI NO

For these configuration settings described above, you must stop and restart thedatabase server before the new settings will take effect.

If you are planning to use SPB to develop stored procedures for a DB2 for OS/390server, see Chapter 4, “SQL Procedures for DB2 UDB for OS/390” on page 109for detailed information.

When you install the SDK in your machine, a path to SPB is automaticallyincluded in the DB2 UDB program group. You can launch the SPB from the DB2UDB program group, or you can launch SPB as an add-in tool from any of thefollowing applications:

The DB2 Stored Procedure Builder 61

Page 78: Store Procedure

• IBM VisualAge for Java

• Microsoft Visual Studio Version 5 and Version 6

• Microsoft Visual Basic Version 5 and Version 6

3.2.2.1 Starting SPB from IBM VisualAge for JavaThe integration of SPB and VisualAge for Java that is currently available is:VisualAge for Java 3.0. The SPB that is integrated with VA Java 3.0 is the DB2UDB version 6 code base.

Follow the steps below to invoke the Stored Procedure Builder driver:

1. Right-click the VisualAge for Java project you want to use the StoredProcedure Builder with.

2. Select Tools from the menu.

3. Select IBM DB2 Stored Procedure Builder.

SPB projects save connection information and stored procedure objects thathave not yet been built to a database.

Figure 6 shows how to invoke the SPB through VA Java Workbench.

Figure 6. Invoking SPB through VisualAge for Java

If the SPB project file is NOT found in the VisualAge for Java that you use toinvoke SPB, then the "Specify Database Connection" dialog appears (Figure 7).

If the SPB project file is found in the VisualAge for Java that you use to invokeSPB, then the "Specify Database Connection" does not appear (since we use the

62 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 79: Store Procedure

connection information stored in the SPB project file found in the VA Javaproject).

Figure 7. Specify Database Connection Window

The SPB main frame is displayed once you have specified the connectioninformation (see Figure 8).

The DB2 Stored Procedure Builder 63

Page 80: Store Procedure

Figure 8. SPB main frame invoked through VA Java Workbench

3.2.2.2 Starting SPB from Microsoft Visual StudioIf Microsoft Visual Studio was not installed when you installed DB2 SDK, youmust perform one of the following steps to register the add-in with Visual Studio. IfMicrosoft Visual Studio was installed when you installed DB2 SDK, you shouldskip these steps.

• If you have Visual Studio 5, copy the file DB2SSPB.DLL from the directoryx:\sqllib\bin to y:\Program Files\DevStudio\SharedIDE\AddIn, where x: is thedrive on which you have installed DB2 SDK, and y: is the drive on which youhave installed Visual Studio 5.

• If you have Visual Studio 6, copy the file DB2SPBVS.DLL from the directoryx:\sqllib\bin to y:\Program Files\Microsoft Visual Studio\Common\MSDev98\AddIns, where x: is the drive on which you have installed DB2 SDK,and y: is the drive on which you have installed Visual Studio 6.

To launch SPB from Microsoft Visual Studio, you have to enable the SPB add-in.This can be done using the following steps:

1. From the main Visual Studio window select Tools --> Customize... The popupwindow showed in Figure 9 is displayed.

64 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 81: Store Procedure

Figure 9. Customizing Microsoft Visual Studio

2. Select the Add-ins and Macro Files tab, and click on the check box near theIBM DB2 Stored Procedure Builder add-in. Close the window.

You should now have a fast path for SPB in your Microsoft Visual Studio desktop.

3.2.2.3 Starting SPB from Microsoft Visual BasicIf Microsoft Visual Basic was not installed when you installed DB2 SDK, you mustperform the following steps to register the add-in with Visual Basic:

1. Open a DOS command prompt and change to the directory x:\sqllib\bin, wherex: is the drive on which you have installed DB2 SDK.

2. Enter the following command:

db2spbvb -addtoini

To launch SPB from Microsoft Visual Basic, you have to enable the SPB add-in.This can be done using the following steps:

1. Select Add-Ins --> Add-In Manager. The Add-In Manager window opens.

2. Select IBM DB2 Stored Procedure Builder and click OK.

The SPB is added to the Add-Ins menu.

3.3 Advanced configuring of the SPB

You can customize your SPB environment by using a Windows initialization (INI)file. SPB uses the DB2SPB.INI file to save information about your preferencesand environment. The DB2SPB.INI file is located in the SPB subdirectoryx:\sqllib\spb, where x: is the drive on which you have installed DB2 SDK.

You need to edit the DB2SPB.INI file to change stored procedure option defaults.You can also use the Environment Properties notebook in SPB to change allother defaults.

The DB2 Stored Procedure Builder 65

Page 82: Store Procedure

3.3.0.1 The DB2SPB.INI fileThe DB2SPB.INI file contains several sections marked by a section namesurrounded by brackets ([]). The entries in each section contain keynames andtheir associated values. Following is an example of the DB2SPB.INI file we usedin our project:)

[IBM DB2 Stored Procedure Builder 2.1.0b] (1) (see Figure 10)ENABLE_STDERR_CONSOLE = FALSEBUILD_KEEP_TMPDIR_AFTER_FAILURE = FALSE

[Previous projects]--------- (see Figure 11)MRU_FILE1 = D:\SQLLIB\spb\projects\sg245485.sppMRU_FILE0 = D:\SQLLIB\spb\projects\sueli.spp

[Debug information]--------- (see Figure 16)DEBUG_PORT = 8000DEBUG_IPADDR = 9.1.151.109

[Logon information]--------- (see Figure 12)DEFAULT_JDBC_CLASS = COM.ibm.db2.jdbc.app.DB2DriverDEFAULT_JDBC_DRIVER = 378DEFAULT_JDBC_DATABASE = SAMPLEDEFAULT_JDBC_URL = jdbc:db2:SAMPLE

[Data type preferences]----- (see Figure 18 and Figure 19)TYPE_MAP_BYTES = 7TYPE_MAP_STRING_MAGNITUDE =TYPE_MAP_BYTES_LENGTH = 254TYPE_MAP_DEFAULT_LENGTH = 254TYPE_MAP_DEFAULT = 7TYPE_SYNONYM_7 = varcharTYPE_SYNONYM_6 = charTYPE_SYNONYM_4 = doubleTYPE_SYNONYM_2 = decTYPE_MAP_BYTES_MAGNITUDE = BTYPE_SYNONYM_1 = intTYPE_CASE = LOWERTYPE_MAP_DEFAULT_BITDATA = FALSETYPE_MAP_STRING_LENGTH = 254TYPE_MAP_STRING = 7

[Output preferences]----- (see Figure 15)OUTPUT_COMMIT_RUN = FALSEOUTPUT_MAX_ROWS =OUTPUT_MAX_COLWIDTH =OUTPUT_ALL_ROWS = TRUEOUTPUT_ALL_COLWIDTH = TRUEOUTPUT_STATEMENT_SEPARATOR = @

[User-assistance preferences]----- (see Figure 14)ASSISTANCE_BEEPS = TRUEASSISTANCE_WINDOW SIZE_WIDTH = 660ASSISTANCE_BORDERS = TRUEASSISTANCE_SPLIT_HORZ_LOCATION = 339ASSISTANCE_SPLIT_VERT_LOCATION = 163ASSISTANCE_WINDOW SIZE_HEIGHT = 350ASSISTANCE_TIPS = TRUEASSISTANCE_INFOPOPS = TRUE

66 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 83: Store Procedure

[Stored-procedure options] (2) (see Figure 17)SPOPTION_COMPILE_TEST_OPTION = NOTEST(block,noline,nopath)SPOPTION_WLM_ENVIRONMENT = wlmenv1SPOPTION_SQLPROC_BUILDER = DSNTPSMPSPOPTION_EXTERNAL_SECURITY = DB2SPOPTION_STAY_RESIDENT = FALSESPOPTION_LINK_OPTIONS =SPOPTION_LE_TEST_OPTION = NOTEST(ALL,*,,VADTCPIP&9.1.151.109:*)SPOPTION_COMPILE_OPTIONS = list,longnameSPOPTION_LE_OPTIONS =SPOPTION_TEST = FALSESPOPTION_COLLID = TESTSPOPTION_PRELINK_OPTIONS = nomapSPOPTION_PSM_PRECOMPILE = sourceSPOPTION_BIND_OPTIONS =

[Editor preferences]----- (see Figure 13)EDITOR_LINE_NUMBERS = TRUEEDITOR_FONT_SIZE = 12EDITOR_TAB_SIZE = 4EDITOR_LANGUAGE_PARSING = TRUE

The first section (1), IBM DB2 Stored procedure Builder 2.1.0b, is internal onlyand must not be modified.

The Stored Procedure Option (2) is for OS/390 only. Part of the information willbe externalized in a future release of SPB to facilitate updating via theEnvironment Properties dialog.

Figure 10 through Figure 19 show the various menus of the SBP.

Figure 10. Stored Procedure Builder

The DB2 Stored Procedure Builder 67

Page 84: Store Procedure

Figure 11. SPB: Previous Projects

Figure 12. Environment Properties: Connection

68 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 85: Store Procedure

Figure 13. Environment Properties: Editor

Figure 14. Environment Properties: Assistance

The DB2 Stored Procedure Builder 69

Page 86: Store Procedure

Figure 15. Environment Properties: Output

Figure 16. Environment Properties: Debug

70 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 87: Store Procedure

Figure 17. Environment Properties: OS/390 Options

Figure 18. Environment Properties: SQL Types

The DB2 Stored Procedure Builder 71

Page 88: Store Procedure

Figure 19. Environment Properties: Type Mapping

3.3.0.2 Entries in the DB2SPB.INI fileEach section of the DB2SPB.INI file contains keywords that affect the behavior ofSPB. Table 8 shows the keywords associated with each section, their possiblevalues, and a description of each keyword.

Table 8. DB2SPB.INI file sections and keywords

Section Keyname Possible Values Description

[Most recentlyused projects]

MRU_FILE<number> <project-file-name-with-absolute-path>

Specifies absolute path of an SPBproject file. The number appended tothe keyname represents how recentlythe file was used; for example,MRU_FILE0 is the most recentlyused file.

[Storedprocedureoptions]

SPOPTION_STAY_RESIDENT

TRUE | FALSE OS/390 only: Specifies whether thestored procedure load module remainsin memory when the stored procedureends

SPOPTION_EXTERNAL_SECURITY

DB2 | USER | DEFINER OS/390 only: Specifies the type ofexternal security environment for thestored procedure

SPOPTION_COLLID <collection-ID> | <user-ID> OS/390 only: Specifies the packagecollection used when the storedprocedure is executed

SPOPTION_LE_OPTIONS <Language-Environment-options>

OS/390 only: Specifies LanguageEnvironment run-time options

72 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 89: Store Procedure

SPOPTION_WLM_ENVIRONMENT

<Work-Load-Manager-environment>

OS/390 only: Specifies the MVSworkload manager (WLM)environment where the storedprocedure runs

SPOPTION_PSM_PRECOMPILE

<PSM-precompile-options>| CONNECT(1),DATE(LOC), DEC(31),FLAG(I), HOST(SQL),LINECOUNT(0),MARGINS(0), NOSOURCE,SQLFLAG(STD),TIME(LOC)

OS/390 only: Specifies precompilationoptions for building SQL storedprocedures on a DB2 for OS/390server

SPOPTION_TEST TRUE | FALSE Specifies whether or not to build theJava or SQL stored procedure fordebugging

[User-Assistancepreferences]

ASSISTANCE_INFOPOPS TRUE | FALSE Specifies whether pop-up help forinterface controls is on or off

ASSISTANCE_BEEPS TRUE | FALSE Specifies whether the system beep forinput constraint violations is on or off

ASSISTANCE_TIPS TRUE| FALSE Specifies whether pop-up informationfor fields with constraint checking areon or off

ASSISTANCE_BORDERS TRUE | FALSE Specifies whether the blue or redborder around constraint checkingfields is on or off

[Outputpreferences]

OUTPUT_ALL_COLWIDTH TRUE | FALSE Specifies whether all columns in astored procedure result set display

OUTPUT_ALL_ROWS TRUE | FALSE Specifies whether all rows in a storedprocedure result set display

OUTPUT_MAX_COLWIDTH

<maximum-column-width> |20

Specifies maximum number ofcharacters displayed per column in astored procedure result

OUTPUT_MAX_ROWS <maximum-row_count> | 10 Specifies maximum number of rowsdisplayed in a stored procedure result

[Debuginformation]

DEBUG_IPADDR <your-IP-address> Specifies IP address of the workstationon which SPB is installed

DEBUG_PORT <your-port> | 8000 Specifies port number which thedebugger can use to connect to theclient workstation

[Logoninformation]

DEFAULT_JDBC_DRIVER app | net | odbc | other Specifies the default driver used toestablish a database connection

DEFAULT_JDBC_DATABASE

<database-or-alias> |<first-alias>

Specifies the name of the databasewith which to establish a connection

DEFAULT_JDBC_HOST <host> | <empty> Specifies the host name of the DB2server

Section Keyname Possible Values Description

The DB2 Stored Procedure Builder 73

Page 90: Store Procedure

DEFAULT_JDBC_PORT <port> | <empty> Specifies the port defined by the DB2server

DEFAULT_JDBC_URL <connection-URL> |jdbc:db2:<first-alias>

Specifies the location path of thedatabase

DEFAULT_JDBC_CLASS <driver-class> |COM.ibm.db2.jdbc.app.DB2Driver

Specifies the driver class associatedwith the chosen driver

[Data typepreferences]

TYPE_SYNONYM_7 varchar | char varying |character varying

Specifies default synonym for SQLdata type varchar

TYPE_SYNONYM_6 char | character Specifies default synonym for SQLdata type char

TYPE_SYNONYM_4 double | double precision Specifies default synonym for SQLdata type double

TYPE_SYNONYM_2 decimal | dec | numeric |num

Specifies default synonym for SQLdata type dec

TYPE_SYNONYM_1 int | integer Specifies default synonym for SQLdata type int

TYPE_CASE INITIAL | UPPER | LOWER Specifies default type case settings forSQL data type names

TYPE_MAP_STRING 6 | 7 | 8 | 9 | 10 | 11 | 12 | 132 Specifies default SQL type mapped tothe Java type string

TYPE_MAP_STRING_LENGTH

<length> | 256 Specifies default SQL type length forthe Java type string

TYPE_MAP_STRING_MAGNITUDE

B | K | M | G3 Specifies default SQL type unit size forthe Java type string

TYPE_MAP_BYTES 6 | 7 | 8 | 172 Specifies the default SQL typemapped to the Java type string

TYPE_MAP_BYTES_LENGTH

<length> | 256 Specifies default SQL type length forthe Java type byte

TYPE_MAP_BYTES_MAGNITUDE

B | K | M | G3 Specifies default SQL type unit size forthe Java type byte

TYPE_MAP_DECIMAL_PRECISION

<precision> | 5 Specifies the default precision for theSQL type mapped to Java typedecimal

TYPE_MAP_DECIMAL_SCALE

<scale> | 0 Specifies the default scale for the SQLtype mapped to Java type decimal

TYPE_MAP_DEFAULT 6 | 7 | 8 | 9 | 10 | 11 | 12 | 132 Specifies default SQL type mapped tounknown Java and JDBC types (forSQL written outside of SQL Assistant)

TYPE_MAP_DEFAULT_LENGTH

<length> | 256 Specifies default SQL type length

TYPE_MAP_DEFAULT_MAGNITUDE

B | K | M | G3 Specifies default SQL type unit size

Section Keyname Possible Values Description

74 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 91: Store Procedure

3.3.1 Concepts and terminologySPB uses some terms to define objects and operations related to the creationand maintenance of stored procedures. Following are some of the most importantterms associated with SPB objects and operations:

3.3.1.1 ProjectWhen using SPB, you must create a project. A project stores the connectioninformation to the databases you are accessing and stored procedures sourcesthat have not been build to the DB2 server. The connections information specifiedin the project file is used for all the functions performed by SPB.

3.3.1.2 CreateThe create function is associated with the creation of new stored proceduresusing the New Stored Procedures SmartGuide. At the end of the creation of thestored procedure you can choose to generate the stored procedure, or togenerate and build the stored procedure.

3.3.1.3 GenerateThe process of generating a new stored procedure is started by the New StoredProcedures SmartGuide. The generate option creates a base skeleton for yourstored procedure based on the information provided through the SmartGuide.Note that the generate function runs locally and does not include any informationabout the stored procedure on the DB2 server, that is, the source code isgenerated in memory.

TYPE_MAP_DEFAULT_PRECISION

<precision> | 5 Specifies the default precision for theSQL type mapped to unknown Javaand JDBC types

TYPE_MAP_DEFAULT_MAGNITUDE

B | K | M | G3 Specifies default SQL type unit size

TYPE_MAP_DEFAULT_PRECISION

<precision> | 5 Specifies the default precision for theSQL type mapped to unknown Javaand JDBC types

TYPE_MAP_DEFAULT_SCALE

<scale> | 0 Specifies the default scale for the SQLtype mapped to unknown Java andJDBC types

TYPE_MAP_DEFAULT_BITDATA

TRUE | FALSE Specifies whether SQL types use thebit data subtype for character strings

[Editor] EDITOR_TAB_SIZE <width> | 4 Specifies the default tab width incharacter spaces

EDITOR_FONT_SIZE <size> | 12 Specifies the default font size in points

EDITOR_LINE_NUMBERS TRUE | FALSE Specifies whether line number displayis on or off

EDITOR_LANGUAGE_PARSING

TRUE | FALSE Specifies whether color-coded text ison or off

Section Keyname Possible Values Description

The DB2 Stored Procedure Builder 75

Page 92: Store Procedure

If the stored procedure is in Java, the Build action compiles the source in localtemporary directories, creates a jar file to contain the executables, and then callsthe sqlj_install.jar() utility to add the jar file to the server. When developing SQLstored procedures, the source is generated in local memory, and the CREATEPROCEDURE statement is compiled and processed on the server.

3.3.1.4 BuildThe build function is responsible for performing all the tasks necessary to createand register the stored procedure on the DB2 server. Only when you build thestored procedure does it become available for use at the DB2 server.

3.3.1.5 RegisterInserting the row for a stored procedure into the DB2 table for stored procedures,along with the associated parameters of those stored procedures.

3.3.1.6 RunAfter building the stored procedure, the SPB allows you to execute the storedprocedure without writing a client program. The run function invokes the storedprocedure on the DB2 server, prompts for parameters, and display the results ofthe stored procedure. You can use the run function to execute any storedprocedure registered at the DB2 server, regardless of the language of the storedprocedure.

3.3.1.7 Get SourceStored procedures written in Java or SQL Procedures language have their sourcecodes stored at the DB2 server in control tables. When working with SPB, youcan request the stored procedure source code from the DB2 server by using theget source function.

With DB2 UDB, procedures written in SQL Procedures language always havetheir source stored in the DB2 tables, even if they were created outside SPB,however, Java procedures created outside SPB may not have their sourcesstored in the DB2 tables. In this case, if the procedures were registered withLANGUAGE JAVA and PARAMETER STYLE JAVA, when SPB cannot find thesource code in the DB2 tables, a popup window is displayed and you canassociate a file with the Java procedure source code, and this source code will bestored by SPB in the DB2 tables.

With DB2 for OS/390, your SQL stored procedures may not have their sourcecodes in DB2 tables if they were not created using SPB. In this case, when SPBcannot find the source code in the DB2 tables, a popup window is displayed andyou can associate a file with the SQL stored procedures source code, and thissource code will be stored by SPB in the DB2 tables. The file with the sourcecode must be downloaded from the mainframe, and has to reside on a disk thatcan be accessed by SPB.

3.3.1.8 ModifyOnce you have the stored procedures source code available in SPB, you canchange the stored procedure using the stored procedures editor, or the SPBassistants, such as the SQL Assistant. You can only modify stored procedureswritten in Java or SQL Procedures language.

76 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 93: Store Procedure

3.3.1.9 Dirty ProceduresA dirty procedure is indicated in SPB by having its name in bold. A storedprocedure is considered dirty if you have made modifications to the storedprocedures source code that have not been built back to the DB2 server.

3.3.1.10 Database ConnectionSPB can be used to develop stored procedures to access many servers. Within aproject, you can have different database connections to the DB2 servers beingaccessed.

3.3.2 What are its components?The SPB has many components to help you create, build, and debug your storedprocedures. The SPB main panel, shown in Figure 20, provides icons and fastpaths to other components.

Figure 20. SPB main panel

Following is a description of the main components of SPB.

3.3.2.1 New Stored Procedure SmartGuideThe New Stored Procedures SmartGuide is a graphical user interface that helpsyou to create a new stored procedure written in Java or SQL Procedureslanguage. The SmartGuide helps you to specify the name, the general pattern forthe source code, the query to run, the SQL data types for the parameters, and thebuild options for a new stored procedure.

The DB2 Stored Procedure Builder 77

Page 94: Store Procedure

You can start the New Stored Procedures SmartGuide by clicking on the InsertJava Procedure icon or the Insert SQL Procedure icon. You can also start theSmartGuide by right-clicking the entry Stored Procedures, in the tree-view, andchoosing Insert Java Stored Procedure or Insert SQL Stored Procedure.Figure 21 shows the initial window of the New Stored Procedures SmartGuide.

Figure 21. The New Stored Procedures SmartGuide

The SmartGuide has many features to help you build your stored procedure:

• Field Sensitive Help: You can click on any object in the SmartGuide windowsand press F1. Help information and tips are presented in a yellow box near theobject.

• Smart Fields: Whenever you need to type information in the SmartGuide,smart input fields will help you. If the border is blue, the field is selected andcontains valid information. If the border turns red, the SmartGuide has found aproblem with your input. When a problem is detected, a grey popup messageappears showing the error. If you press F1, a tip with a possible solution isdisplayed.

3.3.2.2 The SQL AssistantThe SQL Assistant is a SmartGuide that steps you through the processing ofcreating SQL statements. You can select tables on which to run queries, jointables, enter conditions and columns, determine how to sort the result, anddisplay the SQL statement so that you can copy or test the SQL query. In SQLAssistant, the tables that you can view and build queries from are listed from thecatalog tables of the current database alias.

78 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 95: Store Procedure

The SQL Assistant can be invoked from the editor, or from the New StoredProcedure SmartGuide dialogs. Figure 22 shows the first window of the SQLAssistant.

Figure 22. SQL Assistant window

3.3.2.3 Client Configuration AssistantThe DB2 Client Configuration Assistant SmartGuide can be invoked from SPB tocatalog new databases, if necessary. During the creation of a new project orwhen inserting a new database connection, if you click on the Create... buttonnear the database alias pulldown, the Client Configuration Assistant is started.

3.3.2.4 IBM Distributed DebuggerThe IBM Distributed Debugger, also referred as VisualAge Remote Debugger, isthe client debugger application running on your workstation that allows you toremotely debug a stored procedure executing on the server. The client debuggermust be connected to the debugger backend on the DB2 server. You can debugstored procedures written in Java or SQL Procedures language executing on DB2servers on Windows NT, AIX, or OS/390. Other platforms will be added in thefuture for remote debugging.

3.3.3 Working with SPB projectsSPB manages the work by using projects. A project stores the information aboutthe databases you are working and also stored procedures that have not yet beenbuilt into the DB2 server. A project can contain many connections to different DB2databases or servers; each of these databases can contain many storedprocedures. Figure 23 shows the relationships among projects, connections, andstored procedures.

The DB2 Stored Procedure Builder 79

Page 96: Store Procedure

The SPB does not control concurrent access on a project file and/or storedprocedures. You must be careful when many developers are working with thesame databases, to avoid unintentional destruction of stored procedures orchanges.

Figure 23. SPB projects (*.spp), connections and stored procedures

When SPB starts, it prompts you to either create a new project, or work with anexisting project. The following sections describe how to create and manage SPBprojects.

3.3.3.1 Creating Stored Procedure Builder projectsThe first thing you have to do when working with SPB is to specify your project.You can open an existing project or create a new one. When creating a newproject, you have to provide some initial information about the project, such asthe project name, and the database being accessed. Figure 24 shows the NewProject window used to create a new project.

Project (proj.spp)

Connection 1Database DB2Aspjdbc1

spsqlj2

spsqlp3

spcobol4

Connection 2Database DB2B

Stored Procedures

80 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 97: Store Procedure

Figure 24. Creating new project "ITSO SG245485"

Note the following items in Figure 24:

1. Project name. This is the name of your new project. The project name can beup to 256 characters, and can contain any alphanumeric character and theunderscore ’_’ character. If you violate any of these rules, when you click OK,a popup window with an error message is displayed. SPB will save yourproject in a file with extension .spp and the same name as the project. This.spp file is created in the project path.

2. Project path. The project path defines the location of your project in yourworkstation or in a shared disk. By default, the project path points tox:\sqllib\spb\projects, where x: is the drive on which you have installed DB2SDK.

3. Driver. Select the appropriate driver for your connection to the database onwhich you want to build stored procedures. When you install the DB2 SDK, thefollowing IBM DB2 drivers are installed on your workstation. When you selectone of these drivers for a new SPB project, the JDBC URL and driver class areautomatically entered for you. In this release of the product, only the followingdriver is supported:

• IBM DB2 alias — When the DB2 database to which you want to connect isdefined as an alias in your DB2 database client, select the IBM DB2 aliasdriver. When you use the IBM DB2 alias driver, you do not need to enterthe host name and port for the DB2 database in SPB. By default, SPBselects the IBM DB2 alias driver for a connection. You may also click on theCreate pushbutton; this will invoke the DB2 Client Configuration Assistant,and allow you to create a new alias to a database.

1 - Creating new project "ITSO SG245485"

23

4

5

6

7

The DB2 Stored Procedure Builder 81

Page 98: Store Procedure

4. Alias. Select the database alias you plan to use. You may also click on theCreate pushbutton; this will invoke the DB2 Client Configuration Assistant,and allow you to create a new alias to a database. After you create yourproject, you will be able to insert connections to other databases, in the sameproject, by using the Insert Connection dialog.

5. Userid and Password. Type the userid and password for accessing the DB2server database. For security reasons, even if you specify your password here,whenever you open your project, you will be prompted for the password toaccess remote DB2 servers.

6. Use your current user ID and password check box. Select this if you want touse the current window userid and password to connect to the DB2 server.

7. Filter. If the database you are connecting to contains a large number ofexisting stored procedures and you want to limit the stored proceduresdisplayed in the tree view, you may click on the Filter... pushbutton. You willbe able to filter the procedures displayed using the name, the schema, or thecollection id (OS/390 only) of the stored procedure.

3.3.3.2 Managing SPB projectsAfter creating your SPB projects you are ready to start working with SPB. Youmay change your project properties such as name and description using theProject Properties dialog clicking on File --> Project Properties. You cannotchange the path of you project.

When you first create your project, only one database connection is defined. Youmay however, define other connections using the Insert Connection dialog. Ifyou right-click on the connection at any time, you will also be able to delete,refresh, filter, or change properties of your connections.

A good practice is to refresh your connections periodically to check changes thatother users of the database might have made.

You can save your project at any time you want. If you have made changes tostored procedures, but have not built them to the database, the changes aresaved with your project, so you can continue working with them later.

Note: Other developers working in different projects with connections to the samedatabase will not be able to see your changes until you build them to thedatabase.

3.3.3.3 Sharing SPB projectsThe way that SPB currently works is not suitable for a team developmentenvironment. The current version of SPB does not control concurrence in projectsand does not provide check-in/check-out mechanisms, versioning, or any otherfeature to control accesses in your project.

Saving a project in a shared disk is possible, and may be helpful when more thanone developer wants to copy a project with changes from another developer.However, you should not have one project file being used by many developers,since this may lead to unintentional destruction of changes not built into thedatabase.

When sharing SPB projects, it is important to have the same database aliasespointing to the same database servers in all the developers’ workstations.

82 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 99: Store Procedure

3.4 Using the Stored Procedure Builder

The SPB provides you a single development environment for your storedprocedures. You will be able to perform all tasks related to the creation andmaintenance of stored procedures in both DB2 for OS/390 and DB2 UDB servers.In the future, SPB will also work with DB2 UDB for AS/400, but not in the currentversion.

3.4.1 Viewing existing stored proceduresThe SPB allows you to view all the stored procedures that are registered in theDB2 server catalog tables for stored procedures. Regardless of the language inwhich the stored procedure was written, you can view the existing proceduresand parameters being passed; however, you can only get the source, modify, orrebuild existing stored procedures written in SQL Procedures language or Java.

Since only SQL stored procedures and Java stored procedures are mandatory tobe registered in the DB2 UDB catalog, it is possible that you have storedprocedures in other languages that will not be shown, because they were notregistered in the DB2 UDB catalog using the CREATE PROCEDURE statement.

When you create or open an SPB project, all the registered stored procedures inthe defined database connections are displayed in the SPB main window treeview. Figure 25 shows the tree view of existing stored procedures in SPB.

Figure 25. Tree view of existing stored procedures

Note that in the tree view, the stored procedures are not presented in alphabeticalorder, and also, the parameters are not shown. You can easily access detailedinformation on the existing stored procedures, such as parameter lists, specificname, and language, by double-clicking the folder Stored Procedures in the treeview. A detailed list of the stored procedures, in alphabetical order, is displayed in

The DB2 Stored Procedure Builder 83

Page 100: Store Procedure

the list view part of the SPB main window. Figure 26 shows the detailed view ofthe existing registered stored procedures.

Figure 26. Detailed view of existing stored procedures

If you have a large number of registered stored procedures, you can filter the listof the stored procedures to be displayed. To open the filter dialog, right-click onthe Stored Procedures folder in the tree view, and choose Filter, as shown inFigure 27.

Figure 27. Filtering the list of stored procedures

84 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 101: Store Procedure

The Filter dialog window is displayed, and you can filter the list of storedprocedures based on the name or the schema of the registered storedprocedures. You can filter using the complete name of the stored procedure orschema or just a substring of the name or schema. If you are using a substring,you can choose to list procedures that start or end with the substring, or thatcontains the substring. Figure 28 shows the Filter dialog window, and some ofthe filter options.

Figure 28. The Filter dialog window

3.4.2 Creating new stored proceduresUsing SPB, you can create new stored procedures in the SQL Procedures or Javalanguages. The New Stored Procedures SmartGuide helps you in creating thebase skeleton of the stored procedure, so you can later include your businesslogic in it. For DB2 for OS/390 servers, SPB can only create new SQL storedprocedures. Support for Java stored procedures for DB2 for OS/390 through SPBis not yet available.

To invoke the New Stored Procedures SmartGuide to create a new SQL storedprocedure, right click on the Stored Procedures folder, and choose Insert SQLStored Procedure, as shown in Figure 29. You can also click on the Insert SQLProcedure icon in the SPB toolbar.

The DB2 Stored Procedure Builder 85

Page 102: Store Procedure

Figure 29. Creating a new SQL stored procedure

The New Stored Procedures SmartGuide guides you through 5 steps to createyour stored procedure, as follows:

1. Name: In this step, you provide the name of the new stored procedure.

2. Pattern: In this step, you provide the characteristics that describe the patternof your stored procedure, such as, if your stored procedure returns a resultset, or if your stored procedure runs a single SQL.

3. SQL Query: In this step, you can type one SQL query to be run by your storedprocedure. If in the Pattern panel, you have chosen Run one query from aset of queries, you can specify multiple queries in the SQL Query panel.From the SQL Query panel, you can also invoke the SQL AssistantSmartGuide to help you build your query, by clicking on the Define SQLbutton.

4. Parameters: In this step, you provide the parameters and associateddatatypes being passed to or from your stored procedure. This step isoptional, and if your stored procedures do not expect parameters, you mayskip this panel.

5. Options: In this panel, you specify options for generating the basic skeleton ofyou SQL stored procedure, and for building your stored procedure at the DB2server.

3.4.2.1 The New Stored Procedures SmartGuideWhen you start the New Stored Procedures SmartGuide, the Name panelappears, as shown in Figure 30. In any panel of the SmartGuide, if you positionyour mouse cursor on any field, a popup window appears with more informationrelated to that field. This can be very helpful when you are in doubt of themeaning of the fields in a specific panel.

86 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 103: Store Procedure

Figure 30. The Name panel of the New Stored Procedures SmartGuide

When you are creating a new SQL stored procedure for a DB2 UDB server, thename of the stored procedure is presented already prefixed with your userid asthe schema name. If you are creating a new SQL stored procedure for a DB2 forOS/390 server, the name of the stored procedure is not prefixed, and the defaultschema SYSPROC is used. If you want, you can type a new entry or change theschema in the stored procedure name field.

After providing a name to your stored procedure, you can click on the Nextpushbutton. The Pattern panel is displayed, as shown in Figure 31.

The DB2 Stored Procedure Builder 87

Page 104: Store Procedure

Figure 31. The Pattern panel of the New Stored Procedures SmartGuide

The Pattern panel is divided into three sections: Query, Output, and Errors.

The Query section allows you to specify if your stored procedure executes onlyone query or a set of queries. If you specify that your stored procedure executesa set of queries, the SQL Query panel will allow multiple SQL statements to bedefined, and your skeleton source code will include a CASE statement and aninput parameter to select which SQL statement to run. If you specify that yourstored procedure executes a single query, only one SQL statement will beallowed in the SQL Query panel. However, even if you specify a single query,after the SQL stored procedure skeleton code is generated, you can modify it toinclude other SQL statements required for your stored procedure function.

In fact, usually stored procedures execute more than one SQL statementthroughout the procedure logic. For these cases, you can select the Run a singlequery radio button, and later modify your procedure to include the additionalstatements.

The Output section allows you to specify if your stored procedure returns a resultset to the calling application. If you select the Return a result set checkbox, aRESULT SETS 1 parameter is included in the CREATE PROCEDURE statementfor your stored procedure. If your stored procedure returns more than one resultset, you can change the numbers of result sets in the CREATE PROCEDUREstatement manually after the source code generation.

The Errors section allows you to specify how you want your stored procedure tohandle errors. For SQL stored procedures, the first option GenerateSQLEXCEPTION does not generate any code in the source, and if an SQL erroroccurs, the stored procedure will be terminated.

88 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 105: Store Procedure

The second option, Output arguments for SQLSTATE and SQLCODE, includesoutput parameters and a handler in your SQL stored procedure source code toprovide the client application with the values of SQLSTATE and SQLCODEvariables. SQL stored procedures can return SQLSTATE and SQLCODEinformation, but not SQLMESSAGE.

Following is an example of the code generated by this option:

CREATE PROCEDURE DRDARES1.PROC3 ( OUT SQLSTATE_OUT char(5),OUT SQLCODE_OUT int )

SPECIFIC DRDARES1.S1022844RESULT SETS 1LANGUAGE SQL

P1: BEGINDECLARE SQLSTATE CHAR(5) DEFAULT '00000';DECLARE SQLCODE INT DEFAULT 0;

-----------DECLARE EXIT HANDLER FOR SQLEXCEPTION

IF (1 = 1) THENSET SQLSTATE_OUT = SQLSTATE;SET SQLCODE_OUT = SQLCODE;

END IF;------------END P1

At the time we were writing this book, the above code would only work properlywith DB2 for OS/390 servers. In DB2 UDB, the values of SQLCODE andSQLSTATE variables are set after every statement, and in the above generatedexample, the IF and the SET statements would reset the original SQLCODE andSQLSTATE values. For more information on handling errors in SQL storedprocedures running on DB2 UDB, refer to Chapter 5, “SQL Procedures for DB2UDB for UNIX, Windows, OS/2” on page 145.

After choosing your options in the Pattern panel, when you click the Nextpushbutton, the SQL Query panel is displayed, as shown in Figure 32.

The DB2 Stored Procedure Builder 89

Page 106: Store Procedure

Figure 32. The SQL Query panel of the New Stored Procedures SmartGuide

The SQL Query panel allows you to create one or multiple SQL statements to beincluded in your SQL stored procedures code. You can type your SQL statementin the left area of the panel, or you can use the SQL Assistant SmartGuide. TheDefine SQL pushbutton invokes the SQL Assistant SmartGuide, that helps youto create SELECT, INSERT, UPDATE, and DELETE statements through dialogsthat access the DB2 catalog. For more information on the SQL AssistantSmartGuide, refer to “SQL Assistant” on page 94.

The Actual Costs pushbutton is only available when you are creating an SQLstored procedure for a DB2 for OS/390 server. After you define your SQLstatement, if you click the Actual Costs pushbutton, the stored procedureDSNWSPM is invoked at the DB2 for OS/390 server to evaluate the cost of yourSQL statement and the results are presented by SPB.

Click on the Next pushbutton, and the Parameters panel is displayed, as shownin Figure 33.

90 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 107: Store Procedure

Figure 33. The Parameters panel of the New Stored Procedures SmartGuide

In the Parameters panel, you define the parameters that are sent to, or receivedfrom, the SQL stored procedure. If you click on the Add pushbutton, the DefineParameter dialog is displayed, as shown in Figure 34.

Figure 34. The Define Parameter dialog

The DB2 Stored Procedure Builder 91

Page 108: Store Procedure

In the Define Parameter dialog, you specify the characteristics of your SQLstored procedure parameters. The parameter mode defines if a parameter isused as an input, output, or input/output for the stored procedure. In this dialog,you also define the name and SQL type of the parameter. The length, unit,precision, and scale fields are requested according to the SQL type of theparameter. You cannot use user defined datatypes as SQL types for SQL storedprocedures parameters.

The parameters you define in the Parameters panel are included in thegenerated CREATE PROCEDURE statement for the SQL stored procedure.Before generating the code for your SQL stored procedure, you can also change,delete, or change the order of the parameters in the Parameters panel. After thecode is generated, you can change the definition of your parameters by editingthe CREATE PROCEDURE statement.

After you define your stored procedure parameters, you can click on the Nextpushbutton to go to the last panel of the New Stored Procedures SmartGuide,the Options panel, as shown in Figure 35.

Figure 35. The Options panel of the New Stored Procedures SmartGuide

The Options panel allows you to specify options for generating and building yourstored procedure. The options available are different for DB2 for OS/390 and DB2UDB servers.

The Options panel displayed in Figure 35 is for DB2 UDB servers. For DB2 UDBservers, you may define the specific name of your SQL stored procedure. Thespecific name you type in the input field is included in the generated CREATEPROCEDURE statement.

92 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 109: Store Procedure

In the Completion area of the panel, you can specify if you want to generate thesource code and automatically build the procedure at the DB2 server, or if youwant only to generate the source code. In most cases, you should choose theGenerate only option, to add specific logic to your SQL stored procedure. Afterthe generation, you will be able to change the SQL stored procedure source toinclude your changes, and then build the procedure.

The Build the stored procedure for debugging checkbox should be selected ifyou want to use the IBM Distributed Debugger to debug your procedure. Whenselected, this option includes an entry in the DB2 UDB debugger table.

The Options panel for DB2 for OS/390 SQL stored procedures allows you tospecify the collection id and load module name for the SQL stored procedure inentry fields. For DB2 for OS/390, the Options panel also includes an Advancedoptions pushbutton. If you click on the Advanced pushbutton, the OS/390Options window is displayed, as shown in Figure 36 and Figure 37. In thiswindow, you can specify parameters used during the build process, that arepassed to the DSNTPSMP stored procedure in the mainframe.

Figure 36. The Advanced options for DB2 for OS/390 SQL stored procedures

The DB2 Stored Procedure Builder 93

Page 110: Store Procedure

Figure 37. The Advanced build options for DB2 for OS/390 SQL stored procedures

Note that in the OS/390 Options, you can also specify the name of the storedprocedure to be invoked for the build process in the Build name entry field. Bydefault, SPB invokes the DSNTPSMP REXX stored procedure, but you canchange this procedure for your installation, and specify the name of yourcustomized build procedure in the OS/390 options.

3.4.2.2 SQL AssistantThe SQL Assistant is a SmartGuide that steps you through the processing ofcreating SQL statements. You can select tables on which to run queries, jointables, enter conditions and columns, determine how to sort the result, anddisplay the SQL statement so that you can copy or test the SQL query.

You can invoke the SQL Assistant during the creation of a new storedprocedure, by clicking on the Define SQL pushbutton in the SQL Query panel ofthe New Stored Procedures SmartGuide. You can also invoke the SQLAssistant when modifying your stored procedure by clicking on the Insert SQLicon from the SPB toolbar.

The SQL Assistant guides you through a series of steps to create your SQLstatement. In the first step, you choose the type of SQL statement beinggenerated and the tables that are referenced by your statement, as shown inFigure 38.

94 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 111: Store Procedure

Figure 38. The Tables panel of the SQL Assistant

In the Tables panel of the SQL Assistant, you can choose if you want to generatea SELECT, INSERT, UPDATE, or DELETE statement. However, if you selectmore than one table from the list, the SQL Assistant only allows SELECTstatements to be generated. You can refine the list of tables being presented byusing the View schemas and the Filter tables pushbuttons.

After selecting the tables for your SQL statement, the Join panel of the SQLAssistant is displayed, as shown in Figure 39.

The DB2 Stored Procedure Builder 95

Page 112: Store Procedure

Figure 39. The Join panel of the SQL Assistant

In the Join panel, you can click on the columns on each table that are used tojoin the tables to highlight them. After that, you can click on the Join pushbuttonto create the join. By default, an inner join is created, but if you click on theOptions pushbutton, you can change the type of the join being created, as shownin Figure 40. In the Join properties panel, you can choose if you want to createan inner join, a left outer join, or a right outer join between the selected tables.

Figure 40. Changing the type of Join created by SQL Assistant

The next panel of the SQL Assistant is the Conditions panel. In this panel you canspecify search conditions that are included in the WHERE clause of your SQLstatement. The Conditions panel is shown in Figure 41.

96 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 113: Store Procedure

Figure 41. The Conditions panel of the SQL Assistant

In the Conditions panel, you can include search conditions based in any columnof any of the tables included in your SQL statement. Just select the table youwant to add the condition, click on the column name and operator you want tohighlight them. Then, in the Values section of the panel, type the search value foryour condition. To check the existing values for the column you are defining yourcondition, just click on the Find pushbutton below the Values section. If youwant, you can click on the Variables pushbutton to define a variable for yoursearch condition as shown in Figure 42.

Figure 42. Specifying a variable for a condition

You can define as many conditions as you want. To define new conditions for yourSQL statement, just click on the Find on another column pushbutton.

The next panel of the SQL Assistant is the Columns panel, as shown in Figure43.

The DB2 Stored Procedure Builder 97

Page 114: Store Procedure

Figure 43. The Columns panel of the SQL Assistant

In the Columns panel, just select the columns of each table that you want toinclude in your SQL statement, by highlighting the column name and then clickingon the Add pushbutton.

After selecting the columns for your SQL statement, you can specify one or morecolumns to be used to sort the output of your statement, using the Sort panel, asshown in Figure 44.

98 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 115: Store Procedure

Figure 44. The Sort panel of the SQL Assistant

In the Sort panel, you can select the columns of any of the referenced tables tobe used for sorting the output. The columns you select are included in theORDER BY clause of your SQL statement.

The last panel of the SQL Assistant is the SQL panel, as shown in Figure 45.

The DB2 Stored Procedure Builder 99

Page 116: Store Procedure

Figure 45. The SQL panel of the SQL Assistant

The SQL panel displays the generated SQL statement that will be included inyour stored procedure. If you click on the Finish pushbutton, the SQL Assistantends and the SQL statement is inserted in the stored procedure source code.Before closing the SQL Assistant, in the SQL panel you have three pushbuttonsthat you can use.

The Copy to clipboard pushbutton copies the generated SQL statement to theWindows clipboard, so you can paste it in any application that has access to theWindows clipboard. The Save SQL pushbutton saves the generated SQLstatement to a file in your hard disk. The Run SQL pushbutton allows you to testthe generated SQL statement, before inserting the statement in your SQL storedprocedure code.

If your SQL statement is expecting variables, when you click on the Run SQLpushbutton, you are prompted to enter the values for the variables, as shown inFigure 46.

100 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 117: Store Procedure

Figure 46. Entering values for variables in the SQL statement

Enter the values for the variables and click on Run SQL pushbutton again. Theresults of your SQL statement are displayed as shown in Figure 47. You can copythese results to the clipboard, or save them to a file if you want. Click on the OKpushbutton to return to the SQL panel of the SQL Assistant.

Figure 47. Displaying the results of the SQL Statement

3.4.3 Building stored proceduresThe process of building a stored procedure is different between DB2 for OS/390and DB2 UDB servers. SPB handles this difference and builds the storedprocedure according to the DB2 server being accessed.

For DB2 for OS/390 servers, the current version of SPB only supports creationand building of stored procedures written in the SQL Procedures language. Thebuild process of SPB, by default, invokes the OS/390 Procedure Processor,

The DB2 Stored Procedure Builder 101

Page 118: Store Procedure

which is a REXX stored procedure (DSNTPSMP), in the mainframe to build thenew or changed stored procedure. You can customize the DSNTPSMP procedureat the mainframe to better fit the needs of your environment, and change SPBparameters, so it will invoke your customized procedure instead of the defaultDSNTPSMP.

For DB2 UDB (Windows, UNIX), the build process invokes the commandprocessor of DB2 to build the new or changed procedure.

For DB2 UDB for AS/400, you cannot use SPB, however, if you have an localdatabase with tables defined with the same structure of your AS/400 database,you can create the procedure with SPB working with the local database. You canthen, save the stored procedure in a sequential file and upload it to AS/400. Thestored procedure can be built using AS/400 commands with minimum changes.That was what we did in this project. Refer to Chapter 6, “SQL Procedures forDB2 UDB for AS/400” on page 169 for detailed information about how to build anSQL stored procedure for DB2 UDB for AS/400.

In both cases, prior to building the stored procedure, SPB drops the existingversion of the stored procedure on the DB2 server.

The process of building an SQL stored procedure involves the creation of theexecutable file and the registration of the stored procedure at the DB2 server.

To create the executable file, both DB2 UDB and DB2 for OS/390 enginesgenerate an intermediate C source code that is precompiled, compiled, andlinked at the DB2 server. For more information refer to Chapter 4, “SQLProcedures for DB2 UDB for OS/390” on page 109, Chapter 5, “SQL Proceduresfor DB2 UDB for UNIX, Windows, OS/2” on page 145 and Chapter 6, “SQLProcedures for DB2 UDB for AS/400” on page 169.

3.4.4 Modifying existing stored proceduresUsing SPB you can easily modify SQL stored procedures already built in the DB2for OS/390 or DB2 UDB servers.

To modify an existing stored procedure, double-click on the name of the storedprocedure. SPB gets the SQL stored procedure source from the DB2 server andopens the edit window, as shown in Figure 48.

102 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 119: Store Procedure

Figure 48. Modifying an existing stored procedure

For DB2 UDB servers, the source of the SQL stored procedure is saved in theSYSIBM.SYSPROCEDURES table, regardless of the method used to create theprocedure. In this case, SPB always find the source code on the DB2 server anddisplays it for your modifications.

For DB2 for OS/390 servers, when you create your SQL stored procedure usingSPB, the source code is stored in the SYSIBM.SYSPSM table. However, if youdid not use the SPB to build your procedure, it is possible that the source code isnot stored in the server. In this case, when you try to get the source of your SQLstored procedure, SPB displays a window prompting you to specify a file, residingon your workstation, containing the source code.

After the source code is displayed in the edit window, you can type anymodifications you want to your stored procedure. The current version of the SPBeditor does not check the syntax of the statements you are including or changing.Syntax errors are only detected during the build process of the stored procedure.

Any changes you do to your stored procedure are not included in the DB2 serveruntil you build it again. While you are changing the SQL stored procedure, thename of the procedure is shown in bold characters in the tree view part of theSPB main window. In this case, the procedure is referred as a dirty procedure,meaning that the code you have in SPB is not the same as in the DB2 server.

If you make changes to your SQL stored procedures, and do not build theprocedure back to the DB2 server, when you close SPB you are prompted to saveyour changes locally, so you do not lose any of your modifications. Rememberthat other developers will not be able to see your changes until you build them tothe DB2 server, and that SPB does not control concurrent access to the sameSQL stored procedure.

The DB2 Stored Procedure Builder 103

Page 120: Store Procedure

3.4.5 Copying and pasting stored procedures across connectionsYou can copy your stored procedures from one DB2 server to another. SPBprovides a copy and paste facility to help you copy individual procedures. Infuture releases of SPB, an import/export utility for bulk copy of stored procedureswill be available.

To copy one SQL stored procedure to another DB2 server, you can right-click onthe procedure name in the tree view of SPB, and select Copy procedure asshown in Figure 49.

Figure 49. Copying one SQL stored procedure

When you click on Copy Procedure, SPB gets the source of the storedprocedure from the DB2 server tables, and copies the source to the SPBclipboard.

To copy the procedure to another DB2 server, in the SPB tree view, right click onthe Stored Procedures folder of the connection to the target DB2 server, asshown in Figure 50.

104 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 121: Store Procedure

Figure 50. Paste the stored procedure at the target server

When pasting the stored procedure at the target server, you have two options. Ifyou choose Paste Procedure, the procedure is created only in SPB but not onthe target DB2 server. In this case, you can change the stored procedure codebefore building it to the DB2 server. If you do not plan to change the storedprocedure, you can select Paste and Build Procedure, that copies theprocedure and builds it to the DB2 server without any changes to the originalsource code.

3.4.6 Debugging stored proceduresThe DB2 SPB can help you to debug your SQL stored procedures. The IBMDistributed Debugger is shipped with DB2 SDK, and can be used to debug SQLstored procedures.

There are a few tasks to perform at both the DB2 server and client workstations.If you plan to debug your stored procedure, it has to be prepared with parametersthat will trigger the debugging process during the execution of the storedprocedure. The steps to prepare the SQL stored procedure at the DB2 server fordebugging are different for DB2 UDB and DB2 for OS/390 servers. For moreinformation on how to prepare your DB2 for OS/390 SQL stored procedures fordebugging, refer to 4.6, “Stored procedure debugging” on page 142. For moreinformation on how to prepare your DB2 UDB for UNIX, Windows, and OS/2 SQLstored procedures for debugging, refer to 5.6, “Stored procedure debugging” onpage 166.

The client workstation for debugging remote stored procedures must beexecuting a Windows NT environment. During our project, we worked with a betaversion of the IBM Distributed Debugger.

The DB2 SPB is not a prerequisite for debugging your SQL stored procedures.You can debug your SQL stored procedures even if you did not create them with

The DB2 Stored Procedure Builder 105

Page 122: Store Procedure

SPB. The SPB can help you with panels to customize the DB2 server fordebugging, but the process of debugging is independent of SPB. Figure 51 showshow the debugger process is triggered for stored procedures.

Figure 51. Debugging process

SPB also avoids the need to create a client application to debug your storedprocedure. You can invoke your procedure from SPB and the debugging processis triggered.

To be able to debug remote stored procedures, you must have the IBMDistributed Debugger client daemon executing on your workstation. To start thedebugger client daemon, you can issue the following command:

idebug -qdaemon -quiport=8000

The above command starts the debugger client listener in TCP/IP port 8000. Inyour DB2 server running the procedure, you need to inform this port and the IPaddress of your client machine, so when the stored procedure executes on theserver, the debugger is started in your workstation. Figure 52 shows the IBMDistributed Debugger daemon window, when waiting for a remote connection.

Figure 52. IBM Distributed Debugger daemon

When your procedure starts in the DB2 server, the debugger code in the server,sends a message to the debugger client, and the IBM Distributed Debugger mainwindow is started. Figure 53 shows the IBM Distributed Debugger main window.

106 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 123: Store Procedure

Figure 53. IBM Distributed Debugger main window

The IBM Distributed Debugger main window is divided into three main parts: onecontaining the source code of your stored procedure, one with monitors, and onewith stacks. On the top of the window, you have controls that allow you tomanage the execution of your procedure, step-by-step if you want.

In the source code part of the main window, an arrow shows the currentstatement being executed. Due to the fact that SQL Procedures generates a Ccode, during our project with the beta version of the debugger, we had to stepmany times to go from one SQL stored procedure statement to the following,because it was actually stepping on the C code generated. This may changewhen the final version is released.

You can also set breakpoints in your source code, indicated by a red dot next tothe line number. To set breakpoints, all you have to do is double-click next to theline number and the breakpoint is set. You can only set breakpoints in lines thatactually execute some code, so you will not be able to set breakpoints in lineswith comments, for example.

In the monitor part of the main window, you can monitor and change values ofvariables and parameters of your stored procedure. To start monitoring the valuesof a variable, just click on Monitor -> Add variable to program monitor. TheMonitor Expression window appears and you can type the name of the variableyou want to monitor. Figure 54 shows the Monitor Expression window.

The DB2 Stored Procedure Builder 107

Page 124: Store Procedure

Figure 54. Monitoring variables

Remember that during the generation of the C code your parameters are prefixedwith the procedure name, and your variables declared within a compoundstatement are prefixed with the label of the compound statement. You mustremember to type the prefixed name of the variable, or you will not be able to addthe variable to the monitor. In our example, this is the name of the storedprocedure, DEBUG, as typed before the name of the parameter we wanted tomonitor, EMPNUM.

After you have added your variable or parameter to the monitor, you can easilychange the contents of it, by simply double clicking on the name.

With the IBM Distributed Debugger graphical interface, it is very easy tounderstand and debug the logic of your stored procedures running in any DB2server in your network.

108 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 125: Store Procedure

Chapter 4. SQL Procedures for DB2 UDB for OS/390

In this chapter, we explain how to code SQL Procedures for DB2 UDB for OS/390version 5 and version 6 servers. We focus on system requirements and planning,as well as the rules for writing, preparing, and debugging an SQL Proceduresprogram. Also, we show how the new tool, Stored Procedure Builder (SPB), canbe used in conjunction with the SQL Procedures support on OS/390.

4.1 General considerations

The SQL Procedures language support on the OS/390 platform has beenimplemented for DB2 for OS/390 version 5 and DB2 UDB for OS/390 version 6.

The SQL Procedures support improves the development and usability of storedprocedure, ensures the portability of SQL stored procedures across DB2platforms, and simplifies migration to DB2 from other environments through theuse of a translation tool (expected to be made available by first quarter of 2000).

There are three main methods, describe in detail in this chapter, for developing ofSQL stored procedures on OS/390:

• Method 1 — Using the Stored Procedure Builder (SPB) tool, which runs on allcurrent Windows platforms, and later will be made available on UNIX. TheSPB invokes the OS/390 SQL Procedure Processor for building the storedprocedure.

• Method 2 — Using the OS/390 SQL Procedure Processor (DSNTPSMP).

• Method 3 — Using Job Control Language (JCL) or Command List (CLIST).

For most situations, we recommend that you use Method 1, because the SPB toolhelps you in coding, testing and debugging of your stored procedure, therebyimproving the development process (see Chapter 3, “The DB2 Stored ProcedureBuilder” on page 57 for more information about the SPB). However, you shouldalso read the section for each corresponding method and choose the one that fitsbest in your environment.

4.2 System requirements and planning

If you already have version 6 already installed, or if you are still using version 5and are planning to use this new stored procedure programming language, youneed to follow the steps below, which describe the prerequisites for this support.Otherwise, this support will be provided as part of installing or migrating toversion 6.

4.2.1 Requirements for DB2 for OS/390 Version 5The trial beta version of the SQL Procedures language support is shipped as azip file, sqlproc1.zip, which you can download from:

http://www.software.ibm.com/data/db2/os390/sqlproc

© Copyright IBM Corp. 1999 109

Page 126: Store Procedure

This Web download includes the following software, which you will need to applyto your OS/390 environment:

• Load modules for SQL Procedures language support

• JCL and SQL samples, including DSNHSQL, used to create your SQL storedprocedures

• A readme file, which contains detailed installation instructions

Once you have done this, you will be able to develop and prepare storedprocedures written in the SQL Procedures language. At this point, the preparationprocess for your SQL stored procedures can be done manually, that is, throughJCL, as described in 4.5.3, “Using JCL” on page 136.

If you plan to use the OS/390 Procedure Processor, either directly or through theSPB, you must download an additional zip file, sqlprocp.zip. This additional zip fileincludes the following software:

• PTF for DB2 APAR PQ24199 — Dynamic invocation of the bind

• PTF for DB2 APARs PQ29706 and PQ32467— REXX stored proceduresupport

• REXX exec DSNTPSMP — The OS/390 Procedure Processor

• JCL job DSNTIJSQ, which must be manually customized by the user.Directions are provided in the JCL prologue. This job performs the following:

• Creates and defines the DSNTPSMP stored procedure to DB2 and grantsEXECUTE to PUBLIC.

• Executes the DDL to create the SQL Procedures database, tablespaces,tables and indexes. See 4.2.4, “Creating non-catalog DB2 tables” on page112 for details about this database.

• Grants SELECT access to the SQL Procedures tables.

• JCL and samples, including DSNWLMP, which is a sample JCL procedure tostart the WLM-managed stored procedures address space required byDSNTPSMP. Customize this procedure for your site by following the directionsin the prologue, and then copy it to your system PROCLIB.

• A readme file, which contains detailed instructions.

The REXX language support feature must also be installed if you plan to use theOS/390 Procedure Processor. The following feature numbers are orderablethrough your IBM Representative:

• 5861 for install using 6250 tape

• 5862 for install using 3480 cartridge

• 5275 for install using 4mm DAT

If you plan to use the OS/390 Procedure Processor through the SPB, then youneed to install the SPB product on your PC (see Chapter 3, “The DB2 StoredProcedure Builder” on page 57). If you want to use the SPB SQL CostingInformation, you need to install the following PTFs on your OS/390 system:

• PTF for DB2 APAR PQ23162

• PTF for DB2 APAR PQ24230

110 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 127: Store Procedure

Note: For detailed information about how to install the SQL Procedures code,refer to the document DB2 for OS/390 Version 5 Preview of SQL Procedures,available at the following URL (download site):

http://www.software.ibm.com/data/db2/os390/sqlproc

Details will also be available in the readme file that is downloaded with the zip files.

4.2.2 Requirements for DB2 UDB for OS/390 Version 6The following PTFs must be applied in your environment:

• PTF for DB2 APARs PQ29782 and PQ30467 — SQL Procedures support forDB2 pre-compiler

• PTF for DB2 APAR PQ24199 — Dynamic invocation of the bind

• PTF for DB2 APAR PQ30219 — REXX stored procedure support

• PTF for DB2 APAR PQ30492 — This includes the following components:

• Modifications to DB2 Install parts in support of SQL Procedures

• JCL and SQL samples

• Jobs to create the SQL Procedures database

• The OS/390 Procedure Processor (DSNTPSMP)

• JCL job DSNTIJSQ, a post-install job that creates objects required for DB2SQL Procedures. This job must be manually customized by the user.Directions are provided in the JCL prologue. This job performs thefollowing:

• Creates and defines the DSNTPSMP stored procedure to DB2 andgrants EXECUTE to PUBLIC.

• Executes the DDL to create the SQL Procedures database,tablespaces, tables, and indexes. See 4.2.4, “Creating non-catalog DB2tables” on page 112 for details about this database.

• Grants SELECT access to the SQL Procedures tables.

• Copies JCL procedure DSNHSQL to the system PROCLIB.

• Copies DSNTPSMP to prefix.NEW.SDSNCLST, where the WLM Startupprocedure for DSNTPSMP will expect to find it.

• A sample JCL procedure (DSN8WLMP), which starts the WLM-managedstored procedures address space required by DSNTPSMP. Customize thisprocedure for your site by following the directions in the prologue, and thencopy it to your system PROCLIB.

• The REXX language support feature is a prerequisite for REXX storedprocedure and must also be installed if you plan to use the OS/390 ProcedureProcessor.

• PTF for DB2 APAR PQ30439 — External Savepoint support

• PTF for DB2 APAR PQ32670 — Declared Temporary Table support

• PTF for DB2 APARs PQ30684 and PQ30652 — Identity Columns support

• PTF for DB2 APAR PQ24891 - SPB SQL Costing Information

SQL Procedures for DB2 UDB for OS/390 111

Page 128: Store Procedure

Further components will be forthcoming through APARs as they becomeavailable.

Note: For detailed information about how to install the version 6 SQL Procedurescode, refer to the document DB2 UDB for OS/390 Version 6 Preview of SQLProcedures, available at the URL:

http://www.software.ibm.com/data/db2/os390/spb

4.2.3 Remote Debugger and Debug toolIf you plan to use the Remote Debugger and the Debug tool to debug your storedprocedures (see 4.6, “Stored procedure debugging” on page 142), you need to:

• Apply DB2 PTF APAR PQ30773 (for DB2 version 5 and version 6).

• Install the Remote Debugger on your PC (see 3.4.6, “Debugging storedprocedures” on page 105).

• Install the Debug tool on your OS/390 system.

The beta for the Debug tool code and information can be downloaded from thefollowing Web site:

http://www.software.ibm.com/ad/c390/cmvsbeta.htm

Following are the requirements to install the Debug tool on your OS/390system environment:

• TCP/IP version 3.2

• LE/390 base C compile with debug (OS/390 optional feature codes 5962,5963, 5712).

• 5655-B85 IBM C/C++ Productivity Tools for OS/390 Release 1.

Once you have installed the Debug tool, you have to:

• Apply the PTF for Debug tool APARs PQ27247 and PQ25905, on yourOS/390 system. These PTFs contain additions to the Debug tool for storedprocedure debugging.

4.2.4 Creating non-catalog DB2 tablesThe SQL Procedures database DSNDPSM contains the tablespace DSNSPSM,the three non-catalog DB2 tables SYSIBM.SYSPSM, SYSIBM.SYSPSMOPTS,and SYSIBM.SYSPSMOUT, and the indexes DSNPSMX1, DSNPSMX2, andDSNPXMOX1. These are required for the OS/390 Procedures Processor. You donot need to create these if you are planning to build your SQL stored proceduresusing JCL only (see 4.5.3, “Using JCL” on page 136).

This SQL Procedures database is created by:

• For customers using version 5: Running the job DSNTIJSQ when installingfrom the sqlprocp.zip download.

This is the site to use to get the trial code for SQL Procedures and the StoredProcedure Builder:

ftp://ftp.software.ibm.com/software/os390/db2server/fixes/db2apars/

Important:

112 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 129: Store Procedure

• For customers installing a new DB2 version 6 system: Running the normalinstallation scenario, using the DB2 install CLIST and customized install andsample jobs.

• For customers migrating to version 6: Running installation job DSNTIJSG.

• For customers who have already installed or migrated to version 6: Runningpost-installation job DSNTIJSQ, which is delivered with the PTF for APARPQ30492.

4.2.4.1 Creating SYSIBM.SYSPSMTable 9 shows the definition of SYSIBM.SYSPSM, which stores the unmodifiedsource code of the SQL stored procedure.

Table 9. SYSIBM.SYSPSM

4.2.4.2 Creating SYSIBM.SYSPSMOPTSTable 10 shows the definition of SYSIBM.SYSPSMOPTS, which stores theprecompile, compile, prelink, link and bind options.

Table 10. SYSIBM.SYSPSMOPTS

Column name Format(Length) Description Nullable Default

SCHEMA CHAR(8) Owner ID Y Y

PROCEDURENAME CHAR(18) SQL stored procedurename

N N

SEQNO SMALLINT Used to sequence lines forSQL stored proceduresource code greater than3800 characters

N N

PSMDATE DATE Creation date N N

PSMTIME TIME Creation time N N

PROCCREATESTMT VARCHAR(3800) SQL stored proceduresource

N N

Column name Format(Length) Description Nullable Default

SCHEMA CHAR(8) Owner ID Y Y

PROCEDURENAME CHAR(18) SQL stored procedurename

N N

BUILDSCHEMA CHAR(8) Owner ID of build module.Usually SYSPROC

Y Y

BUILDNAME CHAR(18) Build module name. UsuallyDSNTPSMP.

Y Y

BUILDOWNER CHAR(8) Builder ID of SQL storedprocedure (current SQLID)

Y Y

PRECOMPILE_OPTS VARCHAR(255) Precompile options Y Y

COMPILE_OPTS VARCHAR(255) Compile options Y Y

PRELINK_OPTS VARCHAR(255) Prelink options Y Y

LINK_OPTS VARCHAR(255) Link options Y Y

SQL Procedures for DB2 UDB for OS/390 113

Page 130: Store Procedure

4.2.4.3 Creating SYSIBM.SYSPSMOUTTable 11 shows the definition of SYSIBM.SYSPSMOUT, which is a globaltemporary table for DSNTPSMP.

Table 11. SYSIBM.SYSPSMOUT

Refer to 4.4, “Stored procedure preparation” on page 118 for details about howthese tables are updated.

4.2.5 WLM requirements for OS/390 Procedure ProcessorThe OS/390 Procedure processor (DSNTPSMP) should be set up in a WLMenvironment of its own. It is recommended that no other stored procedure shouldbe defined to this environment. The OS/390 Procedure Processor requires thatthe NUMTCB in the WLM managed region be 1, which means that only oneinstance of DSNTPSMP will be able to execute in its own WLM environment atany time.

The main consequence is that only one SQL stored procedure can be built ineach WLM environment at one time, but it is possible to have more than oneWLM environment, each running its own version of DSNTPSMP. See Figure 55.

Figure 55. Multiple WLM environments

See 4.5, “Setting up DSNTPSMP” on page 120 for more details on how to set upthe OS/390 Procedure Processor.

BIND_OPTS VARCHAR(1024) Bind options Y Y

SOURCEDSN VARCHAR(255) Data set name of SQLstored procedure sourcecode

Y Y

Column name Format(Length) Nullable Default

STEP VARCHAR(16) Y Y

FILE VARCHAR(8) Y Y

SEQN INTEGER Y Y

LINE VARCHAR(255) Y Y

Column name Format(Length) Description Nullable Default

W L M 1runn ing

D SN T P SM PN U M T C B= 1

W LM 2runn ing

D S N T PSM PN U M T C B =1

W LM 3run n ing

D SN T PS M PN U M T C B =1

.......

114 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 131: Store Procedure

4.3 Coding considerations

In this section we document some of the issues that we found while creating SQLstored procedures on the OS/390 platform.

4.3.1 Length and size limitsThe size of your SQL stored procedure code is limited to 32K. Note that if you areusing DSNTPSMP, the tables SYSIBM.SYSPSM, SYSIBM.SYSPSMPOPTS, andSYSIBM.SYSPSMOUT will be updated. Although the field PROCCREATESTMTin SYSIBM.SYSPSM, which contains the source code, is limited to 3800characters, DSNTPSMP will break up your source into 3800 character "chunks"and use the SEQNO field to sequence these lines to keep the order of yoursource code.

When creating your SQL stored procedure using the SPB, the width of yourstatements must be limited to 72 bytes. Although the edit screen in SPB is widerthan this, the DB2 pre-compiler will only read a width of 72 bytes.

The name of the SQL stored procedure can be a maximum of 18 characters, butdue to OS/390 limitations, the member name created at the DBRMLIB, LOADLIB,and other libraries is limited to 8 bytes. If you are creating your SQL storedprocedure through the SPB or calling the OS/390 Procedure Processor directly,and your procedure name is longer than 8 characters, DSNTPMSP will generatean 8-character name for you, consisting of the characters "SP" followed by 6random alphameric characters. We recommend that the first 8 characters beunique within one project, and that you limit your procedure name to 8 characterswhen building it, using the JCL batch job.

4.3.2 Parameters and variablesTo store data used within an SQL stored procedure, you can declare SQLvariables. SQL variables can have the same data types and lengths as SQLstored procedures parameters.

SQL stored procedures parameters and variables have the following restrictions:

• Since the precompiler folds all SQL variables to uppercase, two variablescannot be declared the same except for their case. For example, variablesVAR1 and var1 declared in the same SQL stored procedure will receive acompile error.

• Variable and parameter names cannot be the same name. The following errormessage is issued:

DSNH590I Name <name> is not unique

• An SQL reserved word cannot be used as a parameter or variable.

• Do not precede the variable name with a colon.

• In version 5, parameters cannot contain underscores (in version 6 thisrestriction is removed).

Currently, this restriction is not picked up by the compiler; you will only see theerror message when the START PROCEDURE command is issued. Forexample:

STC00044 DSNX904E . DSNX9CAT THE NAME DEPT_NUM IN THE PARMLIST

SQL Procedures for DB2 UDB for OS/390 115

Page 132: Store Procedure

FOR PROCEDUREGETMEDIANSALARY CONTAINS AN INVALID CHARACTER. REASON CODE IS 000.STC00044 DSNX948I . DSNX9ST2 START PROCEDURE FAILED FOR *, DUETO PREVIOUSLYREPORTED ERROR CONDITION

• In version 5, parameter names must be 8 bytes or less (in version 6 thisrestriction is removed).

Currently, this restriction is not picked up by the compiler; you will only see theerror message when the START PROCEDURE command is issued. Forexample:

STC00044 DSNX903E . DSNX9CAT THE NAME MEDIANSALARY IN THEPARMLIST COLUMN OFSYSIBM.SYSPROCEDURES FOR PROCEDURE GETMEDIANSALARY IS TOO LONG.STC00044 DSNX948I . DSNX9ST2 START PROCEDURE FAILED FOR *, DUETO PREVIOUSLYREPORTED ERROR CONDITION

The following items should be qualified to avoid ambiguity and also preventcompilation or bind errors:

• When using a parameter in the procedure body, qualify the parameter namewith the procedure name.

• Qualify variable names with the label of the compound statement in which thevariables appear.

• Qualify column names with the table name. For example:

SELECT STAFF.ID INTO V_IDFROM DB2RES1.STAFF WHERE STAFF.ID = V_ID;

• A parameter name can be the same as a column name, but the column namemust be qualified with the table name.

• If you qualify a parameter with a misspelled procedure name, the followingerror message is issued:

DSNH312I Undefined or unusable host variable

This is also true of variables qualified with misspelled label names.

In version 5, although the maximum length of the parameter list (PARMLIST)column is defined as 3000 in SYSIBM.SYSPROCEDURES, you are limited to amaximum of 254 bytes, because when your SQL stored procedure is defined toDB2, it issues an INSERT statement containing a literal to update theSYSIBM.SYSPROCEDURES table. You will receive an SQLCODE -102 if theliteral string to be inserted to PARMLIST is longer than 254. This limitation doesnot apply when using a host variable.

In version 6, the previous limitation does not apply, because a DDL CREATEPROCEDURE statement is executed to define your SQL stored procedure toDB2.

If you are planning to use the SPB to test your SQL stored procedures, werecommend that you prefix any table referenced in your SQL stored procedurecode with the owner ID. Otherwise, the owner of the OS/390 ProcedureProcessor, which is a REXX stored procedure, will be assumed as the owner ofthe tables.

116 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 133: Store Procedure

4.3.3 Handling SQLCODE and SQLSTATE valuesThe sample A.2.19, “SMP7LMS” on page 207 of Appendix A, “Sample SQL storedprocedure programs” on page 195 shows how the SQLCODE and SQLSTATE valuescan be captured and handled in an SQL stored procedure. But it is important to beaware of the following warning when trying to capture BOTH the SQLCODE andSQLSTATE values:

4.3.4 SQL statementsTo define your SQL stored procedure to DB2 in version 5, an INSERT DMLstatement is made to SYSIBM.SYSPROCEDURES. This INSERT statement iscreated for you from the SQL Procedures pre-compiler in ddname SYSUT1. Inversion 6 this is kept as a CREATE PROCEDURE DDL statement and will begenerated for you from the SQL Procedures precompiler in ddname SYSUT2.

If you are building your SQL stored procedure through JCL, you need to executethis generated statement through DSNTIAD to define your SQL stored procedureto DB2. If you are using the SPB or calling DSNTPSMP directly, this will beautomatically executed for you.

Currently, in SQL Procedures for OS/390, you can have only one compoundstatement (see 2.4, “Current implementation of SQL Procedures language” onpage 17). But you can overcome this limitation by coding all the compoundstatements within a single simple statement, for example in a LOOP or IFstatement. The example below shows that the compound statements test andtest2 are contained within the loop1 loop statement:

CREATE PROCEDURE spmd0211(INOUT ps1 SMALLINT, inout ps2 smallint,inout pc1 char(20))LANGUAGE SQLWLM ENVIRONMENT WLMENV1COLLID CLMD02

loop1: looptest: BEGIN

DECLARE i1 INT;DECLARE p1 DOUBLE PRECISION;...............................................delete from tsttab11

where num = test.n2;end if;set spmd0211.ps1 = spmd0211.ps1 + 10; -- ps1 is 80

end test;test2: begin

Since a SET statement is an SQL statement, the SQLCODE and SQLSTATEare set to the values returned by the SELECT generated under-the-covers forthe SET statement. So, in the example A.2.19, “SMP7LMS” on page 207, whenyou say SET PSQLST = SQLSTATE, it will set PSQLST to the SQLSTATEreturned by the previously-executed statement, which is what you wouldexpect. However, when you follow that with SET PSQLCO = SQLCODE, it willset PSQLCO to the SQLCODE returned by the SET PSQLST = SQLSTATE,which will be most certainly zero. You will not get the SQLCODE you expect,that is, from the statement executed just before the handler was invoked.

Important:

SQL Procedures for DB2 UDB for OS/390 117

Page 134: Store Procedure

DECLARE s1 smallINT default 0;DECLARE c1, c2 CHAR (5);........................................close cursor1;set spmd0211.ps2 = test2.s1;

END test2;leave loop1;

end loop

This method can also be used within handlers which cannot currently supportnested compound statements. For example, you can have a block of statementsby using the IF statement as below:

DECLARE CONTINUE HANDLER FOR NOT FOUNDIF (1=1) THENSET ENDTABLE = 1;SET OUTCODE = SQLCODE;

END IF;

4.3.5 Client applicationNo major change is needed in the way the client application is coded, or the wayit calls a stored procedure written with the SQL Procedures programminglanguage.

Note: Following the SQL/PSM standard, DB2 supports only the parameter styleGENERAL WITH NULLS linkage convention for SQL stored procedures. Thismeans that you should include a null indicator variable for each of the parametersthat will be returned from the SQL stored procedure. Refer for DB2 for OS/390 V5Application Programming and SQL Guide, SC26-8958, or DB2 UDB for OS/390V6 Application Programming and SQL Guide, SC26-9004, for detailedinformation about linkage conventions.

4.4 Stored procedure preparation

There are three methods available for preparing a stored procedure written inSQL Procedures language as shown in Figure 56:

1. The Stored Procedure Builder (SPB) Tool, which invokes the OS/390Procedure Processor, can be used to build your SQL stored procedures.

2. The OS/390 Procedure Processor, called DSNTPSMP, can be used to buildyour SQL stored procedures.

3. All steps required to build an SQL stored procedure can be run using JCL. Youcan use the DB2-supplied JCL procedure (DSNHSQL). The option to compileusing the DB2 Interactive (DB2I) panels will be available from version 6.

118 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 135: Store Procedure

Figure 56. Three methods for preparing SQL stored procedures

4.4.1 ProcessThe process involved in the creation of the SQL stored procedure is as follows:

1. The user creates the SQL stored procedures source (either manually orthrough prompted help via the SPB).

2. The source is then precompiled resulting in a C language program completewith SQL and logic.

3. The generated C program is then precompiled by the normal DB2 precompiler(DSNHPC) as per any other program using parameter of HOST(C).

4. The modified C source is then compiled and linkedited

5. The DBRM is bound.

6. The following tables might be updated when an SQL stored procedure iscreated successfully:

• SYSIBM.SYSPROCEDURES (in version 5) or SYSIBM.SYSROUTINESand SYSIBM.SYSPARMS (in version 6)

• SYSIBM.SYSPSM

• SYSIBM.SYSPSMOPTS

• SYSIBM.SYSPSMOUT

Note: If you are using Method 1 or 2, a DML INSERT statement to populatethe SYSIBM.SYSPROCEDURES (if against DB2 version 5), or a DDLCREATE PROCEDURE statement (against DB2 version 6), will be

normal precompile

compile

prelink

bind

SQL Precompile

link

321

update DB2 tables

SPB Using JCLOS/390

ProceduresProcesso

SQL Procedures for DB2 UDB for OS/390 119

Page 136: Store Procedure

automatically executed for you. But if you are using Method 3, you need toexecute these statements to define the procedure to DB2.

4.4.2 AuthorizationThe authorization needed to build SQL stored procedures in DB2 version 5 differsfrom that in version 6. In version 5, there is no explicit security for storedprocedures, because they are not recognized as DB2 resources or objects, asthey are in version 6.

The authorization used for DB2 when generating and binding the SQL storedprocedure is the current SQLID or submitter of the job.

The extra privileges needed by the person requesting the build of the SQL storedprocedure in version 5 and version 6 are:

• DB2 version 5 — SELECT, DELETE and INSERT from tablesSYSIBM.SYSPROCEDURES, SYSIBM.SYSPSM, SYSIBM.SYSPSMOPTS,and SYSIBM.SYSPSMOUT.

• DB2 version 6 — CREATEIN, DROPIN or ALTERIN to the SCHEMA nameunder which you will be creating your SQL stored procedure.

• DB2 version 6 — (if using SPB or DSNTPSMP), you need EXECUTE ONPROCEDURE DSNTPSMP.

• Alternatively, you need SYSADM or SYSCTRL authority.

The normal privileges are needed to bind to the collection being used for yourSQL stored procedure and any privileges to tables referenced in your SQL storedprocedure.

Please also note that update access needs to be given on the datasetsreferenced in the WLM region, to the userid running the WLM.

4.5 Setting up DSNTPSMP

Since the OS/390 Procedure Processor itself is a stored procedure, it isassociated with a particular WLM environment. The JCL to run this WLMenvironment is, therefore, set up with ddnames referencing a single set ofapplication libraries.

The DSNTPSMP is written using REXX, and it was designed to attend customersin general. When you install the SQL Procedures support, you get the sourcecode of the DSNTPSMP, which can be customized to a specific environment.

In addition, you might want the processor to be able to use more than one WLMenvironment, so that a different set of libraries can be referenced. You might dothis if, for example, you are building SQL stored procedures for different projects,or if you want to set up different environments for test and production, or even ifyou just want to be able to test in a WLM environment without affecting or beingaffected by other people who may be testing.

To be able to set up your environment so that DSNTPSMP can be used in morethan one WLM environment, you need to do the following:

• Define a new stored procedure based on the existing DSNTPSMP, but:

120 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 137: Store Procedure

• Use a different procedure name.

• Use a different WLM environment.

Here is an example of defining a new OS/390 Procedure Processor calledNEWTPSMP to use a WLM region called WLMENV2:

(version 5)

INSERT INTO SYSIBM.SYSPROCEDURESVALUES('NEWTPSMP',

' ',' ','DSNTPSMP',' ','DSNREXCS','REXX',0,' ','N','TRAP(OFF),MSGFILE(SYSPRINT)','VARCHAR(20) IN, VARCHAR(18) IN, VARCHAR(32672) IN, VARCHAR(10

24) IN, VARCHAR(255) IN, VARCHAR(255) IN, VARCHAR(255) IN, VARCHAR(255)IN, VARCHAR(254) IN, VARCHAR(80) IN, VARCHAR(8) IN, VARCHAR(18) IN, VARCHAR(255) OUT',

1,'WLMENV2', 'M','N','N');

(version 6)

CREATE PROCEDURE NEWTPSMP(IN P1 VARCHAR(20),IN P2 VARCHAR(8),IN P3 VARCHAR(32672),IN P4 VARCHAR(255),IN P5 VARCHAR(255),IN P6 VARCHAR(255),IN P7 VARCHAR(255),IN P8 VARCHAR(255),IN P9 VARCHAR(254),IN P10 VARCHAR(80),OUT P11 VARCHAR(255))

EXTERNAL NAME DSNREXCSPARAMETER STYLE GENERALWLM ENVIRONMENT WLMENV2PROGRAM TYPE MAINLANGUAGE REXXRESULT SETS 1RUN OPTIONS 'TRAP(OFF),MSGFILE(SYSPRINT)';

• Note that the other definitions should be the same as what was originallydefined for DSNTPSMP.

• Register the new WLM environment.

• Set up the JCL for the WLM started task JCL to reference the other set oflibraries.

To make the SPB recognize this new procedure name for the DSNTPSMP, youhave to change the Build utility field. This field is located from the "Advanced"button from the "Options" tab when building SQL Procedures for the OS/390environment. It is also available from the Properties option when you click on the

SQL Procedures for DB2 UDB for OS/390 121

Page 138: Store Procedure

procedure with the right mouse button. See Figure 57 for an example where wechanged the Build utility to NEWTPSMP.

Figure 57. Build Name field on OS/390 Options

When you generate and build this new SQL stored procedure using NEWTPSMP,the dbrm, load, and source modules will be placed in the data sets referenced bythe ddnames in the WLM environment associated with NEWTPSMP.

If you are building your SQL stored procedure by calling the procedure processordirectly, it is just a simple matter of changing the called procedure name fromDSNTPSMP to NEWTPSMP.

4.5.1 Using the SPBThe easiest method of creating, generating, and testing your SQL storedprocedure is to use the Stored Procedure Builder Tool. Only the OS/390 relatedoptions will be discussed here. See Chapter 3, “The DB2 Stored ProcedureBuilder” on page 57 for a general description of using the SPB to build your SQLstored procedure.

The OS/390 Options screen is available from the Advanced button on the Optionstab when using the SmartGuide to create your SQL stored procedure. See Figure58 and Figure 59. It is also available from the Properties option when youright-click on your procedure name.

122 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 139: Store Procedure

Figure 58. OS/390 Options from SPB — 1/2

Figure 59. OS/390 Options from SPB — 2/2

SQL Procedures for DB2 UDB for OS/390 123

Page 140: Store Procedure

You specify on this panel the options that will be used when SPB builds yourprocedure.

The Build utility name needs to be changed if you are running the OS/390Procedure processor in multiple WLM environments. See 4.5, “Setting upDSNTPSMP” on page 120 for more details about this.

Once you have successfully generated and built your SQL stored procedure, youcan then choose to test it by clicking the Run button from the main panel.

4.5.1.1 SQL costing informationThe SPB tool allows you to measure the costing of the SQL statements in yourSQL stored procedure. This functionality is only available for the OS/390environment.

From the SPB tool, click on the Actual Costs button to get the costs of running theSQL stored procedure against the OS/390 environment. This button is located onthe SQL Query tab when generating your SQL stored procedure using theSmartGuide. For this release of the SPB, the actual costs will only be calculatedfor the whole SQL stored procedure, but in future releases you will be able to getthe cost of each SQL statement by highlighting it.

The SPB calls the stored procedure monitor program DSNWSPM which starts themonitor trace and formats the output. From the output you can then view and sortby different columns. Note that the first time this is called, the number ofGETPAGEs is higher because the module needs to be loaded into the buffer.

Stored procedure monitor programThe stored procedure monitor program DSNWSPM (which itself is an assemblerstored procedure) returns CPU time and other DB2 costing information for thethread on which it is running. A client program can connect to DB2 on OS/390,execute SQL and then call DSNWSPM to find out how much CPU time it took.

DSNWSPM works on either a local or remote thread.

The instrumentation values that DSNWSPM provides are:

• CPU time in external format

• Latch/lock contention wait time, external format

• CPU time as an integer in hundredths of a second

• Latch/lock contention wait time

• Number of GETPAGEs in integer format

• Number of read I/Os in integer format

• Number of write I/Os in integer format

Figure 60 shows an output of the SQL Procedures monitor program. You can sortthe information shown by clicking on the columns. Additionally, if you place yourmouse pointer over any SQL statement, it will be expanded for you.

124 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 141: Store Procedure

Figure 60. SQL Costing Information panel

Setup and securityAn accounting trace needs to be started on the host for this option to besuccessfully executed. The command to start the accounting trace is:

start trace(acctg) class(1,2,3)

The monitor trace also has to be on, but DSNWSPM starts that internally.

The authority you need to execute the stored procedure is:

• For version 5: MONITOR1 and TRACE

• For version 6: MONITOR1, TRACE, and EXECUTE ON PROCEDURE

For example, to allow USRT011 to execute DSNWSPM on version 6:

GRANT TRACE TO USRT011;

GRANT MONITOR1 TO USRT011;

GRANT EXECUTE ON PROCEDURE SYSPROC.DSNWSPM TO USRT011;

Invoking the stored procedure monitor program (DSNWSPM)You can call DSNWSPM in two ways:

1. Before and after executing the SQL

2. Only after executing the SQL

The preferred way to use DSNWSPM is the first method, because the time valuesare more accurate, as they are the delta values between beginning and endingtime. If you call DSNWSPM using the second method, after executing the SQLonly, the beginning CPU time returned to you will include the thread setup time,and may include the times for SQL that you have previously executed on thesame thread.

4.5.2 Using OS/390 Procedure Processor (DSNTPSMP)After coding the SQL stored procedure you can choose to prepare it using theOS/390 Procedure Processor (method 2). The processor automates andperforms all the steps required to generate and build your SQL stored procedure.

The way to do this is to code a client program (coded in any language), whichinvokes the OS/390 Procedure Processor. The processor (DSNTPSMP) itself is astored procedure which has input and output parameters. You pass to it thefunction that you wish performed on your SQL stored procedure source. Thefunctions are: Build, Destroy, Rebuild, Rebind and Alter LE Run Options (see4.5.2.4, “DSNTPSMP functions” on page 129).

SQL Procedures for DB2 UDB for OS/390 125

Page 142: Store Procedure

Using this method, your client program will invoke DSNTPSMP and pass to it theparameters which it needs to completely build your stored procedure.

One of the reasons for coding a client program rather than using the SPB Tool isthat the project administrator or DBA might wish to standardize the bind, link, orcompile options within a project. One way of doing this is to only allow theprogrammer to pass a few parameters, for example: function, SQL stored

procedure name, SQL stored procedure source. The other options can then behardcoded in your client program and therefore "hidden" from the SQL storedprocedure developer. See 4.5.2.5, “Example of a client program” on page 131 fora sample client program written in PL/1, which does this.

Figure 61 shows the input and output to DSNTPSMP. The WLM environmentdefined to be used by DSNTPSMP must be available before you call DSNTPSMP.

Figure 61. Input / Output for SQL Procedures Processor

4.5.2.1 Input parameters for DSNTPSMPThe parameters passed to DSNTPSMP must be in this order:

1. Function: The action that you want DSNTPSMP to perform on your SQLstored procedure. See 4.5.2.4, “DSNTPSMP functions” on page 129 for adescription of each function.

DSNTPSMP

Datasets referenced in WLM DB2 tablesupdated

Procedure Name

Source Code

Bind Options

Compiler Options

Link Options

Input Dataset

Build Schema

LE Runtime Options

Prelink OptionsFunction

Precompiler Opts Build Name

1

12

11

10

9

8

7

6

5

4

3

2

Input Parameters

D

CA B

Result Set

Outputstring

126 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 143: Store Procedure

2. Procedure Name: The name of your SQL stored procedure (maximum 18characters). This needs to be the same as the name you specify in yourCREATE PROCEDURE statement. In version 6, the procedure name can be upto 27 characters (8-byte schema, 1-byte dot, 18-byte routine name).

3. Source Code: The SQL stored procedure source code. This is not needed ifyou pass the source via an Input File data set. But if both parameters arepassed, source will be taken from this parameter in preference to source fromthe data set. In version 6, source code passed in as a parameter can be 32K. Ifusing a dataset for the input, there is no limit.

4. Bind Options: The options with which you wish to bind your SQL storedprocedure package. The maximum length is 1024 characters.

5. Compiler Options: The options which you want to pass for use in compilingyour SQL stored procedure module, for example, TEST/NOTEST. Themaximum length is 255 characters.

6. Precompiler Options: The options to be used during pre-compilation of yourSQL stored procedure. Maximum length is 255 characters.

7. Prelink Options: The options to be used to pre-link your module. Maximumlength is 255 characters.

8. Link Options: The options passed to the linkage editor. Maximum length is255 characters.

9. LE Runtime Options: The options to be passed to the Language Environmentfor execution of your module. Input passed here will be ignored for otherfunctions. The maximum length is 254 characters.

10.Input Dataset: The data set containing the SQL stored procedure sourcecode. If you pass this parameter, then you do not need to pass the source inthe Source Code parameter. But if both parameters are passed, the source inthe Source Code parameter is used in preference.

11.Build Schema: This contains the schema name for the procedure name youpass in the Build Name (parameter 12). Usually this is SYSPROC for version5, and could be any name in version 6.

12.Build Name: A name for the OS/390 Procedures Processor, usuallyDSNTPSMP. The maximum length is 18 characters.

4.5.2.2 DDNAMES used by DSNTPSMP on WLMThe DDNAMES for the permanent datasets referenced on the WLM region thatare used by DSNTPSMP are described here. They are used for both input andoutput:

• SQLDBRM — Your SQL stored procedure DBRM module

• SQLCSRC — Your SQL stored procedure precompiled C source codegenerated by DSNTPSMP

• SQLLMOD — SQL stored procedure generated load module

• SQLLIBC — Language C header files

• SQLLIBL — Link libraries, run libraries, DB2 load libraries

• SYSMSGS — SCEEMSG "C" messages library for prelinker

Other ddnames are also used, but permanent datasets do not need to beallocated to them.

SQL Procedures for DB2 UDB for OS/390 127

Page 144: Store Procedure

Following is part of the JCL used in our WLM environment, which was set up forexecuting DSNTPSMP, showing the relevant ddnames :

//************************************************************//**** Data sets required by the SQL Procedures Processor ****//************************************************************//SQLDBRM DD DISP=SHR, <== DBRM Library// DSN=DSN.DBRMLIB.DATA//SQLCSRC DD DISP=SHR, <== Generated C Source// DSN=DSN.SRCLIB.DATA//SQLLMOD DD DISP=SHR, <== Application Loadlib// DSN=DSN.RUNLIB.LOAD//SQLLIBC DD DISP=SHR, <== C header files// DSN=CEE.SCEEH.H// DD DISP=SHR,// DSN=CEE.SCEEH.SYS.H//SQLLIBL DD DISP=SHR, <== Linkedit includes// DSN=CEE.SCEELKED// DD DISP=SHR,// DSN=DSN.SDSNLOAD//SYSMSGS DD DISP=SHR, <== Prelinker msg file// DSN=CEE.SCEEMSGP(EDCPMSGE)//************************************************************//**** Workfiles required by the SQL Procedures Processor ****//************************************************************//SQLSRC DD UNIT=SYSDA,SPACE=(16000,(20,20)),// DCB=(RECFM=FB,LRECL=80)//SQLPRINT DD UNIT=SYSDA,SPACE=(16000,(20,20)),// DCB=(RECFM=VB,LRECL=137)//SQLTERM DD UNIT=SYSDA,SPACE=(16000,(20,20)),// DCB=(RECFM=VB,LRECL=137)//SQLOUT DD UNIT=SYSDA,SPACE=(16000,(20,20)),// DCB=(RECFM=VB,LRECL=137)//SQLCPRT DD UNIT=SYSDA,SPACE=(16000,(20,20)),// DCB=(RECFM=VB,LRECL=137)//SQLUT1 DD UNIT=SYSDA,SPACE=(16000,(20,20)),// DCB=(RECFM=FB,LRECL=80)//SQLUT2 DD UNIT=SYSDA,SPACE=(16000,(20,20)),// DCB=(RECFM=FB,LRECL=80)//SQLCIN DD UNIT=SYSDA,SPACE=(32000,(20,20))//SQLLIN DD UNIT=SYSDA,SPACE=(8000,(30,30)),// DCB=(RECFM=FB,LRECL=80)//SQLWORK1 DD UNIT=SYSDA,SPACE=(16000,(20,20)), <= Work C source// DCB=(RECFM=FB,LRECL=80)//SQLWORK2 DD UNIT=SYSDA,SPACE=(16000,(20,20)), <= Work LOADMOD// DCB=(RECFM=U)//SYSMOD DD UNIT=SYSDA,SPACE=(16000,(20,20)), <= PRELINKER// DCB=(RECFM=FB,LRECL=80

4.5.2.3 Output parameters of DSNTPSMPDepending on whether your SQL stored procedure was successfully generated,the output from your call to DSNTPSMP will be as follows:

• If your SQL stored procedure was successfully generated, the DBRM and loadmodule members are placed into the data sets referenced by the ddnames onthe WLM started task JCL. See "A" in Figure 61 on page 126.

128 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 145: Store Procedure

• If your SQL stored procedure was successfully generated, the caller ofDSNTPSMP (which might be SPB or your own client) must commit thechanges made to the DB2 tables. See "B" in Figure 61 on page 126. If thereare any problems found by DSNTPSMP, and rows are returned in the resultset, the caller must issue a ROLLBACK.

• When an unrecoverable error was received, DSNTPSMP will store alldiagnostic information into a temporary table and return these as a result setto the calling application (SPB Tool or your own) indicating the failing step anda return code. See "C" in Figure 61 on page 126. You need to code the normalresult set processing to process the messages received. For example:

• DESCRIBE PROCEDURE

• ASSOCIATE LOCATORS

• ALLOCATE CURSOR

• DESCRIBE CURSOR

See 4.5.2.5, “Example of a client program” on page 131 for a samplewritten in PL/1.

• Output received via the Output String (outstring) parameter. This contains theresults of your call to DSNTPSMP. You should pass an output parameter(empty variable) of length 255 when you invoke DSNTPSMP. The outstringparameter returns with zero condition code or error messages (see "D" inFigure 61 on page 126). For the time being, the outstring returned is only aninteger such as 0, 4, 8, and 999. No text is returned. This may be enhanced inthe future. Below, the text after the = sign is an explanation or programmeraction:

outstring: 0 = successful operation

4 = successful operation with warnings, look at result set

8 or higher = failure, look at result set

999 = severe internal error look at result set

Note: If you are using DSNTPSMP directly, the input source string should bebroken up into lines of code <=80 , with the separating character being anEBCDIC newline ('15'x) or linefeed ('25'x).

4.5.2.4 DSNTPSMP functionsFollowing are the functions performed by the OS/390 Procedure Processor:

• BUILD

This function goes through all the necessary steps for preparing an SQLstored procedure. The build process will terminate if the build is requested foran SQL stored procedure which already exists:

MEDSALRY already exists in SQLDBRM.

Figure 62 shows the steps executed in a BUILD process. Given the SQLstored procedure source as input:

1. DSNTPSMP defines the SQL stored procedure to DB2 by updating theDB2 tables SYSIBM.SYSPROCEDURES (v5) or SYSIBM.SYSROUTINESand SYSIBM.SYSPARMS (v6). The unmodified SQL stored proceduresource is stored in the SYSIBM.SYSPSM table, and the process optionsare stored in SYSIBM.SYSPSMOPTS.

SQL Procedures for DB2 UDB for OS/390 129

Page 146: Store Procedure

2. For DB2 version 5, the SQL Procedures pre-compiler is invoked totranslate the source to a C host language stored procedure with embeddedSQL.

3. A "normal" precompile is then done to produce a DBRM and a modifiedsource.

4. A bind is done to create a stored procedure package.

5. The modified source is compiled with the C compiler, pre-linked andlinkedited to produce an executable load module.

If BUILD abends halfway through this process, the caller (SPB or own client)must issue a ROLLBACK to back out of the updates made to the DB2 tables.

Figure 62. The BUILD process

Below is an example of a call to DSNTPSMP to perform a BUILD:

EXEC SQLCALL DSNTPSMP( :func,:proc-name,:PSM-source,:bnd-opt,:comp-opt, :pcomp-opt,:plnk-opt,:link-opt, :lert-opt,:in-dsname, :build-schema, :build-name, :out-var )END-EXEC.

• DESTROY

This function cleans up the definitions in the catalog and the members in thelibraries which are associated with the SQL stored procedure.

Figure 63 on page 131 shows the actions taken for the destroy process.

1. First the definition of the stored procedure is deleted fromSYSIBM.SYSPROCEDURES (v5) or dropped fromSYSIBM.SYSROUTINES and SYSIBM.SYSPARMS (v6).

2. The SQL stored procedure source is then deleted from SYSIBM.SYSPSMand SYSIBM.SYSPSMOPTS.

3. A drop package is done for the stored procedure package.

SQL proceduresource

SQLprecompiler

Cprecompiler

C source + embedded SQL

bind

PLAN

compile/pre-link

link

LOAD module

DB2 tables

1

2

3

45

130 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 147: Store Procedure

4. The load module, DBRM, and C source are deleted from the relevantlibraries referenced in the ddnames on the WLM JCL.

Figure 63. The DESTROY process

The parameters that need to be passed to DSNTPSMP are the function andthe procedure name. The other parameters can be empty (nulls).

CALL DSNTPSMP( :func,:proc-name,,,,,,,,, )

• REBUILD

Performs the same functions as BUILD but will overwrite any DB2 rows andlibrary members if necessary. It is generally performed against an existingSQL stored procedure but is also allowed for new non-existent routines. Theparameters passed are the same as for Build function.

• REBIND

This function will be used against an existing SQL stored procedure to changebind options and rebind the stored procedure package.

4.5.2.5 Example of a client programBelow is a sample of a PL/1 program which calls DSNTPSMP to perform a buildof an SQL stored procedure.

It can be coded generically enough so that only three parameters need to bepassed: function, procedure name, and the SQL stored procedure source dataset.

You would only need to compile it once. Using this program, the DBA or projectadministrator can control the compile, link, and bind options being used to createSQL stored procedures for their project.

PL/1 sample client program//*****************************************************//PSMBUILD JOB 'USER=JONATHAN','JONATHAN',CLASS=K,// MSGCLASS=H,MSGLEVEL=(1,1)//*****************************************************//* COMPILE/LINK THE CALLING APPLICATION//*****************************************************//STEPPROC EXEC PROC=DSNHPLIA,DB2LEV=DB2A,MEM=STUBPGM//PC.SYSIN DD *STUBPGM: PROCEDURE(PARMS) OPTIONS(MAIN );

EXEC SQL INCLUDE SQLCA;EXEC SQL INCLUDE SQLDA;

/**************************************************//* INPUT PARAMETERS/**************************************************/

Deletefrom

ddnames

Delete orDrop

procedure

Delete fromSYSPSM&

SYSPSMOPTS

Droppackage

SQL Procedures for DB2 UDB for OS/390 131

Page 148: Store Procedure

DECLARE PARMS CHAR(100) VARYING ;

DECLARE WHATTODO CHAR(8) VARYING;DECLARE SPNAME CHAR(8) VARYING;DECLARE SRCDSN CHAR(80) VARYING;

DECLARE space1 BIN FIXED(15);DECLARE space2 BIN FIXED(15);DECLARE parm_len BIN FIXED(15);

DECLARE action CHAR(20) VARYING;DECLARE member_name CHAR(18) VARYING;DECLARE psm_program CHAR(32672) VARYING;DECLARE bind_opts CHAR(1024) VARYING;DECLARE comp_opts CHAR(255) VARYING;DECLARE precomp_opts CHAR(255) VARYING;DECLARE prelink_opts CHAR(255) VARYING;DECLARE link_opts CHAR(255) VARYING;DECLARE le_opts CHAR(254) VARYING;DECLARE input_dsn CHAR(80) VARYING;DECLARE buildschema CHAR(8) VARYING;DECLARE buildname CHAR(18) VARYING;DECLARE out_string CHAR(255) VARYING;

DECLARE SP1RS SQL TYPE IS RESULT_SET_LOCATOR VARYING;DECLARE STEP CHAR(16);DECLARE FILE CHAR(8);DECLARE SEQN BIN FIXED(31);DECLARE LINE CHAR(255);

action = '';member_name = '';psm_program = '';bind_opts = '';comp_opts = '';precomp_opts = '';prelink_opts = '';link_opts = '';le_opts = '';input_dsn = '';buildschema = '';buildname = '';out_string = '';

buildschema='SYSPROC'; /* Schema name of builder */buildname='DSNTPSMP'; /* Builder name */

/**************************************************//* parse the input parameter to get - *//* function *//* SQL Procedure module name *//* SQL Procedure source dataset *//**************************************************/parm_len = length(parms);space1 = index(parms,' ');space2 = index(substr(parms,space1+1,parm_len-space1),' ');

132 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 149: Store Procedure

WHATTODO = SUBSTR(PARMS,1,space1-1);SPNAME = SUBSTR(PARMS,space1+1,space2-1);SRCDSN = SUBSTR(PARMS,space1+space2+1,parm_len-space1-space2);

PUT SKIP LIST('######################');PUT SKIP LIST('Function=',WHATTODO) ;PUT SKIP LIST('Progname=',SPNAME) ;PUT SKIP LIST('Dataset =',SRCDSN);PUT SKIP LIST('######################');CLOSE FILE(SYSPRINT) ;

SELECT (WHATTODO);WHEN('BUILDT') CALL program1; /* BUILD for debug */WHEN('BUILD') CALL program2; /* BUILD normally */WHEN('DESTROY') CALL program3; /* DESTROY */WHEN('REBUILD') CALL program4; /* REBUILD */WHEN('REBIND') CALL program6; /* REBIND */OTHERWISEDO;PUT SKIP LIST('** NO ACTION SPECIFIED, EXITING **');EXIT;

END;END;

/*********************************************************/

EXEC SQLCALL :BUILDNAME ( :action,

:member_name,:psm_program,:bind_opts,:comp_opts,:precomp_opts,:prelink_opts,:link_opts,:le_opts,:input_dsn,:buildschema,:buildname,:out_string)

;

IF SQLCODE¬=0 THENcall Print_SQLCA;

PUT SKIP LIST ('*** SQLCODE from call == ',sqlcode);

PUT SKIP LIST('** STUBPGM Call return from REXX stored proc **');PUT SKIP LIST ('REXX output parm follows.....');PUT SKIP EDIT('Returned outstring =', out_string) (A,A(100));

/* Will get result set only if errors received */PUT SKIP LIST ('Doing associate locators....');EXEC SQLASSOCIATE LOCATORS (:SP1RS) WITH PROCEDURE DSNTPSMP;IF (SQLCODE ¬=0) & (SQLCODE ¬= -482)THENcall Print_SQLCA;

SQL Procedures for DB2 UDB for OS/390 133

Page 150: Store Procedure

PUT SKIP LIST ('Doing allocate cursors....');EXEC SQLALLOCATE C1 CURSOR FOR RESULT SET :SP1RS;IF (SQLCODE¬=0) & (SQLCODE ¬= -423) THENcall Print_SQLCA;

PUT SKIP LIST ('** Result set follows **');do while (sqlcode=0);EXEC SQL FETCH C1 INTO :STEP, :FILE, :SEQN, :LINE ;

PUT SKIP DATA (LINE);end;PUT SKIP LIST ('** End of result set **');

program1: procedure;

comp_opts='LIST,TEST,LONGNAME';precomp_opts='SOURCE';prelink_opts='NOMAP,DEBUG(SHOWIO)';link_opts='AMODE=31,MAP,LIST=ALL';le_opts='TRAP(OFF),RPTOPTS(ON)';input_dsn=SRCDSN;action='BUILD';psm_program = '';bind_opts='PACKAGE(COLLID) ACT(REP) ISO(CS)';member_name=SPNAME;

end;

program2: procedure;

comp_opts='LIST';precomp_opts='SOURCE';prelink_opts='NOMAP';link_opts='AMODE=31,MAP';le_opts='TRAP(OFF),RPTOPTS(ON)';input_dsn=SRCDSN;action='BUILD';bind_opts='PACKAGE(COLLID) ACT(REP) ISO(CS)';member_name=SPNAME;

end;

program3: procedure;

action='DESTROY';member_name=SPNAME;

end;

program4: procedure;

call program1;action='REBUILD';

end;

134 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 151: Store Procedure

program6: procedure;

action='REBIND';comp_opts='LIST,TEST,LONGNAME';precomp_opts='SOURCE';prelink_opts='NOMAP,DEBUG(SHOWIO)';link_opts='AMODE=31,MAP,LIST=ALL';le_opts='TRAP(OFF),RPTOPTS(ON)';input_dsn=SRCDSN;psm_program = '';bind_opts='PACKAGE(COLLID)';member_name=SPNAME;

end;

Print_SQLCA: procedure;PUT SKIP EDIT('DUMP SQLCA BY FIELDS') (A);PUT SKIP EDIT('SQLCAID=',SQLCAID) (A,A(8));PUT SKIP EDIT('SQLCABC=',SQLCABC) (A,F(11));PUT SKIP EDIT('SQLCODE=',SQLCODE) (A,F(11));PUT SKIP EDIT('SQLERRM=',SQLERRM)(A,A(LENGTH(SQLERRM)));PUT SKIP EDIT('SQLERRP=',SQLERRP) (A,A(8));PUT SKIP EDIT('SQLERRD(1)=',SQLERRD(1)) (A,F(11));PUT SKIP EDIT('SQLERRD(2)=',SQLERRD(2)) (A,F(11));PUT SKIP EDIT('SQLERRD(3)=',SQLERRD(3)) (A,F(11));PUT SKIP EDIT('SQLERRD(4)=',SQLERRD(4)) (A,F(11));PUT SKIP EDIT('SQLERRD(5)=',SQLERRD(5)) (A,F(11));PUT SKIP EDIT('SQLERRD(6)=',SQLERRD(6)) (A,F(11));PUT SKIP EDIT('SQLWARN0=',SQLWARN0) (A,A(1));PUT SKIP EDIT('SQLWARN1=',SQLWARN1) (A,A(1));PUT SKIP EDIT('SQLWARN2=',SQLWARN2) (A,A(1));PUT SKIP EDIT('SQLWARN3=',SQLWARN3) (A,A(1));PUT SKIP EDIT('SQLWARN4=',SQLWARN4) (A,A(1));PUT SKIP EDIT('SQLWARN5=',SQLWARN5) (A,A(1));PUT SKIP EDIT('SQLWARN6=',SQLWARN6) (A,A(1));PUT SKIP EDIT('SQLWARN7=',SQLWARN7) (A,A(1));PUT SKIP EDIT('SQLWARN8=',SQLWARN8) (A,A(1));PUT SKIP EDIT('SQLWARN9=',SQLWARN9) (A,A(1));PUT SKIP EDIT('SQLWARNA=',SQLWARNA) (A,A(1));PUT SKIP EDIT('SQLSTATE=',SQLSTATE) (A,A(5));

end;

END STUBPGM;//LKED.SYSIN DD *INCLUDE SYSLIB(DSNELI)INCLUDE SYSLIB(DSNTIAR)NAME STUBPGM(R)//***************************************************//* BIND THE CALLING APPLICATION//****************************************************//STEPBND EXEC TSOBATCH,DB2LEV=DB2A//SYSTSIN DD *DSN SYSTEM(V51A)

FREE PACKAGE(COLLID.STUBPGM)FREE PLAN(SPMAINT)

SQL Procedures for DB2 UDB for OS/390 135

Page 152: Store Procedure

BIND PACKAGE(COLLID) MEMBER(STUBPGM)BIND PLAN(SPMAINT) PKLIST(DSNREXCS.DSNREXX, COLLID.STUBPGM)

//**********************************************************//* INVOKE THE CALLER//**********************************************************//STEPRUN EXEC TSOBATCH,DB2LEV=DB2A//SYSTSIN DD *DSN SYSTEM(V51A)

RUN PROGRAM(STUBPGM) -PLAN(SPMAINT) -PARMS('/BUILD MEDIANSALARY SG245485.SAMPLES.SOURCE(MEDSAL)')//*//* PARMS('/DESTROY MYTEST2 DUMMY')//* PARMS('/BUILD LT1PSM1 SG245485.SAMPLES.SOURCE(LT1PSM1)')//* PARMS('/REBUILD LT1PSM1 SG245485.SAMPLES.SOURCE(LT1PSM1)')

Once the calling program is compiled, the SQL stored procedure developer onlyneeds to execute STEPRUN when they want to generate their own SQL storedprocedure.

Below is the output received from the program above for a successful REBUILDof an SQL stored procedure:

######################Function= REBUILDProgname= MEDSALDataset = SG245485.SAMPLES.SOURCE(MEDSAL)######################*** SQLCODE from call == 0** STUBPGM Call return from REXX stored proc **REXX output parm follows.....Returned outstring =0Doing associate locators...Doing allocate cursors....** Result set follows **** End of result set **

Now that your SQL stored procedure is built, you can test it by building the clientapplication to call it, or testing it through the SPB Tool.

Note: DB2 delivers a sample C-language caller of DSNTPSMP called DSN8ED5.The sample job DSNTEJ65 shows how to prepare and run DSN8ED4 to callDSNTPSMP to prepare a sample SQL stored procedure called DSN8ES2.DSNTEJ65 also prepares and invokes a sample C-language caller of DSN8ES2called DSN8ED5.

4.5.3 Using JCLThe SQL stored procedure can also be prepared by invoking the DB2 suppliedJCL procedure DSNHSQL (4.5.3.2, “JCL for DSNHSQL procedure” on page 140).

See 4.5.3.1, “JCL for building an SQL stored procedure” on page 139 for aversion 5 example of the steps mentioned here:

136 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 153: Store Procedure

• DELCATG — Executes DSNTEP2. If definitions already exist for the storedprocedure, that is, you have already built it, this step deletes it fromSYSIBM.SYSPROCEDURES. If not, you will not need to execute this step.

In version 6, a DROP PROCEDURE is executed instead of the delete. Thisremoves the definition of your SQL stored procedure fromSYSIBM.SYSROUTINES and SYSIBM.SYSPARMS. An example of thisstatement follows:

DROP PROCEDURE SMP1LMS RESTRICT;

• PROCESS — Calls the DSNHSQL procedure which executes the followingsteps:

Figure 64. DSNHSQL process

1. For version 5, DSNHPSM is executed to convert your SQL storedprocedure source module into an equivalent C language program whichcontains the embedded SQL calls. In version 6, normally the precompilerDSNHPC is executed twice instead. The parameter used when callingDSNHPC for the first run is PARM='HOST(SQL)'.

Note: In version 6 for compatibility purposes, it will still be possible to runDSNHPSM instead of DSNHPC with PARM='HOST(SQL)'

2. DSNHPC is called with PARM=’HOST(C)’ to precompile the C sourcegenerated by the previous step to process the embedded SQL calls.

3. C compiler CBCDRVR is called to perform a normal C compile.

4. EDCPRLK is called to perform a normal pre-linkedit.

DSNHSQL process

DSNHPC converts SQL procedure source toC language source with embedded SQL

DSNHPSM converts SQL procedure sourceto C language source with embedded SQL

DSNHPC to process embedded SQL calls

CBCDRVR to compile the C program

EDCPRLK to pre-linkedit object module

IEWL to linkedit the pre-linked module

Step for v5(acceptable in v6)

Step for v6 only(if previous stepnot executed)

SQL Procedures for DB2 UDB for OS/390 137

Page 154: Store Procedure

5. IEWL is called to perform a normal linkedit.

• ISRTCATG — Executes DSNTIAD to register the definition for your SQLstored procedure to DB2. The statements generated are from the step whichexecutes the DSNHPSM precompile.

For DB2 version 5, a DML INSERT statement is generated to update theSYSIBM.SYSPROCEDURES table. For example:

INSERT INTO SYSIBM.SYSPROCEDURES(PROCEDURE, AUTHID, LUNAME, LOADMOD, LINKAGE, COLLID,LANGUAGE, ASUTIME, STAYRESIDENT, IBMREQD,RUNOPTS, PARMLIST, RESULT_SETS, WLM_ENV,PGM_TYPE, EXTERNAL_SECURITY, COMMIT_ON_RETURN)

VALUES('MEDSALRY','','','MEDSALRY','N','','SQL',0,' ','N','','DEPTNUM SMALLINT IN, MEDSALY SMALLINT OUT',0,'WLMENV1','M','N','N')

For DB2 version 6, a DDL CREATE PROCEDURE statement is generated todefine the procedure to SYSIBM.SYSROUTINES and SYSIBM.SYSPARMS.For example:

CREATE PROCEDURE SMP0LMS6( IN EMPLOYEE_NO CHAR ( 6 ) ,OUT EMP_FIRSTNAME VARCHAR ( 12 ) ,OUT EMP_LASTNAME VARCHAR ( 15 ) ,OUT SQLCPARM INTEGER )FENCED RESULT SET 0 LANGUAGE SQLDETERMINISTIC MODIFIES SQL DATA NO DBINFO COLLID SG245485WLM ENVIRONMENT WLMENV1 ASUTIME NO LIMIT STAY RESIDENT NOPROGRAM TYPE MAIN SECURITY DEFINER COMMIT ON RETURN NO

One row which defines your procedure is created in SYSIBM.SYSROUTINES.

The SYSIBM.SYSPARMS catalog table will contain one row for each input oroutput parameter required by your SQL stored procedure. In the exampleabove, four rows will be added.

• BINDSP — Binds the DBRM for your SQL stored procedure.

Note: If you did not specify the collection id in the CREATE PROCEDUREstatement, DB2 will not execute your SQL stored procedure even if yousubsequently bind the DBRM to a specific collection id in this step. If you wishto use the collection id of the client, specify NO COLLID. Later when you bindthe client package, you can then bind the SQL stored procedure package tothe same collection id and your SQL stored procedure will be executedsuccessfully.

• SELCATG — Executes DSNTEP2 to select from SYSIBM.SYSPROCEDURESto view the inserted values for the new procedure.

Note: DB2 delivers a sample job called DSNTEJ63 that demonstrates how to useDSNHSQL to prepare a sample SQL stored procedure called DSN8ES1. Thesample job DSNTEJ64 prepares and calls a sample caller of DSN8ES1 calledDSN8ED3.

138 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 155: Store Procedure

4.5.3.1 JCL for building an SQL stored procedureThis is the JCL used in DB2 version 5 to manually create stored procedures usingthe SQL Procedures language. The SQL stored procedures source is input inddname PC.SYSIN.

//BUILDER JOB 'USER=KATHLEEN','KATHLEEN',CLASS=A,// MSGCLASS=H,REGION=4096K//*----------------------------------//* BUILDING SOURCE -> BASECASE//*----------------------------------//JOBLIB DD DSN=CEE.SCEERUN,DISP=SHR <- IBM LE RUNTIME// DD DSN=DB2A.DSNEXIT,DISP=SHR <- DB2 USER EXITS// DD DSN=DB2A.DSNLOAD,DISP=SHR <- DB2 LOAD MODS//*********************************************************************//* DELETE FROM CATALOG THIS PROCEDURE//*********************************************************************//DELCATG EXEC TSOBATCH,DB2LEV=DB2A//SYSTSIN DD *DSN SYSTEM(V51A)RUN PROGRAM(DSNTEP2)//SYSIN DD *DELETE FROM SYSIBM.SYSPROCEDURES WHERE

PROCEDURE LIKE 'BASECASE%';//*//PROCESS EXEC DSNHSQL,MEM=BASECASE,// COND=(4,LT),// PARM.PC='HOST(SQL),SOURCE,XREF,MAR(1,72),STDSQL(NO)',// PARM.PCC='HOST(C),SOURCE,XREF,MAR(1,80),STDSQL(NO)',// PARM.C='SOURCE LIST MAR(1,80) NOSEQ LO RENT',// PARM.LKED='AMODE=31,RMODE=ANY,MAP,RENT'//PC.SYSUT1 DD DSN=&&SPDML,DISP=(,PASS),// UNIT=SYSDA,SPACE=(TRK,1),// DCB=(RECFM=FB,LRECL=80)//PC.SYSIN DD DISP=SHR,DSN=USER.SAMPLES.SOURCE(&MEM.)//LKED.SYSLMOD DD DSN=USER.RUNLIB.LOAD(&MEM.),// DISP=SHR//LKED.SYSIN DD *INCLUDE SYSLIB(DSNRLI)NAME BASECASE(R)//ISRTCATG EXEC PGM=IKJEFT01,DYNAMNBR=20//SYSTSPRT DD SYSOUT=*//SYSTSIN DD *DSN SYSTEM(V51A)RUN PROGRAM(DSNTIAD) PLAN(DSNTIAD)END//SYSPRINT DD SYSOUT=*//SYSUDUMP DD SYSOUT=*//SYSIN DD DSN=&&SPDML,DISP=(OLD,DELETE) <-FROM PRECEDING STEP//**********************************************************************//* BIND STEP//**********************************************************************//BINDSP EXEC TSOBATCH,DB2LEV=DB2A//SYSTSIN DD *DSN SYSTEM(V51A)BIND PACKAGE(COLLID) MEMBER(BASECASE) ACT(REP) ISO(CS)//*********************************************************************//* SELECT FROM CATALOG THIS PROCEDURE

SQL Procedures for DB2 UDB for OS/390 139

Page 156: Store Procedure

//*********************************************************************//SELCATG EXEC TSOBATCH,DB2LEV=DB2A//SYSTSIN DD *DSN SYSTEM(V51A)RUN PROGRAM(DSNTEP2)//SYSIN DD *SELECT * FROM SYSIBM.SYSPROCEDURES WHERE

PROCEDURE LIKE 'BASECASE%';

4.5.3.2 JCL for DSNHSQL procedureA sample of the JCL for DSNHSQL which was executed against a DB2 version 5environment is shown below. This JCL is supplied when you install the SQLProcedures support. It performs the steps described in Figure 64 on page 137.

//*********************************************************************//*//DSNHSQL PROC WSPC=500,MEM=TEMPNAME,USDN=USER//*//*********************************************************************//* PC: Precompile the PSM source//*********************************************************************//PC EXEC PGM=DSNHPSM,PARM='HOST(SQL)',REGION=4096K//STEPLIB DD DISP=SHR,DSN=DB2A.DSNEXIT// DD DISP=SHR,DSN=DB2A.DSNLOAD//SYSPRINT DD SYSOUT=*//SYSTERM DD SYSOUT=*//SYSUDUMP DD SYSOUT=*//SYSCIN DD DSN=&&DSNHSQL,DISP=(MOD,PASS),UNIT=SYSDA,// SPACE=(800,(&WSPC,&WSPC))//SYSLIB DD DISP=SHR,DSN=&USDN..SRCLIB.DATA//SYSUT1 DD DUMMY <-- DML to register PSM SP (V5 only)//SYSUT2 DD DUMMY <-DDL to register PSM SP (V6 and subsequent)//*//*********************************************************************//* PCC: Precompile C source generated by the previous step//*********************************************************************//PCC EXEC PGM=DSNHPC,REGION=4096K,// PARM='HOST(C),MAR(1,80)',// COND=(4,LT,PC)//DBRMLIB DD DISP=SHR,DSN=&USDN..DBRMLIB.DATA(&MEM)//STEPLIB DD DISP=SHR,DSN=DB2A.DSNEXIT// DD DISP=SHR,DSN=DB2A.DSNLOAD//SYSPRINT DD SYSOUT=*//SYSTERM DD SYSOUT=*//SYSUDUMP DD SYSOUT=*//SYSIN DD DSN=&&DSNHSQL,DISP=(OLD,DELETE)//SYSCIN DD DSN=&&DSNHOUT,DISP=(MOD,PASS),UNIT=SYSDA,// SPACE=(800,(&WSPC,&WSPC))//SYSLIB DD DISP=SHR,DSN=&USDN..SRCLIB.DATA//SYSUT1 DD SPACE=(800,(&WSPC,&WSPC),,,ROUND),UNIT=SYSDA//SYSUT2 DD SPACE=(800,(&WSPC,&WSPC),,,ROUND),UNIT=SYSDA//*//*********************************************************************//* C: Compile the output from the precompiler//*********************************************************************//C EXEC PGM=CBCDRVR,REGION=4096K,// PARM=('MAR(1,80) NOSEQ LO RENT'),// COND=((4,LT,PC),(4,LT,PCC))

140 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 157: Store Procedure

//STEPLIB DD DSN=CBC.SCBCCMP,DISP=SHR// DD DSN=CEE.SCEERUN,DISP=SHR//SYSLIB DD DSN=CEE.SCEEH.H,DISP=SHR// DD DSN=DB2A.SDSNC.H,DISP=SHR//SYSLIN DD DSN=&&LOADSET,DISP=(MOD,PASS),UNIT=SYSDA,// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//SYSPRINT DD SYSOUT=*//SYSCPRT DD SYSOUT=*//SYSTERM DD DUMMY//SYSIN DD DSN=&&DSNHOUT,DISP=(OLD,DELETE)//SYSUT1 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//SYSUT2 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//SYSUT3 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//SYSUT4 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//SYSUT5 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=3200,BLKSIZE=12800)//SYSUT6 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=3200,BLKSIZE=12800)//SYSUT7 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=3200,BLKSIZE=12800)//SYSUT8 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=3200,BLKSIZE=12800)//SYSUT9 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=VB,LRECL=137,BLKSIZE=882)//SYSUT10 DD SYSOUT=*//SYSUT14 DD UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=3200,BLKSIZE=12800)//*//*********************************************************************//* PLKED: Pre-linkedit the object module from the C compiler//*************************************************************//PLKED EXEC PGM=EDCPRLK,REGION=2048K,// COND=((4,LT,PC),(4,LT,PCC),(4,LT,C))//STEPLIB DD DSN=CEE.SCEERUN,DISP=SHR//SYSMSGS DD DSN=CEE.SCEEMSGP(EDCPMSGE),DISP=SHR//SYSLIB DD DUMMY//SYSIN DD DSN=&&LOADSET,DISP=(OLD,DELETE)//SYSMOD DD DSN=&&PLKSET,UNIT=SYSDA,DISP=(MOD,PASS),// SPACE=(32000,(30,30)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//SYSOUT DD SYSOUT=*//SYSPRINT DD SYSOUT=*//*

SQL Procedures for DB2 UDB for OS/390 141

Page 158: Store Procedure

//*************************************************************//* LKED: Linkedit the output from the pre-linkeditor//*************************************************************//LKED EXEC PGM=IEWL,PARM='MAP',// COND=((4,LT,PC),(4,LT,PCC),(4,LT,C),(4,LT,PLKED))//SYSLIB DD DSN=CEE.SCEELKED,DISP=SHR// DD DSN=DB2A.DSNLOAD,DISP=SHR//SYSLIN DD DSN=&&PLKSET,DISP=(OLD,DELETE)// DD DDNAME=SYSIN//SYSLMOD DD DSN=&USDN..RUNLIB.LOAD(&MEM),DISP=SHR//SYSPRINT DD SYSOUT=*//SYSUT1 DD SPACE=(32000,(30,30)),UNIT=SYSDA//*//DSNHSQL PEND

Once the SQL stored procedure is created and its definition registered in DB2,you can test it by invoking it from a client application or by using the SPB Tool.Through the SPB Tool, all you need to do is to insert a connection to the OS/390database, highlight the relevant procedure, and choose the RUN button.

Note: If your SQL stored procedure does not return any output, you must check ifit was linked and bound correctly.

If the procedure is created manually (not using the OS/390 ProceduresProcessor), the definition for your SQL stored procedure will not be inserted intothe tables SYSIBM.SYSPSM or SYSIBM.SYSPSMOPTS. Therefore, the sourcecannot be viewed through the SPB Tool automatically.

If you wish to view the source using the SPB Tool, you need to download the SQLstored procedure source to the workstation environment, where the SPB isinstalled, and save it in any directory. After that, when you choose the Get Sourceoption, you can then point to where you have saved it. See Chapter 3, “The DB2Stored Procedure Builder” on page 57 for more details on this option.

You can even choose to save all your SQL stored procedure source for yourproject in a shared drive. This could be important in an environment where theDB2 application developer or DB2 administrator wishes to keep track of thestored procedures for tuning or maintenance purposes through the SPB Tool.

4.6 Stored procedure debugging

Regardless of the method used to build your SQL stored procedure, you caninvoke the Debug tool to debug it.

To debug your SQL stored procedure on OS/390, you need to install the Remotedebugger client code on your workstation. Refer to 3.4.6, “Debugging storedprocedures” on page 105, for detailed information about how to install andactivate the client debugger.

142 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 159: Store Procedure

4.6.1 ProcessOn the OS/390 side, you need to perform the following steps:

• Concatenate the debug load modules in the STEPLIB within your WLM region.

• Create your SQL stored procedure specifying the RUN OPTIONS keyword inyour SQL source:

CREATE PROCEDURE MYPROC(INOUT P1 CHAR(6), IN P2 DATE, IN P3 TIME, IN P4 TIMESTAMP)LANGUAGE SQLRUN OPTIONS ’POSIX(ON),TEST(ALL,*,,VADTCPIP&9.112.111.13:*)’LABEL1: BEGIN

........END LABEL1

In this example, 9.112.111.13 is the IP address of the workstation where youwill be monitoring the debugger output of your SQL stored procedure. It will bethe machine on which you have activated the listener. The debugger screenswill be activated on this machine.

• Compile your SQL stored procedure with the TEST compile option and OPT(0).We recommend that you do not compile using options TEST and OPT(1) orOPT(2). Programs compiled with both the TEST option and either the OPT(1) orOPT(2) options do not have line hooks, block hooks, path hooks or a symboltable generated, regardless of the TEST suboptions specified. Refer to DebugTool: User's Guide and Reference, SC09-2137.

• Ensure that your input C file (not output listing) to the C compile is created ona permanent data set. When using batch JCL to create your SQL storedprocedure, this will be the dataset (in the sample JCL procedure DSNHSQL)called &&DSNHOUT which is normally allocated as a temporary dataset. Whencreating your SQL stored procedure using SPB or DSNTPSMP, this dataset ispermanently allocated anyway.

• Run the SQL stored procedure and the debugger screens will appear on themachine identified by the TCPIP address selected above.

4.6.2 If the debugger does not startIf your debugger does not start, check that the following things have been done:

• The client listener has been started.

• The correct SPAS or WLM JCL is being used.

• IP address is correct.

• The RUN OPTIONS are specified correctly (for example, a wrong number ofcommas might have been used).

• The TEST option has been specified on the C compile.

• The input C file to the C compile has been made a permanent dataset (pleasenote that it is the input file that is required — not the output listing).

SQL Procedures for DB2 UDB for OS/390 143

Page 160: Store Procedure

144 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 161: Store Procedure

Chapter 5. SQL Procedures for DB2 UDB for UNIX, Windows, OS/2

This chapter describes the support for the new SQL Procedures language in DB2UDB servers. During this project we use Windows NT and UNIX platforms.

5.1 General considerations

SQL Procedures is an easy-to-use, simple language, which provides a series oflanguage elements that allow you to develop block-structured stored procedures,with exception handling, flow control, variable declarations, and so on. Using theSQL Procedures language, you have the same functions and performance aswhen using other supported languages, such as multiple parameters (input,output, input/output), returning multiple output result sets, and so on. However,the SQL Procedures language is easier for all developers to use, and isespecially easy to learn for those developers familiar with Sybase, Oracle,Informix, and Microsoft SQL Server proprietary languages.

SQL stored procedures are created using the CREATE PROCEDURE statementand are registered in the DB2 catalog. There are four tables in the DB2 UDBcatalog that contain information related to stored procedures:

• SYSIBM.SYSPROCEDURES: Contains a row for each stored procedure thatis created

• SYSIBM.SYSPROCPARMS: Contains a row for each parameter of everystored procedure.

• SYSIBM.SYSPROCOPTIONS: Each row contains procedure-specific optionvalues.

• SYSIBM.SYSPROCPARMSOPTIONS: Each row contains procedureparameter specific option values.

The source code of SQL stored procedures is stored in the DB2 catalog. TheTEXT column of SYSIBM.SYSPROCEDURES table contains the source of yourSQL stored procedure. You can easily access the source code using a SELECTstatement.

There are no changes related to coding client programs to invoke SQL storedprocedures. The syntax of the SQL CALL statement is the same regardless of thelanguage being used at the server stored procedure.

The support for SQL stored procedures in DB2 UDB is implemented through thegeneration of an intermediary C code. This C code is precompiled, compiled, andlink-edited automatically, and an executable file (.DLL in Windows NT) isgenerated for the stored procedure. For more details, refer to 5.5, “Storedprocedures preparation” on page 159.

The IBM Distributed Debugger can be used to remotely debug SQL storedprocedures executing on the DB2 UDB server. With the IBM DistributedDebugger you can follow the execution of your SQL stored procedure using thesource code, verify and change values for variables, etc. For more information ondebugging, refer to 5.6, “Stored procedure debugging” on page 166.

Stored procedures written in the SQL Procedures language are portable to DB2servers in other platforms with no changes or minimal changes to the sources.

© Copyright IBM Corp. 1999 145

Page 162: Store Procedure

When other database management systems (DBMS) implement languagescompatible with the SQL/PSM standard, it should be possible to port storedprocedures from DB2 to other DBMSs and vice versa.

5.2 Supported platforms

SQL Procedures language will be supported in all DB2 UDB platforms: UNIX,Windows and OS/2. However, the first releases (beta code) of SQL Proceduresare only supported on Windows NT, AIX, and Sun Solaris. The support for otherplatforms will follow shortly.

The remote debugging of DB2 UDB stored procedures is only available forservers on Windows NT, AIX, Sun Solaris, and OS/2. The IBM DistributedDebugger client executes only on Windows NT.

5.3 System requirements and planning

This section describes the requirements for using SQL Procedures with DB2 UDBservers.

Before creating SQL stored procedures, you must ensure that DB2 SDK isinstalled on your DB2 UDB server. This is required because the process thatcreates the SQL stored procedures on the server generates a C source that mustbe prepared using SDK functionality. You do not need to have DB2 SDK installedin the developer’s client workstation, unless you plan to use SPB to build yourstored procedures. It is recommended that you install SDK in the developer’sworkstation so they can benefit from the samples and manuals included in SDK,and also, to allow the developers to create client applications running on theirworkstations. Refer to Chapter 3, “The DB2 Stored Procedure Builder” on page57 for more information about DB2 SPB.

Note that SPB is not a prerequisite to work with SQL stored procedures. The SQLProcedures language support is built into DB2 UDB base code, and you cancreate your SQL stored procedures using only the DB2 command line, or anyother user interface that allows you to issue a CREATE PROCEDURE command.

5.3.1 Requirements for the Windows NT platformTo work with SQL Procedures, you must ensure that a C compiler supported byDB2 SDK is installed in your DB2 UDB server. For DB2 UDB servers executingon Windows NT platforms, initially the only C compiler supported is:

• Microsoft Visual C++ Version 5.0 and 6.0

The IBM VisualAge C compiler should be supported in future releases.

Some customization in the C environment is required to use SQL Procedures.On the Windows NT platform, there are two possible ways to customize yourC environment: using DB2 registry variables, or using NT system variables.

5.3.1.1 Customizing the C environment using the DB2 registryDB2 UDB has a registry variable DB2UDP_COMPILER_PATH that can be set,when you plan to use SQL Procedures. This registry variable should contain thename of a script file that initializes the C compiler environment. DB2 UDB

146 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 163: Store Procedure

executes the command stored in the DB2UDP_COMPILER_PATH automatically,when you issue a CREATE PROCEDURE statement for an SQL storedprocedure.

You can set the DB2UDP_COMPILER_PATH DB2 registry variable using thedb2set command, as follows:

db2set DB2UDP_COMPILER_PATH=initscript

In our project, we used the sample udpprof.bat file for initialization. This file islocated in x:\sqllib\samples\udp, where x: is the drive on which you haveinstalled DB2 SDK. If you plan to use the sample script, you can issue thefollowing:

db2set DB2UDP_COMPILER_PATH=c:\sqllib\samples\udp\udpprof.bat

You must customize the sample udpprof.bat script according to your developmentenvironment. If the initialization script does not contain the correct settings, or theDB2UDP_COMPILER_PATH does not point to the right script, you will not be ableto create SQL stored procedures. For example, the following shows theudpprof.bat file used in our project:

udpprof.batset VC_DRIVE=c:\progra~1\devstu~1set include=%VC_DRIVE%\vc\include;%VC_DRIVE%\vc\atl\include;%VC_DRIVE%\vc\mfc\include;%include%set lib=%VC_DRIVE%\vc\lib;%lib%set path=%VC_DRIVE%\sharedide\bin\ide;%VC_DRIVE%\sharedide\bin;%VC_DRIVE%\vc\bin;%path%

5.3.1.2 Customizing the C environment using system variablesOn the Windows NT environment, instead of using theDB2UDP_COMPILER_PATH DB2 registry variable, you have the option of usingNT system environment variables. SQL Procedures support requires thefollowing variables to be at system level for the DB2 server operatingenvironment:

• INCLUDE

• LIB

• PATH

When you install Microsoft Visual C++, it defines these variables as uservariables. For SQL Procedures, you must define these variables as systemvariables. To copy from a user variable into a system variable follow the stepsbelow:

1. Start -> Settings -> Control Panel -> System -> Environment tab2. Click on the required variable name in the User Variables list box3. Highlight the entry in the Value entry field and click Edit -> Copy4. Click on the required variable name in the System Variables list box5. Check the differences between user and system variable values and modify

the values in the system variable as appropriate in the Value entry field

Once this has been done for all the three variables required, reboot the machine.

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 147

Page 164: Store Procedure

5.3.2 Requirements for the UNIX platformTo work with SQL Procedures, you must ensure that a C compiler supported byDB2 SDK is installed in your DB2 UDB server. For DB2 UDB servers executingon the UNIX platform, to create SQL stored procedures, you must:

• Install the DB2 SDK on your DB2 server.

Ensure that the C compiler supported by the DB2 SDK on your platform isinstalled and configured on your DB2 server.

• Install a supported C compiler.

• SQL Procedures support is available for the following C compilers on AIXVersion 4.2 and later:

• IBM C for AIX Version 3.1.4 and 3.6.4

• SQL Procedures support is available for the following C compilers on SunSolaris Version 2.5.1, 2.6, and 2.7 (Solaris 7):

• SPARCompiler C Version 4.2

• SPARCompiler C Version 5.0

• Initialize the environment for SQL Procedures.

To enable the DB2 server to create SQL stored procedures, you must set theDB2_SQLROUTINE_COMPILER_PATH DB2 registry variable. When you issue aCREATE PROCEDURE statement for an SQL stored procedure, DB2executes the command stored in the DB2_SQLROUTINE_COMPILER_PATH registryvariable to initialize the C compiler environment. You can store the commandto call an initialization script in the DB2_SQLROUTINE_COMPILER_PATH using thefollowing syntax:

db2set DB2_SQLROUTINE_COMPILER_PATH="<initscript>"

where <initscript> represents the command you use to call an initializationscript for the C compiler on your platform.

• Set up the environment for SQL Procedures

The Solaris and AIX platforms contain a sample initialization script calledudppro in the $DB2PATH/samples/sqlproc directory, where $DB2PATH representsthe directory in which you have created your DB2 instance. For example, ifyou create a DB2 instance in the /home/db2inst1 directory, you can set theDB2_SQLROUTINE_COMPILER_PATH DB2 registry variable to call the sampleinitialization script with the following command:

db2set DB2_SQLROUTINE_COMPILER_PATH=". $DB2PATH/samples/sqlproc/udpprof"

where $DB2PATH represents the directory in which you have created yourDB2 instance.

Note: You should use the udpprof sample script only as a basis fordeveloping your own initialization script. You must customize the script tocorrespond to your own operating system and compiler environment. If theinitialization script contains the wrong settings, does not have executablepermissions, or if the DB2_SQLROUTINE_COMPILER_PATH DB2 registry variable isnot set to run the script, you will not be able to create SQL storedprocedures.

148 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 165: Store Procedure

5.3.3 Changing compiler optionsIf you want to customize your C compiler options for SQL Procedures, you muststore the entire command line, including all options, in the DB2 registry variablewith the following command:

db2set DB2_SQLROUTINE_COMPILE_COMMAND=<compiler_command>

where <compiler_command> represents the C compiler command and all of theoptions and parameters required to create SQL stored procedures.

5.3.3.1 Windows NTOn Windows NT, the default value for DB2_SQLROUTINE_COMPILE_COMMAND is:

"cl -0d -W2 /TC -D_X86_=1-IE:\SQLLIB\include sqlroutine_filename.c /link -dll-def:sqlroutine_filename.def /out:sqlroutine_filename.dllE:\SQLLIB\lib\db2api.lib"

Note: To return debug information, you must set this variable using a commandsuch as the following:

db2set DB2_SQLROUTINE_COMPILE_COMMAND="cl -0d -W2 /TC -D_X86_=1 -Z7-IE:\SQLLIB\include sqlroutine_filename.c /link -dll-def:sqlroutine_filename.def /out:sqlroutine_filename.dll-debug:full -pdb:none -debugtype:cv E:\SQLLIB\lib\db2api.lib"

where:

sqlroutine_filename represents the placeholder for the filename used in thegenerated files such as SQC, C, PDB DEF files, EXPfiles, messages log, and DLL files

sqlroutine_entry represents the entry point name

E:\ represents the location of the instance directory

To return to the default compiler options, clear the DB2 registry value forDB2_SQLROUTINE_COMPILE_COMMAND with the following command:

db2set DB2_SQLROUTINE_COMPILE_COMMAND=

5.3.3.2 AIXOn AIX, the default value for DB2_SQLROUTINE_COMPILE_COMMAND is:

"xlC_r -+ -H512 -T512 -I/home/myusr/sqllib/includesqlroutine_filename.c -bE:sqlroutine_filename.exp -esqlroutine_entry -o sqlroutine_filename -L/home/myusr/sqllib/lib -lc -ldb2"

Note: To return debug information, you must set this variable using a commandsuch as the following:

db2set DB2_SQLROUTINE_COMPILE_COMMAND="xlC_r -+ -H512 -T512 -g-I/home/myusr/sqllib/include sqlroutine_filename.c-bE:sqlroutine_filename.exp -e sqlroutine_entry-o sqlroutine_filename -L/home/myusr/sqllib/lib -lc -ldb2"

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 149

Page 166: Store Procedure

where:

sqlroutine_filename represents the placeholder for the filename used in thegenerated files such as SQC, C, PDB DEF files, EXPfiles, messages log, and shared library files

sqlroutine_entry represents the entry point name

home/myusr/ represents the location of the instance directory

5.3.3.3 SolarisOn Solaris, the default value for DB2_SQLROUTINE_COMPILE_COMMAND is:

"cc -# -Kpic-I/disks/home1/myusr/sqllib/include sqlroutine_filename.c-G -o sqlroutine_filename -L/disks/home1/myusr/sqllib/lib-R/disks/home1/myusr/sqllib/lib -ldb2"

Note: To return debug information, you must set this variable using a commandsuch as the following:

db2set DB2_SQLROUTINE_COMPILE_COMMAND="cc -# -Kpic -g-I/disks/home1/myusr/sqllib/include sqlroutine_filename.c -G -osqlroutine_filename -L/disks/home1/myusr/sqllib/lib-R/disks/home1/myusr/sqllib/lib -ldb2"

where:

sqlroutine_filename represents the placeholder for the filename used in thegenerated files such as SQC, C, PDB DEF files, EXPfiles, messages log, and shared library files

sqlroutine_entry represents the entry point name

/disks/home1/myusr/ represents the location of the instance directory

5.3.4 Retaining intermediate filesIssuing an SQL Procedures CREATE PROCEDURE statement, DB2 creates anumber of intermediate files that are normally deleted if DB2 successfullycompletes the statement. If an SQL stored procedure does not perform asexpected, you might find it useful to examine the SQC, C, PDB, and message logfiles created by DB2. To keep the files that DB2 creates during the successfulexecution of a CREATE PROCEDURE statement, you must set the value of theDB2_SQLROUTINE_KEEP_FILES DB2 registry variable to 1. This can be done throughthe following command:

db2set DB2_SQLROUTINE_KEEP_FILES=1

The intermediate files will be retained by DB2 in the following directories:

• Windows NT

%DB2PATH%\function\routine\udp\%$DATABASE%\%SCHEMA%

where:

%DB2PATH% represents the instance directory

%DATABASE% represents the database name

%SCHEMA% represents the schema name with which the SQL storedprocedures were created

150 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 167: Store Procedure

• AIX, Solaris

$DB2PATH/function/routine/sqlproc/$DATABASE/$SCHEMA

where:

$DB2PATH represents the instance directory

$DATABASE represents the database name

$SCHEMA represents the schema name with which the SQL storedprocedure were created

5.4 Coding considerations

This section presents some considerations on coding SQL stored procedures forDB2 UDB. Most of the considerations and techniques described here are valid forWindows and UNIX servers, and any topic that applies only to one type of serverwill be clearly identified.

This section does not provide detailed information about the syntax of the SQLProcedures language. Some examples are provided, but for more information onthe SQL Procedures language refer to Chapter 2, “The SQL Procedureslanguage” on page 9.

5.4.1 Recommendations for writing portable stored proceduresMake sure that the builtin functions you use in your stored procedure aresupported on all the target DB2 platforms you will use.

5.4.2 Structure of SQL stored proceduresAn SQL stored procedure consists of two main blocks:

• A CREATE PROCEDURE statement to define the procedure

• A procedure body with SQL statements and SQL control statements

5.4.2.1 The CREATE PROCEDURE statementThe CREATE PROCEDURE statement is used to register a stored procedure inthe DB2 server. For SQL stored procedures, most of the options of the CREATEPROCEDURE statement are not valid, because these options are related toexternal stored procedures.

For SQL stored procedures, using the CREATE PROCEDURE statement, youcan specify the list of parameters being passed to or from the stored procedure,an specific name for the procedure, the number of result sets being returned, andif the stored procedure reads or modifies SQL data. Following is a typicalCREATE PROCEDURE statement for an SQL stored procedure:

CREATE PROCEDURE SQL1LNS (IN PARM1 CHAR(10), OUT PARM2 INTEGER) SPECIFICS4141979 RESULT SETS 1 READS SQL DATA LANGUAGE SQL BEGIN .... END

With DB2 UDB, you can have various procedures with the same procedure name,as long as they have different specific names, and a different number ofparameters. DB2 UDB recognizes which of the procedures with the same nameyou are actually calling, by comparing the number of parameters being passedand the number of parameters defined in the catalog. Note that DB2 UDB only

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 151

Page 168: Store Procedure

counts the number of parameters; that is why you must have a different number ofparameters for procedures with the same name.

For SQL stored procedures, you cannot specify the following options of theCREATE PROCEDURE statement:

• NO SQL

• FENCED/NOT FENCED

• DETERMINISTIC/NOT DETERMINISTIC

• CALLED ON NULL INPUT

• DBINFO/NO DBINFO

• EXTERNAL

• PARAMETER STYLE

• PROGRAM TYPE

The above options can only be used with external stored procedures. If you try tocode your CREATE PROCEDURE statement for an SQL stored procedure usingany of the above options, you will receive the following message:

SQL0628N Multiple or conflicting keywords involving the "<invalid attributefor SQL procedure>" clause are present. SQLSTATE=42613

SQL stored procedures execute as NOT FENCED, unless they are returningresult sets to the calling program. If the SQL stored procedure returns result sets,it executes as a FENCED stored procedure. This is done internally, and youcannot change the mode of execution of your SQL stored procedure.

5.4.2.2 Defining parametersIf your SQL stored procedure needs to send/receive parameters from the clientprogram, you must define them in the CREATE PROCEDURE statement.

You can define input, output, or input/output parameters of any supported SQLdata types. The following data types are not supported:

• VARGRAPHIC

• LONG VARGRAPHIC

• BLOB

• CLOB

• DBCLOB

• DATALINK

User Defined Data types (UDTs) are not supported, even if they are based onsupported SQL data types.

5.4.3 Coding the SQL stored procedures bodyThe stored procedures body in an SQL stored procedure contains the sourcestatements for the stored procedure. The stored procedures body can contain asingle SQL statement or a compound SQL statement. Following is an example ofan SQL stored procedure with a single SQL statement:

CREATE PROCEDURE SQL2LNS (OUT PARM1 CHAR(10))

152 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 169: Store Procedure

LANGUAGE SQLSET PARM1=’FELIPE’

A stored procedures body with a compound SQL statement must be delimited bya BEGIN and an END statement. Following is an example of an SQL storedprocedure with a compound SQL statement:

CREATE PROCEDURE SQL3LNS (OUT PARM1 CHAR(10), OUT PARM2 CHAR(10))LANGUAGE SQLP1:BEGIN

SET PARM1=’ALINE’SET PARM2=’RICARDO’

END P1

A compound SQL statement may have a label associated to it. In the aboveexample, the label P1 was set for the compound SQL statement. The labels inyour SQL stored procedures body must be unique, and must not be the same asthe name of the stored procedure. Any variables within a labeled compound SQLstatement may be prefixed with the label, if necessary. See 5.4.3.2, “Definingvariables in SQL stored procedures” on page 153 for more details.

5.4.3.1 Statements in the stored procedures bodyThe SQL stored procedures body may contain SQL statements and SQL controlstatements. All executable SQL statements can be contained within an SQLstored procedures body, with the exception of the following:

• COMMIT

• CONNECT

• DISCONNECT

• RELEASE

• SET CONNECTION

• REVOKE

Note: The above restrictions are intended to be removed in future releases ofSQL Procedures support in DB2 UDB. Check your DB2 UDB manuals, to verify ifthese restricitions still apply.

SQL control statements can be assignment statements, CASE statements, IFstatements, LOOP statements, and others, as defined in SQL Procedures. Formore information regarding the syntax of the different SQL Procedures controlstatements, please refer to Chapter 2, “The SQL Procedures language” on page9.

5.4.3.2 Defining variables in SQL stored proceduresWithin a compound SQL statement you can declare SQL variables that can bereferenced in other statements in the stored procedure using the DECLAREstatement.

Recommended naming for parameters and variables:You do not need to declare your parameters as variables within your storedprocedure. Your parameter description provides DB2 enough information tounderstand what the names and datatypes of the parameters are.

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 153

Page 170: Store Procedure

Name your local variables with different names than the parameters to yourstored procedure. If you choose not to do this, then references to the ambiguousname will be interpreted as the local variable and not the parameter. To referencea parameter in this situation, you must qualify it with the stored procedure name.Figure 65 is an example of using variables and parameters with the same name.

Figure 65. Using the same name for variables and parameters

Note that the variable v_var2 does not have the same data type as the parameter,but DB2 handles data type conversions whenever possible.

You should avoid variables with the same name as DB2 table columns. If youhave a variable with the same name as a table column, you must also qualify thevariable in SQL statements with the compound statement label. If you do notqualify the variable, DB2 will interpret that variable as the column name. Figure66 is an example of using a variable and a column with the same name.

Figure 66. Using variables with the same name as a column

Note that it is not necessary to qualify the variable in the INTO clause, only in theWHERE condition.

Naming your parameters and your local variables with the same name.

Avoid:

CREATE PROCEDURE DRDARES1.SMP4LNS (out v_var1 integer, outv_var2 double )

SPECIFIC DRDARES1.S1473953LANGUAGE SQL

P1: BEGINdeclare v_var1 integer;declare v_var2 smallint;

set v_var1 = 10;set smp4lns.v_var1 = p1.v_var1;set v_var2 = 20;set smp4lns.v_var2 = p1.v_var2;

END P1

CREATE PROCEDURE DRDARES1.SMP5LNS (out p_id integer )LANGUAGE SQL

P1: BEGINdeclare id integer;set id = 100;select id into id from staff where id=p1.id;set p_id = id;

END P1

154 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 171: Store Procedure

In variable declarations you can specify a default value. If a default value is notspecified, the variable is initialized to NULL.

5.4.3.3 Assigning values to variablesThe SET statement is used to assign values to variables and parameters. WithDB2 UDB, the value being assigned to the variable may be a constant, anexpression, a DB2 special register, a result of a SELECT statement, and so on.Figure 67 is an example of assigning special register values to parameters inSQL stored procedures.

Figure 67. Assigning special registers to variables

You can also assign the result of DB2 UDB built-in functions or User DefinedFunctions(UDFs) to variables or parameters. However, you should keep in mindthat using DB2 UDB functions, may limit the portability of your SQL storedprocedures, since some of the built-in functions or UDFs might not be available inother DB2 servers, such as DB2 for OS/390 Version 5. Figure 68 is an example ofassigning results of built-in functions to variables.

CREATE PROCEDURE DRDARES1.SMP2LNS ( out v_user char(8), outv_date1 date,out v_date2 date, out v_days1 integer, out v_time1 time,out v_time2 time, out v_timest1 timestamp, out v_timest2timestamp)

SPECIFIC DRDARES1.S5336343LANGUAGE SQL

P1: BEGINset v_user = user;set v_date1 = current date;set v_date2 = v_date1 - 10 days + 3 years;set v_days1 = days(v_date2);set v_time1 = current time;set v_time2 = v_time1 +1 hour - 30 minutes;set v_timest1 = current timestamp;set v_timest2 = v_timest1 - days(v_date1 - 10 days) days;

END P1

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 155

Page 172: Store Procedure

Figure 68. Assigning results of built-in functions to variables

5.4.3.4 Handling errorsIn DB2 UDB SQL stored procedures, you can make references in your storedprocedures body code to SQLCODE or SQLSTATE. All you need to do is todeclare them previously in your stored procedures body.

We strongly recommend that you use handlers for finding and handling errorconditions in your SQL stored procedure. This is the only choice you should makeif you intend for your SQL stored procedure to be portable across DB2 platforms.Here is an example of how to do this:

CREATE PROCEDURE PROC1()LANGUAGE SQLBEGIN

DECLARE SQLCODE INTEGER DEFAULT 0;DECLARE SQLSTATE CHAR(5) DEFAULT ’00000’;

.......END

Avoid checking SQLCA or SQLSTATE values. This is a tricky area and there aresome platform differences. If you do use SQLSTATE or SQLCA checks explicitlyin your SQL stored procedure, please note that you can only check one of thesevalues.

You can declare program variables to hold the SQLCODE or the SQLSTATE fordifferent tests. Keep in mind that you have to choose one of these variables,SQLCODE or SQLSTATE, because the second assignment statement will not getthe return code of the original statement, but from the previous one. Figure 69shows an example of trying to set both variables in an SQL stored procedure.

CREATE PROCEDURE DRDARES1.SMP8LNS (out v1 double, out v2 double,out v3 integer, out v4 integer , out v5 integer,out v6 integer , out v7 char (5),out v8 char(10), out v9char(10), out v10 char (20), out v11 char(5), out v12 char(10))

SPECIFIC DRDARES1.S8389109LANGUAGE SQLP1: BEGIN

set v1 = tan(.5) - (sin(.5)/cos(.5));set v2 = exp(sin(.3)) + exp(cos(.3));set v3 = rand();set v4 = ceil(5.2) + floor(4.3);set v5 = quarter(current date);set v6 = week(current date);set v7 = repeat('*',5);set v8 = lcase('ALINE');set v9 = replace('a1b1c1','1','2');set v10 = monthname(current date) || dayname(current date);set v11 = ltrim('felipe ');set v12 = substr('abcdefghijklmnopq',5,10);

END P1

156 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 173: Store Procedure

Figure 69. Setting both SQLCODE and SQLSTATE variables to program variables

Note that in Figure 69, when you execute the SELECT statement: (1) if the row isnot found, automatically DB2 UDB sets SQLCODE to 100 and SQLSTATE to’02000’. The SET stament (2) sets the program variable SQLC correctly to thevalue of SQLCODE, then SQLC is set to 100. However, the SET statement alsoresets the values of SQLCODE and SQLSTATE, and since the commandexecuted successfully, they are both set to 0. When you execute the second SETstatement (3), the SQLSTATE you get no longer refers to the SQLSTATE of theSELECT statement (1), but to the SQLSTATE of the SET statement (2). This isthe reason why you can only work with one of the variables.

The best way to write portable SQL stored procedures is to perform errorhandling using the DECLARE CONDITION and the DECLARE HANDLERstatements in your SQL stored procedures. This will ensure portability of yourSQL stored procedures among different DB2 platforms.

Nested condition handlers are not supported in the SQL stored procedures body.For more information on declaration of handlers, refer to Chapter 2, “The SQLProcedures language” on page 9.

5.4.3.5 Nested compound statementsSQL Procedures support implemented by DB2 UDB allows you to have nestedcompound statements in your SQL stored procedures body. However, you cannothave ATOMIC compound statements nested. Figure 70 shows an example of anested compound statement in an SQL stored procedure.

Figure 70. Nested compound statement

Another example:

P1: BEGIN

DECLARE SQLCODE INTEGER DEFAULT 0;DECLARE SQLSTATE CHAR(5) DEFAULT ’00000’;DECLARE SQLC INTEGER DEFAULT 0;DECLARE SQLST CHAR(5) DEFAULT ’00000’;....

SELECT ID INTO VID FROM STAFF WHERE ID = 13; (1)SET SQLC = SQLCODE; (2)SET SQLST = SQLSTATE; (3)....

P1: BEGINDECLARE CONTINUE HANDLER FOR NOT FOUNDBEGINSET SQLC=SQLCODE;SET VAR1=1;

END;

SELECT id into vid FROM STAFF where id = vid;

END P1

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 157

Page 174: Store Procedure

DECLARE CONTINUE HANDLER FOR NOT FOUNDIF ( 1 = 1 ) THEN

SET SQLC=SQLCODE;SET VAR1=1;

END IF;SELECT id into vid FROM STAFF where id = vid;END P1

In addition, the code generator supplies the following if SQLCODE andSQLSTATE radio buttons are selected in the wizard:

DECLARE EXIT HANDLER FOR SQLEXCEPTIONIF (1 = 1) THEN

SET SQLSTATE_OUT = SQLSTATE;SET SQLCODE_OUT = SQLCODE;

END IF;

The "IF ( 1 = 1 )" gets around the compound statement limitation.

Since you cannot have ATOMIC nested compound statements, if you want to beable to undo the changes performed only in the nested compound statement, youcan set a SAVEPOINT before the nested compound statement.

5.4.3.6 SavepointsSavepoints are points within an SQL stored procedure, that you can set to be ableto rollback your transaction to that savepoint. A savepoint is set using theSAVEPOINT statement, and may have a name associated to it. (See Figure 71.)

Figure 71. Setting a SAVEPOINT

In your SQL stored procedures, if you detect an error, you can use theROLLBACK TO SAVEPOINT statement to rollback changes performed after thesavepoint was set. A rollback to a savepoint rolls back just the work done afterthe savepoint, the savepoint itself still exists. You can rollback to it again, ifnecessary. A rollback to a savepoint undoes any changes, and also closes allopen cursors.

The first implementation of savepoints in DB2 UDB SQL Procedures does notallow nested savepoints. If you plan to build portable SQL stored procedures, youmust be aware that DB2 for OS/390 V5 and DB2 for AS/400 do not supportsavepoints, but DB2 UDB for OS/390 V6 does.

P1: BEGINUPDATE... ;INSERT... ;...SAVEPOINT S1;BEGINSET VAR1=1;DELETE... ;INSERT ... ;

END;.....END P1

158 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 175: Store Procedure

5.4.3.7 Considerations for comments and blank linesNeither blank lines or comments are tolerated before the actual start of the storedprocedure code, that is not in or before the CREATE PROCEDURE DDLstatement. For example, the comments below are placed as early as they couldpossibly appear in the code.

CREATE PROCEDURE TEAM.Proc1 ( OUT SQLSTATE_OUT char(5),OUT SQLCODE_OUT int )

SPECIFIC TEAM.S1036175RESULT SETS 1LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure TEAM.Proc1------------------------------------------------------------------------P1: BEGIN

DECLARE SQLSTATE CHAR(5) DEFAULT '00000';DECLARE SQLCODE INT DEFAULT 0;

-- Declare cursorDECLARE cursor1 CURSOR WITH RETURN FOR

SELECT * FROM SYSCAT.PROCEDURES;

DECLARE EXIT HANDLER FOR SQLEXCEPTIONIF (1 = 1) THEN

SET SQLSTATE_OUT = SQLSTATE;SET SQLCODE_OUT = SQLCODE;

END IF;

-- Cursor left open for client applicationOPEN cursor1;

SET SQLSTATE_OUT = SQLSTATE;SET SQLCODE_OUT = SQLCODE;

END P1

5.5 Stored procedures preparation

In DB2 UDB, there are many different ways to build your SQL stored proceduresinto your server. You can use the Stored Procedures Builder tool, the DB2Command Line Processor, the DB2 Command Center, or any application programissuing the CREATE PROCEDURE statement. Figure 72 shows different ways tocreate your SQL stored procedures.

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 159

Page 176: Store Procedure

Figure 72. Ways to create SQL stored procedures in DB2 UDB

It is important to notice that, regardless of the method used to start the creation ofthe stored procedure, the process that is used by DB2 UDB internally is alwaysthe same, and the results obtained are equal.

When you submit a CREATE PROCEDURE statement, DB2 UDB performs aseries of steps to build your procedure in the server. These steps are always thesame, and involve the creation of a C source from your SQL stored proceduressource. This C source is precompiled, compiled, and linkedited to generate a DLLfor your SQL stored procedures. So, your SQL stored procedures are notinterpreted during execution, which is important in terms of performance. The laststep in the preparation of your SQL stored procedures is registering theprocedure and parameters in the DB2 catalog tablesSYSIBM.SYSPROCEDURES and SYSIBM.SYSPROCPARMS.

Figure 73 shows the steps involved in the preparation of an SQL storedprocedure.

PressBuild

SQLProcedureDefinitionCompiled

(1) Stored ProcedureBuilder Tool(Window s)

(2) Com mand LineProcessor

(3) Any ClientApplication

(Comm and Center/Script Center)

160 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 177: Store Procedure

Figure 73. Preparation steps for SQL stored procedures in DB2 UDB

Note that as a result of the first step, SQL Parsing and Generation, an SQC file witha C source for your stored procedure is generated. This file also contains, ascomments, your SQL stored procedures source. If you use the IBM DistributeDebugger for debugging your procedure, you will be able to debug using yourSQL stored procedures source contained in the C source file. The #lines

generated perform the mapping between the C statements being executed andthe corresponding SQL Procedures statement. For more information ondebugging your SQL stored procedures, refer to 5.6, “Stored proceduredebugging” on page 166.

The executable files (DLLs in Windows NT) are created in the directory/sqllib/function/routines/udp/schema_name. The specific name of the storedprocedure is used as the name for the executable file. As an example, if you havean SQL stored procedure named PROC1 with an specific name S4231567, anexecutable named S4231567 (S4231567.DLL in NT) will be created for your storedprocedure.

An SQL stored procedure executes as a static application. A package is alsobound as one of the steps of the preparation process. The specific name of theprocedure is used as the package name.

5.5.1 Privileges required to prepare an SQL stored procedureTo issue a CREATE PROCEDURE statement that creates an SQL storedprocedure, the authorization ID executing the statement must have at least one ofthe following privileges:

• SYSADM or DBADM authority

• IMPLICIT_SCHEMA authority on the database, if the implicit or explicitschema name of the procedure does not exist

SQL Parsing&generation

Input

SQLPrecompilation

CREATE PROCEDURESQLPROCLANGUAGE SQLP1: BEGINDECLARE cur1 CURSOR

WITH RETURN FORSELECT*

FROMemployee;OPENcur1;

END P1

C source

Cprecompile

listingwith

messages

PackageCCompile and

Link

DB2 UDBcatalogSYSCAT.PROCEDURES,SYSCAT.PROCPARMS

.o object installed in/function/routines/udp/schema_name/...

.SQCsourcewith SQLand

#linestatements

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 161

Page 178: Store Procedure

• CREATIN privilege on the schema, if the schema name of the procedurerefers to an existing schema

If the authorization ID has insufficient authority to perform the operation, anSQLSTATE 42502 is raised.

5.5.2 Preparing an SQL stored procedure from the DB2 CLPTo create an SQL stored procedure from the DB2 CLP, you must create thesource of your stored procedure in a file.

The CREATE PROCEDURE statement must be interpreted by the DB2 CLP as asingle SQL statement. However, DB2 CLP uses the semicolon (;) as the defaultdelimiter for statements. When your stored procedures have compoundstatements, the statements within the compound statement are also terminatedwith semicolons, causing the DB2 CLP to interpret that as the end of the CREATEPROCEDURE statement, and a syntax error is raised.

To avoid this, you must use an alternative terminating character in your file, andchange the DB2 CLP invocation command to identify this new character as theterminating character. The samples SQL stored procedures shipped with DB2SDK use the $ symbol as a terminating character.

Figure 74 shows a sample file, STP.DB2, containing a simple SQL storedprocedure using the $ symbol as terminating character.

Figure 74. STP.DB2 file containing SQL stored procedures using $ as a delimiter

To execute the above file, you must invoke the DB2 CLP with the -td parameterto specify the $ as the terminating character, as follows:

db2 -td$ -fSTP.DB2

5.5.3 Preparing an SQL stored procedure from the DB2 toolsIf you plan to use DB2 tools such as the Command Center or the Script Center tosubmit your CREATE PROCEDURE statements, you must also change the

STP.DB2

CONNECT TO SAMPRES1$

CREATE PROCEDURE DRDARES1.PROC1 ( )SPECIFIC DRDARES1.S3710781RESULT SETS 1LANGUAGE SQL

P1: BEGIN-- Declare cursorDECLARE cursor1 CURSOR WITH RETURN FOR

SELECT * FROM STAFF;

-- Cursor left open for client applicationOPEN cursor1;

END P1 $

CONNECT RESET$

162 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 179: Store Procedure

termination character for SQL statements, since the default for DB2 tools is alsothe semicolon (;) character.

To change the termination character for the DB2 Command Center, click onScript->Options... then check the Use statement termination charactercheckbox, and specify the character you want to use, for example, the $.

Figure 75 shows the Options window of DB2 Command Center.

Figure 75. Changing the terminating character for the DB2 Command Center

To change the termination character for scripts submitted using the DB2 ScriptCenter, click on Tools->Tools Settings then check the Use statementtermination character checkbox, and specify the character you want to use, forexample, the $.

Figure 76 shows the Tools Settings window for DB2 tools.

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 163

Page 180: Store Procedure

Figure 76. Changing the termination character for DB2 tools

5.5.4 Preparing an SQL stored procedure from application programsThe CREATE PROCEDURE statement may be invoked from an applicationprogram written in CLI, ODBC, JDBC, or embedded SQL. It can be invoked in theapplication as a dynamic or a static SQL statement. However, if the bind optionDYNAMICRULES BIND applies, the statement cannot be dynamically prepared.

5.5.5 Preparing an SQL stored procedure from the SPBIf you create or change an SQL stored procedure with SPB, to prepare the storedprocedure, all you have to do is right-click on the procedure name and then clickon the Build option; or you can select the stored procedure and click on the Buildicon. For more information about SPB, please refer to Chapter 3, “The DB2Stored Procedure Builder” on page 57.

164 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 181: Store Procedure

Figure 77. Using SPB to prepare SQL stored procedures

5.5.6 Copying SQL stored procedures between DB2 UDB serversWhen the support for SQL Procedures become available for DB2 UDB, it ispossible that a utility to generate the source CREATE PROCEDURE statementsfor the SQL stored procedures will be included. However, since the source isavailable in the DB2 UDB catalog, it is very simple to generate a sequential filewith the CREATE PROCEDURE statements and then submit this file to anotherDB2 UDB server to replicate the stored procedures.

To generate a sequential file, after connecting to the DB2 server, issue thefollowing command, from the DB2 Command Window:

db2 SELECT TEXT CONCAT ’$’ FROM SYSIBM.SYSPROCEDURES WHERE LANGUAGE = ’SQL’> sqlp.ddl

The above command generates a file sqlp.ddl, that contains the CREATEPROCEDURE statements for all the SQL stored procedures in your database.You can include more conditions in the WHERE clause if you want to filter theprocedures you want to copy. You can edit the file generated to remove the initialand final lines, and do any kind of changes you want, such as bulk changes to theschema name of the procedures, or table names.

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 165

Page 182: Store Procedure

After changing the file, you may submit it to another DB2 UDB server, byconnecting to the server, and then issuing the following command:

db2 -td$ -fsqlp.ddl

The above command creates all the SQL stored procedures in the sqlp.ddl file atthe remote DB2 UDB server.

5.6 Stored procedure debugging

The support for SQL Procedures implemented in DB2 UDB allows you toremotely debug stored procedures executing on the DB2 UDB server. The remotedebug is already available for Java stored procedures. However, at the time ofwriting this redbook, remote debugging for SQL stored procedures (and C/C++)was still being developed, so we could not test this support.

In this section, we describe the steps required to remotely debug SQL storedprocedures executing on a DB2 UDB server, based on the steps required fordebugging Java stored procedures. Note that since we did not have the finalversion of the product, these steps may be different when the support for SQLProcedures is available.

5.6.1 Platforms supported for remote debuggingAlthough the support for SQL Procedures is implemented in all DB2 UDB serverplatforms, remote debugging of SQL stored procedures is only available for DB2UDB servers executing on Windows NT, OS/2, AIX, and Sun platforms.

The IBM Distributed Debugger client must also be executing in a Windows NTsystem connected to the DB2 UDB server. The IBM Distributed Debugger client isincluded with DB2 UDB.

5.6.2 The DB2DBG.ROUTINE_DEBUG debugger tableDB2 UDB holds information about the stored procedures you want to debug in atable named DB2DBG.ROUTINE_DEBUG. You must create this table in every DB2 UDBserver database that you plan to debug stored procedures.

The file db2debug.ddl contains all the DDL to create the DB2DBG.ROUTING_DEBUG

table. This file is located in the \SQLLIB\MISC directory. To create the table, youmust connect to the DB2 UDB server database and issue the following command:

db2 -tf x:\sqllib\misc\db2debug.ddl

The current version of the db2debug.ddl file creates the DB2DBG.ROUTINE_DEBUG

table, a view named DB2DBG.ROUTINE_DEBUG_USER, and two triggers on the basetable. The DB2DBG.ROUTINE_DEBUG_USER view, limits the access to the table only torows belonging to the user connected to the database. The definition for thetriggers is going to change, since the current triggers are used to ensure that thestored procedure being inserted in the table is a Java stored procedure.

The DB2DBG.ROUTINE_DEBUG table must be populated using INSERT, UPDATE, andDELETE SQL statements, or using the SPB Debug Properties dialog. Everystored procedure you want to debug must contain a row in theDB2DBG.ROUTINE_DEBUG table. Following is an example of an INSERT statement toinclude an entry in the debug table:

166 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 183: Store Procedure

DB2 INSERT INTO db2dbg.routine_debug (AUTHID, TYPE, ROUTINE_SCHEMA,SPECIFICNAME, DEBUG_ON, CLIENT_IPADDR, CLIENT_PORT) VALUES ('DRDARES1', 'S','DRDARES1', 'S2351892', 'Y', '9.179.186.15',8000)

You must provide values for the columns of the table as follows:

• AUTHID: This contains the authorization id that is associated with thedebugging of the stored procedure. DB2 UDB will search the debug tableusing the authorization id passed in the connect statement.

• TYPE: In the current version, the only value supported for this column is ’S’ forstored procedures. In future versions, when the debugging facilities becomeavailable for other DB2 objects, such as functions, other values will be valid.

• ROUTINE_SCHEMA: This is the schema associated with the storedprocedure that you want to debug.

• SPECIFICNAME: This is the specific name of the stored procedure. If you donot know the specific name of the stored procedure you want to debug, youcan check the SYSIBM.SYSPROCEDURES table to get the specific name.

• DEBUG_ON: This column can contain a ’Y’ to turn debugging for the storedprocedure on, or a ’N’ to turn off the debugging.

• CLIENT_IPADDR: contains the IP address of the client workstation runningthe IBM Distributed Debugger client. When the stored procedure starts on theDB2 server, the debugger client will be started in the machine specified here.Note that this machine must be executing the IBM Distributed Debugger clientdaemon for receiving the debugger requests.

• CLIENT_PORT: This contains the port number for the IBM DistributedDebugger client. This port number is specified when starting the debuggerclient in the client workstation.

There are two additional columns, DEBUG_STARTN and DEBUG_STOPN, thatare not used in the current version.

5.6.3 DB2 environment variables for debuggingDB2 UDB has two environment variables that are used for the debugging ofstored procedures.

The DB2ROUTINE_DEBUG variable enables debugging for stored procedures inyour DB2 UDB server instance. To debug your stored procedures, you must setthis variable to ON, as follows:

db2set DB2ROUTINE_DEBUG=ON

To turn off debugging for your DB2 instance, reset the value of theDB2ROUTINE_DEBUG variable, as follows:

db2set DB2ROUTINE_DEBUG=

The DER_DBG_PATH environment variable is used if the source code for thestored procedure resides on the client. This variable should be set at the clientmachine, and must provide the path where the source code resides on the client.In case of SQL stored procedures where the code resides in the DB2 tables, thisvariable is not used.

SQL Procedures for DB2 UDB for UNIX, Windows, OS/2 167

Page 184: Store Procedure

5.6.4 Starting the debugger clientAfter you perform the previous steps in the DB2 UDB server, you are ready todebug your stored procedure. You must ensure that the IBM DistributedDebugger client is installed and started in the client workstation specified in thedebugger table. To start the IBM Distributed Debugger client, you can use thefollowing command:

idebug.exe -qdaemon -quiport=8000

You can invoke the stored procedure from any client workstation, using a clientprogram, SPB, or the PCALL generic client program provided with DB2. Whenthe stored procedure starts at the DB2 server, the debugging process begins inthe client workstation.

For more information about the IBM Distributed Debugger client, refer to 3.4.6,“Debugging stored procedures” on page 105.

5.6.5 Debugging stored procedures through SPBFollowing is what needs to be done for debugging your stored procedure throughthe SPB, which provides an easy way to debug it:

• On the server side:

1. Set the following: db2set DB2ROUTINE_DEBUG=on

• On the client side:

1. Start the debugger daemon: idebug.exe -qdaemon -quiport=8000

2. Start SPB, write your stored procedure, select the stored procedure,right-click -> "Debug Properties" -> "Add" (the values for the IP address aretaken from the SPB machine) -> "OK"

3. Run the stored procedure through the SPB.

The SPB will take care of creating the debugger table andinserting/deleting/updating the entries.

168 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 185: Store Procedure

Chapter 6. SQL Procedures for DB2 UDB for AS/400

This chapter describes the SQL Procedures language support available for DB2UDB for AS/400. The SQL Procedures language was introduced in V4R2.

6.1 General Considerations

An SQL stored procedure is created with the CREATE PROCEDURE statementthat includes a procedure body written in SQL or more precisely in SQLProcedures language. For SQL naming convention, the procedure will be createdin the collection or library specified by the implicit or explicit qualifier. For systemnaming, the procedure will be created in the collection or library specified by thequalifier. If no qualifier is specified, the procedure will be created in the currentlibrary (*CURLIB).

Stored procedures are automatically registered in the system catalog, when theprocedure is created or restored onto another system. Client applications (ODBC,JDBC, ADO based) cannot invoke stored procedures unless they are registeredin the database catalogs.

The DB2 UDB for AS/400 does not provide an SQL stored procedure statementdebugger, so the ILE C program debugger must be used for any debug that isneeded on the stored procedure program.

6.2 System requirements and planning

Before you start to develop the SQL stored procedures on the AS/400 system,make sure that you are running on V4R2 or a higher release of the OS/400 withthe latest CUMPTF loaded.

When you execute the CREATE PROCEDURE statement for the SQL storedprocedure, DB2 UDB for AS/400 walks through a multiphase process to create anILE C program object (*PGM). During this process DB2 UDB for AS/400generates an intermediary ILE C code with embedded SQL statements. This ILEC code is then precompiled, compiled, and linked automatically. This means thatthe SQL Development Kit for AS/400, and the ILE C compiler, need to be installedon the system where you plan to develop SQL stored procedures. Once the ILE Cobject is created, it can be restored onto any V4R2 or higher system and runwithout the SQL Development Kit and ILE C compiler.

Please note that, for performance reasons, the ILE C program object is createdwith Activation Group parameter set to *CALLER.

6.3 System Catalog Tables

The database catalog tables contain information about tables, parameters,procedures, packages, views, indexes, and constraints on the AS/400 system.

The database manager provides views over the catalog tables. The views providemore consistency with the catalog views of other IBM SQL products and with thecatalog views of the ANSI and ISO standard. Tables and views in the catalog arethe same as any other database tables and views. If you have the authorization,

© Copyright IBM Corp. 1999 169

Page 186: Store Procedure

you can use SQL statements to look at data in the catalog views in the same waythat you retrieve data from any other table in the AS/400 system. The databasemanager ensures that the catalog contains accurate descriptions of the objects inthe database at all times.

When you create an SQL stored procedure or an external procedure, there aretwo catalog tables in QSYS2 that are updated: SYSROUTINES and SYSPROCS.

The SYSPROCS table contains one row for each procedure created by theCREATE PROCEDURE statement. Some of the fields are:

• Name of the collection or library where the procedure is created• Name of the procedure• Type of routine body (External or SQL)• Language of the procedure (SQL, C, CL, RPG...)• Number of input parameters• Number of output parameters• Number of input-output parameters• The source code of an SQL stored procedure

Note: If the source of the SQL stored procedure is more than 18K, the source code isnot stored in SYSPROCS.

The SYSPARMS table contains one row for each parameter of a procedurecreated by the CREATE PROCEDURE statement. Some of the fields of this tableare:

• Name of the collection or library where its created• Name of the procedure• Type of parameter (IN, OUT, INOUT)• Name of the parameter• Data type of the parameter• Data scale of the parameter• Data precision of the parameter

6.4 Creating an SQL stored procedure

In this section, we document the steps required to edit and compile an SQLstored procedure (SP). On the AS/400 system there are many different ways tobuilt your SQL stored procedure. You can use following methods:

• Traditional 5250 programming using Source Entry Utility (SEU) andRUNSQLSTM utilities. This gives the best control over the compilerparameters and allows you to debug the ILE C program object.

• Operations Navigator GUI

• Operations Navigator SQL script utility

6.4.1 Creating an SQL SP with traditional toolsThe steps required to create your SQL stored procedures with traditional 5250tools are outlined in the following list:

• Create a library if you do not have one already.

• Create a source physical file; this is the file where all the SQL sourcemembers are going to be stored.

170 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 187: Store Procedure

• Start a Source Entry Utility (SEU) editing session.

• Enter the SQL stored procedure source code.

• Create the SQL stored procedure using the RUNSQLSTM command to issuea CREATE PROCEDURE command. This creates a C program object thatruns when the procedure is called. If there are problems generating theprocedure, there is a listing that shows the syntax errors of the source.

• Invoke the stored procedure through the SQL CALL statement passing theparameter list.

• Check for the completion status of the SQL stored procedure.

Let’ s see how to implement this scenario. First, create a library, a source file, andstart an editing session.

1. To create a library called SQLPROCS, type the following CL command at the5250 emulation prompt:

CRTLIB LIB(SQLPROCS)

2. To create a source physical file called QSQLSRC, type the followingcommand:

CRTSRCPF FILE(SQLPROCS/QSQLSRC) RCDLEN(112) TEXT(’ Source physical file forSQL Procedures’ )

The CRTSRCPF command creates a source physical file QSQLSRC inSQLPROCS library.

3. To start an editing session and create a source member, named SDK2LMS,type the following command:

STRSEU SRCFILE(ORDAPPLIB/QSQLSRC) SRCMBR(SDK2LMS) TYPE(TXT) OPTION(2)

Entering OPTION(2) indicates that you want to start a session for a newmember. The STRSEU command creates a new member, SDK2LMS, in theQSQLSRC file in the SQLPROCS library and starts an edit session.

4. Use SEU to enter the procedure’s source code as shown in Figure 78.

SQL Procedures for DB2 UDB for AS/400 171

Page 188: Store Procedure

Figure 78. Entering source code

Note: 1 We intentionally omitted a comma, which should separate the parametersto produce an error listing in the next step.

5. Run the RUNSQLSTM command to create the procedure. We recommendusing the Debugging view option *LIST and Listing output *PRINT. It is usefulfor debugging and testing purposes. Refer to section 6.6.2, “Preparing theSQL stored procedure for debugging” on page 182 for more details.

Figure 79. Creating the SQL stored procedure

6. If there are syntax errors in your source code, the SQL9010 ’RUNSQLSTMcommand failed’ message appears on your screen. To check for possibleerrors, you need to look at the spool file created by the precompiler. Typefollowing CL command at the command prompt:

CREATE PROCEDURE SDK2LMS( IN empnum CHAR(6) 1INOUT rating SMALLINT )

LANGUAGE SQL- The procedure’s body begins hereBEGIN

DECLARE not_found CONDITION FOR '02000';DECLARE EXIT HANDLER FOR not_foundSET rating = -1;

IF rating = 1THEN UPDATE employeeSET salary = salary * 1.10, bonus = 1000WHERE empno = empnum;

ELSEIF rating = 2THEN UPDATE employeeSET salary = salary * 1.05, bonus = 500WHERE empno = empnum;

ELSE UPDATE employeeSET salary = salary * 1.03, bonus = 0WHERE empno = empnum;

END IF;END;

Run SQL Statements (RUNSQLSTM)

Type choices, press Enter.

Source file . . . . . . . . . . > QSQLSRC NameLibrary . . . . . . . . . . . > SQLPROCS Name, *LIBL, *CURLIB

Source member . . . . . . . . . > SDK2LMS NameCommitment control . . . . . . . > *NONE *CHG, *ALL, *CS, *NONE...Naming . . . . . . . . . . . . . *SYS *SYS, *SQL

Additional Parameters

Debugging view . . . . . . . . . > *LIST *STMT, *LIST, *NONEListing output . . . . . . . . . > *PRINT *NONE, *PRINT

BottomF3=Exit F4=Prompt F5=Refresh F10=Additional parameters F12=CancelF13=How to use this display F24=More keys

172 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 189: Store Procedure

WRKSPLF

The list of your spool files appears. Find the spool file named SDK2LMS andUser Data value SQL. To display the spool file contents, use option 5 asshown in Figure 80.

Figure 80. Working with spool files

7. The SQL stored procedure listing appears. Scroll down and find the SQLmessages section as shown in Figure 81.

Work with All Spooled Files

Type options, press Enter.1=Send 2=Change 3=Hold 4=Delete 5=Display 6=Release 7=Messages8=Attributes 9=Work with printing status

Device or Total CurOpt File User Queue User Data Sts Pages Page Copy5 SDK2LMS JAREK QPRINT SQL RDY 3 1

BottomParameters for options 1, 2, 3 or command===>F3=Exit F10=View 4 F11=View 2 F12=Cancel F22=Printers F24=More keys

SQL Procedures for DB2 UDB for AS/400 173

Page 190: Store Procedure

Figure 81. Displaying SQL precompiler error messages

8. In the preceding listing, there is a syntax error that probably generated theother ones. Correct the syntax error using the SEU utility and execute theRUNSQLSTM command again. This time the command should completesuccessfully.

After the procedure has been successfully created, two system catalog tables areupdated: SYSROUTINES and SYSPARMS. The SYSROUTINES view containsone row for each procedure or User Defined Function. The SYSPARMS tablecontains one row for each parameter of a procedure or UDF. If you intend to workonly with stored procedures, you can also use a catalog view called SYSPROCS,which presents information pertaining to the stored procedures. The systemcatalog includes also a view called SYSFUNCS, which shows the information forthe UDFs.

Once the procedure has been created, it can be invoked with the SQL callstatement using any interface that supports SQL (embedded SQL, ODBC, JDBC,SQLJ, CLI, and so on).

6.4.2 Creating an SQL SP with Operations Navigator GUIThe Operations Navigator provides an attractive graphical interface that allowsyou to perform typical database administration tasks. It allows easy access to allserver administration tools, gives a clear overview of the entire database system,

Display Spooled FileFile . . . . . : SDK2LMSPage/Line 2/17Control . . . . .Columns 1 - 130Find . . . . . .

*...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8....+....0....+....1....+....2....+....3

13 WHERE empno = empnum;14 ELSEIF rating = 215 THEN UPDATE employee16 SET salary = salary * 1.05, bonus = 50017 WHERE empno = empnum;18 ELSE UPDATE employee19 SET salary = salary * 1.03, bonus = 020 WHERE empno = empnum;21 END IF;22 END;

* * * * * E N D O F S O U R C E * * * * *RCHASM20 - V04R04M00 - 471125

5769ST1 V4R4M0 990521 Run SQL Statements SDK2LMS09/14/99 13:52:46 PageRecord *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..SEQNBR Last changeMSG ID SEV RECORD TEXTSQL0199 30 3 Position11KeywordINOUTnotexpected.Validtokens:),

.SQL0104 30 8 Position20TokenHANDLERwasnotvalid.Validtokens:

SCROLL.

More...

174 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 191: Store Procedure

enables remote database management, and provides assistance for complextasks.

In this section, you will learn how to efficiently use the GUI administration toolsoffered by Client Access Express to work with SQL stored procedures on theAS/400 system. We assume that you already know how to set up the OperationsNavigator connection to your AS/400.

The steps below show you how to create an SQL stored procedure using theCreate New SQL Procedure dialog:

1. Double click the Operations Navigator icon on your desktop. In the mainpanel right-click on the library, which contains your database. In our case thename of the library is SAMPLE. Select New ->Procedure-> SQL. The NewSQL Procedure dialog appears.

2. Enter the following for the stored procedure name: SDK2LMS.

3. For the description, type the following: Increase salary depending on rating.

4. Click on the Parameters tab.

5. Click the Insert button. For the first parameter name, type the following:empnum. From the type drop down list, select CHARACTER. In the parameterlength box, enter the number ’6’. Change the parameter style to IN/OUT.

6. Insert the second parameter as shown in Figure 82.

Figure 82. Parameters definition for SQL stored procedure

SQL Procedures for DB2 UDB for AS/400 175

Page 192: Store Procedure

7. Click on SQL Statements tab. Type the procedure body as shown in Figure 83.

Figure 83. Entering SQL statements

8. Click the OK button. The stored procedure is now created.

6.4.3 Creating an SQL SP with the Run SQL Scripts utilityThe Run SQL Script utility is yet another interface that you can use on the AS/400system to create a stored procedure. The script utility is available through theOperations Navigator GUI. It allows you to you create, edit, run, and troubleshootscripts of SQL statements. You can also save the scripts with which you work onyour PC.

The steps below show you how to create an SQL stored procedure using the SQLScript utility.

1. Double click the Operations Navigator icon on your desktop. In the mainpanel right-click the Database object and select Run SQL Script. The RunSQL Scripts windows appears.

2. Type the procedure body as shown in Figure 84.

176 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 193: Store Procedure

Figure 84. Creating SQL SP with script utility

3. To run the CREATE PROCEDURE statement, select Run->All from the Runpull down menu. If the syntax of your SQL statement is correct, the SQLstored procedure is created in the SAMPLE library on your AS/400 system.Check for the completion status in the run history panel of the Run SQL Scriptwindow. The last message displayed in this panel should read:

Statement ran successfully

If the run history panel does not supply sufficient information about the executionof the SQL statements, you can view the AS/400 job log to get additional, morespecific information. From the View drop down menu, select Job Log. A job logwindow appears as shown in Figure 85.

SQL Procedures for DB2 UDB for AS/400 177

Page 194: Store Procedure

Figure 85. Job log window

Note: You may not have the same messages in the job log.

To view a second level message in the job log, double click on the item you wishto view. A dialog window appears with all of the information for that message.

To save the script that contains the source code for the SDK2LMS storedprocedure, select File->Save As from the script utility menu bar. The Save Asdialog is displayed. In the Save in list combo, open the directory you wish to useas your SQL script repository. In our case we used:\sg24_5485\work_in_progress directory. Enter sdk2lms in the file name inputfield.

178 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 195: Store Procedure

Figure 86. Saving SQL Script File

Click Save to return to the Run SQL Script dialog.

The Run SQL Script utility proved to be very useful when we ported the SQLstored procedures from other DB2 UDB platforms to the AS/400. All we had to dowas to copy the scripts to our working directory,and change the file extensionfrom .stp to .sql. Then we could double click a stored procedure file from theWindows Explorer window to load the script into the Run SQL Script utility.

6.4.4 Verifying the stored procedure propertiesOnce the stored procedure has been successfully created, you can verify itsproperties by using the Operations Navigator interface:

1. In the main Operations Navigator window double click the SAMPLE libraryicon. The right-hand panel displays now all DB2 UDB for AS/400 objects inthis library.

2. Find the SDK2LMS stored procedure icon and right-click it. The context menufor this object appears. Select Properties. The SDK2LMS Properties windowshows up. It has three tabs:

• The General page specifies the name by which the procedure is known toSQL programs and the number of result sets it should return. If you want tocall an external program as a procedure, you need to define the program asa procedure before you can call it from an SQL program.

• The Parameters page specifies the parameters that the procedure uses.

• The SQL Statements page contains the code for the external SQLprogram that you are defining as a procedure. You can use the SQLstatement examples and fill in the necessary information to make codingSQL easier. After an SQL stored procedure has been created, the SQLstatements cannot be changed.

The Parameters page for the SDK2LMS stored procedure is shown in Figure 87.

SQL Procedures for DB2 UDB for AS/400 179

Page 196: Store Procedure

Figure 87. Displaying the stored procedure properties

6.5 Deleting or replacing the SQL stored procedure

When you create a procedure, its library and name must be unique to register theSQL stored procedure in the catalogs. However, the CREATE PROCEDUREstatement does not have a replace option. For this reason, if you want tore-create or delete an existing procedure, use the DROP PROCEDUREstatement. If you try to create a stored procedure that already exists in a givenlibrary, you will receive an error return code SQL0454.

For example, when we tried to re-run the CREATE PROCEDURE statement forthe SDK2LMS stored procedure the following error message was displayed in therun history panel of the SQL Script utility:

SQL0454 - ’Function SDK2LMS in SAMPLE with the same signature alreadyexists’.

There are several ways to drop a stored procedure from the AS/400 system:

• In the traditional "green screen" environment, start the interactive SQL sessionwith the STRSQL command, and at the ISQL prompt, type the following SQLstatement:

DROP PROCEDURE library/procedure-name

• In the Operations Navigator environment, in the right panel of the mainOperations Navigator window, right-click the procedure you want to drop andselect the Delete option. A window appears with the stored procedure objectselected for deletion. Confirm that this is the procedure you want to delete,and click the Delete button, as shown in Figure 88.

180 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 197: Store Procedure

Figure 88. Deleting a stored procedure

• In the Run SQL Script utility, insert the DROP PROCEDURE procedure-name

statement in the workable area and then select Run->All from the menu bar.

The system catalog tables, SYSROUTINES and SYSPARMS, are updated whena DROP PROCEDURE statement is executed. In the SYSROUTINES table, arow is deleted corresponding to the information of the deleted procedure. InSYSPARMS table, the number of rows deleted depends on the number ofparameters defined in the procedure.

6.6 Debugging SQL stored procedures

In this section we show how to debug an SQL stored procedure on the AS/400system. DB2 UDB for AS/400 does not provide a native SQL debugger, so theprocesses of eliminating run-time errors requires a certain level of programmingskills in the AS/400 Integrated Language Environment (ILE). As discussed in 6.2,“System requirements and planning” on page 169, when you create an SQLstored procedure, under the covers, the system is creating an ILE C programobject, which implements the procedure. The ILE C programs, in turn can bedebugged with the ILE Source Debugger. We start this section with a briefdescription of the basic ILE Source Debugger functions.

6.6.1 The ILE Source DebuggerThe ILE source debugger is used to detect errors in and eliminate errors fromprogram objects and service programs. By using debug commands with any ILEprogram, you can:

• View the program source or change the debug view• Set and remove conditional and unconditional breakpoints• Step through a specified number of statements• Display or change the value of fields, structures, and arrays• Equate a shorthand name with a field, expression, or debug command

Many debug commands are available for use with the ILE source debugger.These debug commands and their parameters are entered on the debugcommand line displayed in the bottom of the Display Module Source display andthe Evaluate Expression display. These commands can be entered in uppercase,lowercase, or mixed case.

SQL Procedures for DB2 UDB for AS/400 181

Page 198: Store Procedure

Note: The debug commands on the debug command line are not CL commands.

The most important debug commands are briefly described in the following list:

Command Description

ATTR Permits you to display the attributes of a variable. The attributesare the size and type of the variable.

BREAK Permits you to enter either an unconditional or conditionalbreakpoint at a position in the program being tested. Use BREAKline-number WHEN expression to enter a conditional breakpoint.

CLEAR Permits you to remove conditional and unconditional breakpoints.

DISPLAY Allows you to display the names and definitions assigned by usingthe EQUATE command.

EQUATE Allows you to assign an expression, variable, or debug commandto a name for shorthand use.

EVAL Allows you to display or change the value of a variable or todisplay the value of expressions, records, structures, or arrays.

QUAL Allows you to define the scope of variables that appear insubsequent EVAL commands.

STEP Allows you to run one or more statements of the procedure beingdebugged.

FIND Searches forwards or backwards in the module currentlydisplayed for a specified line number or string or text.

UP Moves the displayed window of source towards the beginning ofthe view number of lines entered.

DOWN Moves the displayed window of source towards the end of theview number of lines entered.

LEFT Moves the displayed window of source to the left.

RIGHT Moves the displayed window of source to the right by the numberof characters entered.

TOP Positions the view to show the first line.

BOTTOM Positions the view to show the last line.

NEXT Positions the view to the next breakpoint in the source currentlydisplayed.

PREVIOUS Positions the view to the previous breakpoint in the sourcedisplayed.

HELP Shows the online help information for the available sourcedebugger commands.

6.6.2 Preparing the SQL stored procedure for debuggingA program or module must have debug data available if you are to debug it. Sincedebug data is created during compilation, you need to specify the DBGVIEWparameter on the RUNSQLSTM command. The DBVIEW parameter specifies thetype of source debug information to be provided by the SQL precompiler. Thedefault value for this parameter is *NONE, so no debugging information isincluded in the program object.

182 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 199: Store Procedure

To create the SQL stored procedure with the debug data follow the steps outlinedbelow:

1. At the CL command prompt type RUNSQLSTM and press F4 for prompting.Provide the source file name, library, and source member as shown in Figure89 for our SDK2LMS example.

Figure 89. RUNSQLSTM command

2. Press the Page Down key to scroll to the DBGVIEW parameter. Set theparameter value to *LIST as shown in Figure 90. We also recommend that youset the OUTPUT parameter to *PRINT. The OUTPUT parameter specifieswhether the precompiler listing is generated.

Note: In our example we use the system naming convention, which gives muchmore naming flexibility on the AS/400 system than the SQL naming convention. Inthe SDK2LMS SQL source, we did not qualify the procedure name with a libraryname, so it is going to be created in the current library. If you want the storedprocedure to be created in the SAMPLE library, make sure it is your currentlibrary at the time you run the RUNSQLSTM command. You can use the DisplayLibrary List (DSPLIBL) command to display your library list, and the ChangeCurrent Library (CHGCURLIB) command to change the current library for yourAS/400 job.

Run SQL Statements (RUNSQLSTM)

Type choices, press Enter.

Source file . . . . . . . . . . > QSQLSRC NameLibrary . . . . . . . . . . . > SQLPROCS Name, *LIBL, *CURLIB

Source member . . . . . . . . . > SDK2LMS NameCommitment control . . . . . . . *CHG *CHG, *ALL, *CS, *NONE...Naming . . . . . . . . . . . . . *SYS *SYS, *SQL

Additional Parameters

Severity level . . . . . . . . . 10 0-40Date format . . . . . . . . . . *JOB *JOB, *USA, *ISO, *EUR...Date separator character . . . . *JOB *JOB, /, ., ,, -, ' ', *BLANKTime format . . . . . . . . . . *HMS *HMS, *USA, *ISO, *EUR, *JISTime separator character . . . . *JOB *JOB, :, ., ,, ' ', *BLANKDefault collection . . . . . . . *NONE Name, *NONEIBM SQL flagging . . . . . . . . *NOFLAG *NOFLAG, *FLAGANS flagging . . . . . . . . . . *NONE *NONE, *ANS

More...F3=Exit F4=Prompt F5=Refresh F12=Cancel F13=How to use this displayF24=More keys

SQL Procedures for DB2 UDB for AS/400 183

Page 200: Store Procedure

Figure 90. Specifying the DBGVIEW and OUTPUT parameters

The possible values for the Debugging view parameter are:

*STMT Allows the compiled module object to be debugged using programstatement numbers and symbolic identifiers.

*NONE The debug view is not be generated.*LIST Generates the listing view for debugging the compiled module

object.

The possible values for the Listing output parameter are:

*PRINT The precompiler listing is generated.*NONE The precompiler listing is not generated.

You must specify *STMT or *LIST if you want debugging data to be saved in theprogram. After the RUNSQLSTM command has successfully created theprocedure, we are ready to test it.

6.6.3 Testing the SQL stored procedure in traditional environmentAs you have probably realized by now, the SQL control statements do not includethe PRINT or DISPLAY statements. Therefore, the easiest way to test theexecution of the procedure is to use ILE C source code debugging.

While debugging and testing your program, ensure that your library list ischanged to direct the programs to a test library containing the test data so thatany existing real data is not affected.

To start a debugging session, type the SRTDBG command at the CL prompt andpress F4 for prompting. Provide the program name and the library. Make sure thatyou change the Update production files parameter to *YES. Even if you work withthe test data the library attribute is set to PROD, and your procedure will failmiserably the first time you try to access the data. An example of the STRDBGcommand is shown in Figure 91.

Run SQL Statements (RUNSQLSTM)

Type choices, press Enter.

Decimal Point . . . . . . . . . *JOB *JOB, *SYSVAL, *PERIOD...Sort sequence . . . . . . . . . *JOB Name, *HEX, *JOB...Library . . . . . . . . . . . Name, *LIBL, *CURLIB

Language id . . . . . . . . . . *JOB *JOB, *JOBRUN...Print file . . . . . . . . . . . QSYSPRT NameLibrary . . . . . . . . . . . *LIBL Name, *LIBL, *CURLIB

Statement processing . . . . . . *RUN *RUN, *SYNAllow copy of data . . . . . . . *OPTIMIZE *OPTIMIZE, *YES, *NOClose SQL cursor . . . . . . . . *ENDACTGRP *ENDMOD, *ENDACTGRPAllow blocking . . . . . . . . . *ALLREAD *ALLREAD, *NONE, *READDelay PREPARE . . . . . . . . . *NO *YES, *NODebugging view . . . . . . . . . > *LIST *STMT, *LIST, *NONEUser profile . . . . . . . . . . *NAMING *NAMING, *USER, *OWNERDynamic user profile . . . . . . *USER *USER, *OWNERListing output . . . . . . . . . > *PRINT *NONE, *PRINTTarget release . . . . . . . . . *CURRENT *CURRENT, VxRxMx

BottomF3=Exit F4=Prompt F5=Refresh F12=Cancel F13=How to use this displayF24=More keys

184 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 201: Store Procedure

Figure 91. Starting a debug session

Note: When your session is in debug mode, the job log of the session saves a lotof information related to the SQL statements being executed. The applicationdeveloper can use this information for problem detection and performance tuning.

Once you have filled all the required parameters, press Enter to initialize thedebug session. The ILE Source Debugger loads the ILE C source created for yourSQL stored procedure. At the debug prompt, type the following command: find

main and hit ENTER. This positions you at the main function as shown in Figure92. Now you can set a breakpoint. It always a good idea to check, at thebeginning of a stored procedure execution, whether the parameters were passedcorrectly, so set the breakpoint at line 110. You are all set now — just press F12to return to the command line prompt.

Start Debug (STRDBG)

Type choices, press Enter.

Program . . . . . . . . . . . . > SDK2LMS Name, *NONELibrary . . . . . . . . . . . > SAMPLE Name, *LIBL, *CURLIB

+ for more values*LIBL

Default program . . . . . . . . *PGM Name, *PGM, *NONEMaximum trace statements . . . . 200 NumberTrace full . . . . . . . . . . . *STOPTRC *STOPTRC, *WRAPUpdate production files . . . . > *YES *NO, *YESOPM source level debug . . . . . *NO *NO, *YESService program . . . . . . . . *NONE Name, *NONELibrary . . . . . . . . . . . Name, *LIBL, *CURLIB

+ for more values

More...F3=Exit F4=Prompt F5=Refresh F10=Additional parameters F12=CancelF13=How to use this display F24=More keys

SQL Procedures for DB2 UDB for AS/400 185

Page 202: Store Procedure

Figure 92. Debug session

The next step in the stored procedure testing is to actually invoke the procedure.As mentioned earlier, you cannot invoke the stored procedure from the commandprompt; you need to use the SQL call.

To test the SDK2LMS stored procedure, we coded a small embedded SQL ILE Cprogram that calls the procedure and displays the results. The source code forthe INVSDK2LMS is shown in Figure 93. You can compile this program with thefollowing CL command:

CRTSQLCI OBJ(SQLPROCS/INVSDK2LMS) SRCFILE(SQLPROCS/QCSRC)OBJTYPE(*PGM) OUTPUT(*PRINT) DBGVIEW(*SOURCE)

Display Module Source

Program: SDK2LMS Library: SAMPLE Module: SDK2LMS101 void main(int argc, char* argv[]) {102 1 SQLP_IND = (short int*) argv[3];103 2 sqlcap = (SQLCA*) argv[4];104 3 SQLInitSQLCA((SQLCA*)&sqlca);105 4 SDK2LMS.SQLP_I1 = *(SQLP_IND+0);106 5 if (SDK2LMS.SQLP_I1 != SQLP_NULLIND)107 6 strcpy(SDK2LMS.EMPNUM, argv[1]);108 7 SDK2LMS.SQLP_I2 = *(SQLP_IND+1);109 8 if (SDK2LMS.SQLP_I2 != SQLP_NULLIND)110 9 SDK2LMS.RATING = * (short *) argv[2];111 10 for ( ; ; ) {112 SQLP_L2:113 11 sqlca.sqlcaid[6] = 0x00;114 12 SQLP_RC1 = 0;115 if (SQLP_RC1 != -1 &&

More...Debug . . .

F3=End program F6=Add/Clear breakpoint F10=Step F11=Display variableF12=Resume F17=Watch variable F18=Work with watch F24=More keys

186 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 203: Store Procedure

Figure 93. INVDSK2LMS source code

To run the INVSDK2LMS program, call the program from the command prompt,passing two required parameters as shown below:

CALL PGM(SQLPROCS/INVSDK2LMS) PARM('000010' 1)

The INVSDK2LMS program, in turn invokes the stored procedure and passes thecontrol to it. The stored procedure hits the breakpoint, and the debugger sessionis activated. On the debugging line, you can enter any of the debug commands.In this way, you can display the content of any variable, check the SQL returncode and so on. You can also step through the program using the F10 key.

Since your session is in debug mode, the job log has all the messages related tothe execution of the procedure. We highly recommend that, while developingstored procedures, you always check the joblog messages inserted by the DB2UDB for AS/400 optimizer.

Note: If your stored procedure is defined with only IN parameters and it does notreturn any results sets, you can test it very easily using the Interactive SQL. Let’ssuppose you created a stored procedure called setSalary, which takes two inputparameters: employee_number of type char(6) and salary of type decimal(11,2). Youcould test this procedure from the ISQL session by typing the following statement:

CALL setSalary (’000010’, 65000.00)

#include <stdio.h>#include <stdlib.h>#include <string.h>

EXEC SQL INCLUDE SQLCA;

EXEC SQL BEGIN DECLARE SECTION;char Employee_Number??( 6 ??);short Rating;

EXEC SQL END DECLARE SECTION;

void main( int argc, char **argv ){

/* copy the paremters to the host variables */strcpy(Employee_Number, argv??(1??));Rating = (short)*argv??( 2 ??);

/* any sql errors at the call time? */EXEC SQL WHENEVER SQLERROR GOTO badnews;

EXEC SQL CALL SAMPLE/SDK2LMS( :Employee_Number,:Rating );

if( Rating != -1)printf("Stored Procedure ran successfully...\n");

elseprintf("Error in Stored Procedure.\n");exit(0);

badnews:printf( "Error occured in invoking program. SQLCODE = %5d\n", SQLCODE);exit(1);

}

SQL Procedures for DB2 UDB for AS/400 187

Page 204: Store Procedure

6.6.4 Testing the SQL stored procedure in client/server environmentTesting and debugging of SQL stored procedures in the client/server environmentmaybe a little bit more tricky than in the traditional AS/400 environment. In thissection we will outline the steps required to debug an SQL stored procedurecalled from the Java client. The combination of Java running on the client andSQL running on a powerful database server like the AS/400 can result in a highlyscalable and robust software solution.

In our test scenario, we coded a Java client, which uses the AS/400 JDBC driver,to send the SQL request to DB2 UDB for AS/400. In the AS/400 client/serverarchitecture, a JDBC client communicates with a corresponding AS/400 serverjob, which runs the SQL requests on behalf of this client. In other words, when wecall a stored procedure from the Java client, there is an AS/400 server job thatactually invokes the stored procedure on the server and then passes back theresults to the client. The AS/400 server jobs associated with the database accessare named QZDASOINIT, and run in the QSERVER subsystem. At any giventime, there maybe a large number of database server jobs active in theQSERVER subsystem, so the first step in our debug procedure is to find theserver job, which serves our client. The Java client code we used to debug theSDK2LMS stored procedure is listed in section 6.6.4.1, “Java client calling thestored procedure on the AS/400 server” on page 190.

1. Start the Java code in debug mode and set the breakpoint at the line justbelow the invocation of the getConnection method, as shown in Figure 94.

Figure 94. Running Java client

Note: The AS/400 server job is assigned to your client after the connection wasestablished; that is why you need to set the breakpoint below the getConnectionmethod invocation.

188 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 205: Store Procedure

2. Switch to the AS/400 session. To find the QZDASOINIT job serving your Javaclient, run the following CL command:

WRKOBJLCK OBJ(TEAMXX) OBJTYPE(*USRPRF)

where TEAMXX is the user profile you use to log into the AS/400 system.

The Work with Object Locks dialog appears. There should be one job namedQZDASOINIT listed. Type 5 in the Option field next to this job, as shown inFigure 95, and hit Enter.

Figure 95. Finding the database server job

On the Work with Job dialog, select Option 10 ’Display job log, if active or on jobqueue’. The Display Job Log screen appears. Find the first message in the joblogand write down the fully qualified job name for your database server job, asshown in Figure 96.

Figure 96. Job log for a database server job

In our case, the fully qualified name is: 064728/QUSER/QZDASOINIT.

3. Return to the command prompt and run following CL command:

STRSRVJOB JOB(064728/QUSER/QZDASOINIT )

Note: The Start Service Job (STRSRVJOB) command starts the remote serviceoperation for a specified job so that other service commands can be entered toservice the specified job. Any dump, debug, and trace commands can be run inthat job until service operation ends.

Work with Object LocksSystem: AS20

Object: TEAMXX Library: QSYS Type: *USRPRF

Type options, press Enter.4=End job 5=Work with job 8=Work with job locks

Opt Job User Lock Status Scope Thread5 QZDASOINIT QUSER *SHRRD HELD *JOB

BottomF3=Exit F5=Refresh F12=Cancel

Display Job LogSystem: AS20

Job . . : QZDASOINIT User . . : QUSER Number . . . : 064728

Job 064728/QUSER/QZDASOINIT started on 09/28/99 at 15:38:56 in subsystemQSERVER in QSYS. Job entered system on 09/28/99 at 15:38:56.

Printer device QPRINT not found.Servicing user profile TEAMXX.Servicing user profile TEAMXX from client 10.10.10.10

SQL Procedures for DB2 UDB for AS/400 189

Page 206: Store Procedure

4. Start the ILE C Source Debugger for your server job with the following CLcommand:

STRDBG PGM(SAMPLE/SDK2LMS) UPDPROD(*YES)

The ILE Source Debugger loads the ILE C source created for your SQL storedprocedure. Set the breakpoint and return to the command line.

5. Switch back to the Java client session and set the breakpoint at the statementthat calls the stored procedure on the AS/400 system, as shown in Figure 97.

Figure 97. Calling the stored procedure from Java

Run the statement at the breakpoint. The execution of the client code is nowsuspended, since the control was passed to the stored procedure on the AS/400system.

6. Switch to the AS/400 session. The ILE C Source Debugger was activated, andyou can step through your stored procedure on the server. Run the procedureto the completion. The control returns to the client, and you can continue towork with the Java code.

6.6.4.1 Java client calling the stored procedure on the AS/400 serverThe following example Java program shows you how to use the AS/400 JDBCdriver to connect to the AS/400 system and call a stored procedure. It alsoteaches you how to bind IN and INOUT parameters to the CallableStatementclass. You need to pass two arguments: employee’s number and rating, to theprogram, when calling it from the command line, as shown in the example below:

java TestStoredProcedure 000010 1

190 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 207: Store Procedure

Note: Make sure the host server is up and running on the AS/400 system and thatjt400.zip is in your classpath on the client. Refer to "AS/400 Toolbox for JavaSetup Guide", SC41-5438 for more details.

import java.io.*;import java.util.*;import java.sql.*;import com.ibm.as400.access.*;import java.math.*;

class TestStoredProcedure {

// declaration of instance varsprivate Connection conn;private CallableStatement callableStmt;

public String connectToDB( ) {

String dbDriver = null;String dbURL = null;String rtnValue = null;

String uid = null;String pwd = null;

try {//Retrieve driver name and url from config.properties file

dbDriver = "com.ibm.as400.access.AS400JDBCDriver";dbURL = "jdbc:as400://as20";uid = "TEAMXX";pwd = "TEST26T";

// Register drivertry {

DriverManager.registerDriver(newcom.ibm.as400.access.AS400JDBCDriver());

} catch (Exception ex) {System.out.println("cannot register JDBC driver: " + dbDriver);ex.printStackTrace();return "cannot register JDBC driver";

}

// Get Connection to DB, passing in propertiesconn = DriverManager.getConnection(dbURL, uid, pwd);

// Create a callable statementcallableStmt = conn.prepareCall("CALL SAMPLE.SDK2LMS(?, ?)");rtnValue = ("Connected To "+ dbURL);

}catch (Exception e) {

System.out.println("Connection Failed.");System.out.println(e);

}

return (rtnValue);}

public void dispose() {

SQL Procedures for DB2 UDB for AS/400 191

Page 208: Store Procedure

try {// close the the statement, the lastly the connection

if (null != callableStmt) {callableStmt.close();

}if (null != conn) {

conn.close();}System.exit(0);

}catch (Exception e) {

System.out.println("Error while closing...");System.out.println(e);

}}

public void setSalary(String empnum, short rating) {try{

// take over commitment control within getInfo methodconn.setAutoCommit(false);

// set the input parameterscallableStmt.setString(1, empnum);callableStmt.setShort(2, rating);//register the output parametercallableStmt.registerOutParameter(2,java.sql.Types.SMALLINT);

// execute Stored ProcedurecallableStmt.executeUpdate();

// retrieve the values of the output parametershort returnCode = callableStmt.getShort(2);// print out the result of the callif( returnCode != -1)System.out.println("Stored Procedure ran successfully");elseSystem.out.println("ERROR in Stored Procedure");

// commit and give back commitment controlconn.commit();conn.setAutoCommit(true);

}catch (Exception e) {

System.out.println("Error while retrieving information from " +"Database.");

System.out.println(e);try {

// error -> rollback and give back commitment controlconn.rollback();conn.setAutoCommit(true);

} catch (Exception e2) {System.out.println("Error in rollback");System.out.println(e2);

}}

192 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 209: Store Procedure

return;}/*** Starts the application.* @param args an array of command-line arguments*/public static void main(java.lang.String[] args) {

String empnum = args[0];short rating = new Short(args[1]).shortValue();String connect = null;TestStoredProcedure jsp = new TestStoredProcedure();

try {//connect to Databaseconnect = jsp.connectToDB();System.out.println(connect);

//Retrieve information from Databasejsp.setSalary(empnum, rating);

//clean upjsp.dispose();

}catch (Exception e){

System.out.println(e);}

}

SQL Procedures for DB2 UDB for AS/400 193

Page 210: Store Procedure

194 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 211: Store Procedure

Appendix A. Sample SQL stored procedure programs

This appendix shows examples illustrating SQL stored procedures for each DB2release. The same samples were executed against OS/390, NT, and AIX. Thesample SQL stored procedure programs illustrate the theory discussed in thisredbook and are useful for getting started with the SQL Procedures language inyour own environment and gaining some hands-on experience, whatever platformyou have.

A.1 Naming convention

We used the following naming convention shown in Figure 98 for these sampleSQL stored procedures:

Figure 98. Naming convention for samples

The only exception is the sample called DSN8ES1, which will be a sampleincluded in the delivery of the PTF for SQL Procedures language support forOS/390.

The samples beginning with SDK are included when you install the DB2 SoftwareDeveloper’s Kit (SDK) on the workstation platform. They have been customizedfor use in the OS/390 platform.

A.2 OS/390 samples

A.2.1 DSN8ES1

This sample shows the use of: cursors, handlers, WHILE, IF (nested within theWHILE).

CREATE PROCEDURE DSN8ES1( IN DEPTNO CHAR(3),OUT DEPTSAL DECIMAL(15,2),OUT BONUSCNT INT )

FENCEDRESULT SET 1LANGUAGE SQL

NOT DETERMINISTICMODIFIES SQL DATA

NO DBINFOCOLLID DSN8ES51

NO WLM ENVIRONMENT

xxxxLEPEnvironment: N - Windows NT

M - OS/390X - AIX

Purpose: C - Client, S - SQL procedure

Language: L - SQL Procedures language

Uniquely identifies sample

© Copyright IBM Corp. 1999 195

Page 212: Store Procedure

ASUTIME NO LIMITSTAY RESIDENT NOPROGRAM TYPE MAIN

SECURITY DB2COMMIT ON RETURN NO

P1: BEGIN NOT ATOMICDECLARE EMPLOYEE_NUMBER CHAR(6);DECLARE EMPLOYEE_FIRSTNME CHAR(12);DECLARE EMPLOYEE_LASTNAME CHAR(15);DECLARE EMPLOYEE_SALARY DECIMAL(15,2) DEFAULT 0;DECLARE EMPLOYEE_BONUS DECIMAL(15,2) DEFAULT 0;DECLARE TOTAL_SALARY DECIMAL(15,2) DEFAULT 0;DECLARE BONUS_COUNTER INT DEFAULT 0;DECLARE ENDTABLE INT DEFAULT 0;

-- Cursor for result set of employees who got a bonusDECLARE DSN8ES1_RS_CSR CURSOR WITH RETURN WITH HOLD FOR

SELECT RS_SEQUENCE,RS_EMPNO,RS_FIRSTNME,RS_LASTNAME,RS_BONUS

FROM DSN8ES1_RS_TBLORDER BY RS_SEQUENCE;

-- Cursor to fetch department employeesDECLARE C1 CURSOR FOR

SELECT EMPNO,FIRSTNME,LASTNAME,SALARY,BONUS

FROM EMPWHERE WORKDEPT = DEPTNO;

DECLARE CONTINUE HANDLER FOR NOT FOUNDSET ENDTABLE = 1;

DECLARE EXIT HANDLER FOR SQLEXCEPTIONSET DEPTSAL = NULL;

-- Clean residual from the result set tableDELETE FROM db2res1.DSN8ES1_RS_TBL;

OPEN C1;

FETCH C1INTO EMPLOYEE_NUMBER,

EMPLOYEE_FIRSTNME,EMPLOYEE_LASTNAME,EMPLOYEE_SALARY,EMPLOYEE_BONUS;

WHILE ENDTABLE = 0 DOSET TOTAL_SALARY = TOTAL_SALARY

+ EMPLOYEE_SALARY+ EMPLOYEE_BONUS;

196 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 213: Store Procedure

IF EMPLOYEE_BONUS > 0.00 THENSET BONUS_COUNTER = BONUS_COUNTER + 1;

-- Add the employee's data to the result setINSERT INTO db2res1.DSN8ES1_RS_TBL

( RS_SEQUENCE,RS_EMPNO,RS_FIRSTNME,RS_LASTNAME,RS_SALARY,RS_BONUS )

VALUES( P1.BONUS_COUNTER,P1.EMPLOYEE_NUMBER,P1.EMPLOYEE_FIRSTNME,P1.EMPLOYEE_LASTNAME,P1.EMPLOYEE_SALARY,P1.EMPLOYEE_BONUS );

END IF;

FETCH C1INTO EMPLOYEE_NUMBER,

EMPLOYEE_FIRSTNME,EMPLOYEE_LASTNAME,EMPLOYEE_SALARY,EMPLOYEE_BONUS;

END WHILE;

CLOSE C1;SET DEPTSAL = TOTAL_SALARY;SET BONUSCNT = BONUS_COUNTER;

-- Open the cursor to the result setOPEN DSN8ES1_RS_CSR;

END P1

A.2.2 SDK0LMS

This sample shows the use of result sets.

CREATE PROCEDURE SDK0LMS (OUT MEDSAL DOUBLE)RESULT SETS 2LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL STORED PROCEDURE SDK0LNS------------------------------------------------------------------------BEGIN

DECLARE V_NUMRECORDS INT DEFAULT 1;DECLARE V_COUNTER INT DEFAULT 0;DECLARE C1 CURSOR FORSELECT INTEGER(SALARY) FROM DB2RES1.STAFFORDER BY SALARY;

-- USE WITH RETURN IN DECLARE CURSOR TO RETURN A RESULT SETDECLARE C2 CURSOR WITH RETURN FOR

Sample SQL stored procedure programs 197

Page 214: Store Procedure

SELECT NAME, JOB, INTEGER(SALARY)FROM DB2RES1.STAFFWHERE SALARY > MEDSALORDER BY SALARY;

-- YOU CAN RETURN AS MANY RESULT SETS AS YOU LIKE, JUST-- ENSURE THAT THE EXACT NUMBER IS DECLARED IN THE RESULT SETS-- CLAUSE OF THE CREATE PROCEDURE STATEMENT-- USE WITH RETURN IN DECLARE CURSOR TO RETURN ANOTHER RESULT SETDECLARE C3 CURSOR WITH RETURN FORSELECT NAME, JOB, INTEGER(SALARY)FROM DB2RES1.STAFFWHERE SALARY < MEDSALORDER BY SALARY DESC;

DECLARE EXIT HANDLER FOR NOT FOUNDSET MEDSAL = 6666;

-- INITIALIZE OUT PARAMETERSET MEDSAL = 0;SELECT COUNT(*) INTO V_NUMRECORDS FROM DB2RES1.STAFF;OPEN C1;WHILE V_COUNTER < (V_NUMRECORDS / 2 + 1) DOFETCH C1 INTO MEDSAL;SET V_COUNTER = V_COUNTER + 1;

END WHILE;CLOSE C1;-- RETURN 1ST RESULT SET, DO NOT CLOSE CURSOROPEN C2;

-- RETURN 2ND RESULT SET, DO NOT CLOSE CURSOROPEN C3;

END

A.2.3 SDK1LMS

This sample shows the use of the CASE statement. Note that the SPECIFICkeyword used for the other samples is not valid in OS/390.

CREATE PROCEDURE SDK1LMS (IN empnum char(6),IN rating INT, OUT omsg char(20))

-- SPECIFIC DRDARES1.S1156162LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

--------------------------------BEGINDECLARE not_found CONDITION FOR SQLSTATE '02000';DECLARE EXIT HANDLER FOR not_foundSET omsg = 'not found';

CASE ratingWHEN 1 THENUPDATE db2res1.employeeSET salary = salary * 1.10, bonus = 1000WHERE empno = empnum;

WHEN 2 THENUPDATE db2res1.employeeSET salary = salary * 1.05, bonus = 500WHERE empno = empnum;

ELSE

198 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 215: Store Procedure

UPDATE db2res1.employeeSET salary = salary * 1.03, bonus = 0WHERE empno = empnum;

END CASE;END

A.2.4 SDK2LMS

This sample shows the IF statement.

CREATE PROCEDURE SDK2LMS (IN empnum CHAR(6),IN rating SMALLINT )

COLLID SG245485LANGUAGE SQLWLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SDK2LNS------------------------------------------------------------------------

BEGINDECLARE not_found CONDITION FOR SQLSTATE '02000';DECLARE EXIT HANDLER FOR not_foundSET rating = -1;

IF rating = 1THEN UPDATE db2res1.employeeSET salary = salary * 1.10, bonus = 1000WHERE empno = empnum;

ELSEIF rating = 2THEN UPDATE db2res1.employeeSET salary = salary * 1.05, bonus = 500WHERE empno = empnum;

ELSE UPDATE db2res1.employeeSET salary = salary * 1.03, bonus = 0WHERE empno = empnum;

END IF;END

A.2.5 SDK3LMS

This sample shows the use of the RUN OPTIONS debug line and DYNAMIC SQLstatements.

CREATE PROCEDURE SDK3LMS(IN deptnum CHAR(3), OUT tabname CHAR(31) )LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1RUN OPTIONS 'POSIX(ON),TEST(ALL,*,,VADTCPIP&9.112.16.127:*)'

-------------------------------------------------------------------------- SQL stored procedure SDK3LMS------------------------------------------------------------------------BEGINDECLARE stmt VARCHAR(1000);-- continue if sqlstate 42704 ('undefined object name')DECLARE CONTINUE HANDLER FOR SQLSTATE '42704'SET stmt = '';

DECLARE CONTINUE HANDLER FOR SQLEXCEPTIONSET tabname = 'PROCEDURE_FAILED';

Sample SQL stored procedure programs 199

Page 216: Store Procedure

SET tabname = 'DEPT_'||deptnum||'_T';SET stmt = 'CREATE TABLE '||tabname||'( empno CHAR(6) NOT NULL, '||'firstnme VARCHAR(12) NOT NULL, '||'midinit CHAR(1) NOT NULL, '||'lastname CHAR(15) NOT NULL, '||'salary DECIMAL(9,2))' ||'IN DATABASE RUNNING' ;PREPARE s2 FROM STMT;EXECUTE s2;SET stmt = 'INSERT INTO '||tabname||' SELECT empno, firstnme, midinit, lastname, salary '||' FROM db2res1.employee e '||' WHERE workdept = ?';

PREPARE s3 FROM stmt;EXECUTE s3 USING deptnum;

END

A.2.6 SDK4LMS

This sample shows use of the LOOP and LEAVE statements. Note that theITERATE keyword is not valid for OS/390.

CREATE PROCEDURE SDK4LMS ( )LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SDK4LMS------------------------------------------------------------------------BEGIN

DECLARE v_dept CHAR(3);DECLARE v_deptname VARCHAR(29);DECLARE v_admdept CHAR(3);DECLARE at_end INT DEFAULT 0;DECLARE not_found CONDITION FOR SQLSTATE '02000';DECLARE c1 CURSOR FORSELECT deptno, deptname, admrdeptFROM db2res1.departmentORDER BY deptno;

DECLARE CONTINUE HANDLER FOR not_foundSET at_end = 1;

OPEN c1;ins_loop:LOOPFETCH c1 INTO v_dept, v_deptname, v_admdept;IF at_end = 1 THENLEAVE ins_loop;

-- ELSEIF v_dept = 'D11' THEN-- ITERATE ins_loop;

END IF;INSERT INTO db2res1.department (deptno, deptname, admrdept)VALUES ('NEW', v_deptname, v_admdept);

END LOOP;CLOSE c1;

END

200 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 217: Store Procedure

A.2.7 SDK5LMS

This sample shows use of the IF statement nested within the LOOP statement.

CREATE PROCEDURE SDK5LMS (OUT counter INT )LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SDK5LMS------------------------------------------------------------------------BEGINDECLARE v_firstnme VARCHAR(12);DECLARE v_midinit CHAR(1);DECLARE v_lastname VARCHAR(15);DECLARE at_end SMALLINT DEFAULT 0;DECLARE not_foundCONDITION for SQLSTATE '02000';

DECLARE c1 CURSOR FORSELECT firstnme, midinit, lastnameFROM db2res1.employee;

DECLARE CONTINUE HANDLER for not_foundSET at_end = 1;

-- initialize OUT parameterSET counter = 0;OPEN c1;fetch_loop:LOOPFETCH c1 INTOv_firstnme, v_midinit, v_lastname;

IF at_end <> 0 THEN LEAVE fetch_loop;END IF;SET counter = counter + 1;

END LOOP fetch_loop;CLOSE c1;

END

A.2.8 SDK6LMS

This sample also shows LEAVE and IF statements within a loop.

CREATE PROCEDURE SDK6LMS (OUT counter INT )LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SDK6LMS------------------------------------------------------------------------BEGINDECLARE v_firstnme VARCHAR(12);DECLARE v_midinit CHAR(1);DECLARE v_lastname VARCHAR(15);DECLARE c1 CURSOR FORSELECT firstnme, midinit, lastnameFROM db2res1.employee;

DECLARE CONTINUE HANDLER FOR NOT FOUNDSET counter = -1;

-- initialize OUT parameter

Sample SQL stored procedure programs 201

Page 218: Store Procedure

SET counter = 0;OPEN c1;fetch_loop:LOOPFETCH c1 INTOv_firstnme, v_midinit, v_lastname;

IF v_midinit = ' ' THENLEAVE fetch_loop;

END IF;SET counter = counter + 1;

END LOOP fetch_loop;CLOSE c1;

END

A.2.9 SDK7LMS

This sample shows nested CASE statements.

CREATE PROCEDURE SDK7LMS (IN deptnum SMALLINT )LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SDK7LMS------------------------------------------------------------------------BEGIN

DECLARE v_salary DOUBLE;DECLARE v_id SMALLINT;DECLARE v_years SMALLINT;DECLARE at_end INT DEFAULT 0;DECLARE not_found CONDITION FOR SQLSTATE '02000';DECLARE C1 CURSOR FORSELECT id, FLOAT(salary), yearsFROM db2res1.staffWHERE dept = deptnum;

DECLARE CONTINUE HANDLER FOR not_foundSET at_end = 1;

OPEN C1;FETCH C1 INTO v_id, v_salary, v_years;WHILE at_end = 0 DOCASEWHEN (v_salary < 2000 * v_years)THEN UPDATE db2res1.staffSET salary = 2150 * v_yearsWHERE id = v_id;

WHEN (v_salary < 5000 * v_years)THEN CASEWHEN (v_salary < 3000 * v_years)THEN UPDATE db2res1.staffSET salary = 4000 * v_yearsWHERE id = v_id;

ELSE UPDATE db2res1.staffSET salary = v_salary * 1.10WHERE id = v_id;

END CASE;ELSE UPDATE db2res1.staff

SET job = 'PREZ'

202 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 219: Store Procedure

WHERE id = v_id;END CASE;FETCH C1 INTO v_id, v_salary, v_years;

END WHILE;CLOSE C1;

END

A.2.10 SDK8LMS

This sample shows use of nested WHILE and IF statements.

CREATE PROCEDURE SDK8LMS (IN deptnum SMALLINT )LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SDK8LMS------------------------------------------------------------------------BEGIN

DECLARE v_salary DOUBLE;DECLARE v_id SMALLINT;DECLARE v_years SMALLINT;DECLARE at_end INT DEFAULT 0;DECLARE not_found CONDITION FOR SQLSTATE '02000';-- CAST salary as DOUBLE because SQL procedures do not support DECIMADECLARE C1 CURSOR FORSELECT id, FLOAT(salary), yearsFROM db2res1.staffWHERE dept = deptnum;

DECLARE CONTINUE HANDLER FOR not_foundSET at_end = 1;

OPEN C1;FETCH C1 INTO v_id, v_salary, v_years;WHILE at_end = 0 DOIF (v_salary < 2000 * v_years)THEN UPDATE db2res1.staffSET salary = 2150 * v_yearsWHERE id = v_id;

ELSEIF (v_salary < 5000 * v_years)THEN IF (v_salary < 3000 * v_years)THEN UPDATE db2res1.staffSET salary = 3000 * v_yearsWHERE id = v_id;

ELSE UPDATE db2res1.staffSET salary = v_salary * 1.10WHERE id = v_id;

END IF;ELSE UPDATE db2res1.staff

SET job = 'PREZ'WHERE id = v_id;

END IF;FETCH C1 INTO v_id, v_salary, v_years;

END WHILE;CLOSE C1;

END

Sample SQL stored procedure programs 203

Page 220: Store Procedure

A.2.11 SDK9LMS

Sample which uses the REPEAT statement.

CREATE PROCEDURE SDK9LMS (OUT counter INT )LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SDK9LMS------------------------------------------------------------------------BEGINDECLARE v_firstnme VARCHAR(12);DECLARE v_midinit CHAR(1);DECLARE v_lastname VARCHAR(15);DECLARE at_end SMALLINT DEFAULT 0;DECLARE not_foundCONDITION FOR SQLSTATE '02000';

DECLARE c1 CURSOR FORSELECT firstnme, midinit, lastnameFROM db2res1.employee;

DECLARE CONTINUE HANDLER FOR not_foundSET at_end = 1;

-- initialize OUT parameterSET counter = 0;OPEN c1;fetch_loop:REPEATFETCH c1 INTOv_firstnme, v_midinit, v_lastname;

SET counter = counter + 1;UNTIL at_end <> 0

END REPEAT fetch_loop;SET counter = counter - 1; -- count is 1 more than actual for repeatCLOSE c1;

END

A.2.12 SMP0LMS

This sample returns RESULT SETS using CURSOR WITH RETURN.

CREATE PROCEDURE SMP0LMS ( IN PID INT )RESULT SETS 1LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL STORED PROCEDURE SMP0LMS------------------------------------------------------------------------P1: BEGIN

-- DECLARE CURSORDECLARE CURSOR1 CURSOR WITH RETURN FOR

SELECT * FROM DB2RES1.STAFF WHERE ID > PID;OPEN CURSOR1;

END P1

204 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 221: Store Procedure

A.2.13 SMP1LMS

This sample shows use of the IF statement nested within LOOP statement.

CREATE PROCEDURE SMP1LMS ( )LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL STORED PROCEDURE SMP1LMS------------------------------------------------------------------------P1: BEGIN

DECLARE V_DEPT CHAR(3);DECLARE V_DEPTNAME VARCHAR(29);DECLARE V_MGRNO CHAR(6);DECLARE V_ADMDEPT CHAR(3);DECLARE AT_END SMALLINT DEFAULT 0;DECLARE NOT_FOUND CONDITION FOR SQLSTATE '02000';-- DECLARE CURSORDECLARE C1 CURSOR FOR

SELECTdb2res1.DEPARTMENT.DEPTNO,db2res1.DEPARTMENT.DEPTNAME,db2res1.DEPARTMENT.MGRNO,db2res1.DEPARTMENT.ADMRDEPTFROM

db2res1.DEPARTMENT;DECLARE CONTINUE HANDLER FOR NOT_FOUNDSET AT_END = 1;

OPEN c1;loop1:LOOPFETCH c1 into v_dept, v_deptname, v_mgrno, v_admdept;IF at_end = 1 THENLEAVE loop1;

ELSEIF v_mgrno is null THENUPDATE db2res1.departmentset mgrno = '000000' where deptno = v_dept;

ELSEIF v_mgrno = '000000' THENUPDATE db2res1.departmentset mgrno = null where deptno = v_dept;

END IF;END LOOP;

END P1

A.2.14 SMP2LMS

This sample was created to test various date and time values being returned.

CREATE PROCEDURE SMP2LMS (out vuser char(8), out vdate1 date,out vdate2 date, out vdays1 integer, out vtime1 time,out vtime2 time, out vtimest1 timestamp, out vtimest2 timestamp)

LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SMP2LMS------------------------------------------------------------------------P1: BEGIN

Sample SQL stored procedure programs 205

Page 222: Store Procedure

set vuser = user;set vdate1 = current date;set vdate2 = vdate1 - 10 days + 3 years;set vdays1 = days(vdate2);set vtime1 = current time;set vtime2 = vtime1 +1 hour - 30 minutes;set vtimest1 = current timestamp;set vtimest2 = vtimest1 - days(vdate1 - 10 days) days;

END p1

A.2.15 SMP3LMS

This sample was created to test the settings of null and zero.

CREATE PROCEDURE SMP3LMS(out msg1 char(20), out msg2 char(20), out msg3 char(20) )

LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SMP3LMS------------------------------------------------------------------------P1: BEGIN

declare v_var1 integer;if v_var1 is null then

set msg1 = 'is null';elseif v_var1 = 0 then

set msg1 = 'is zero';end if;

set v_var1 = null;

if v_var1 is null thenset msg2 = 'is null';

end if;set v_var1 = 0;if v_var1 is not null then

set msg3 = 'not null';end if;

END p1

A.2.16 SMP4LMS

This is the equivalent sample when run on NT, which allows parameter andvariable names to be the same. On OS/390 it was invalid, even when we prefixedthe parameter name with the procedure name, and the variable name with thelabel name. To make it work, we had to have unique parameter and variablenames.

CREATE PROCEDURE SMP4LMS(out pvar1 integer, out pvar2 double )

LANGUAGE SQLCOLLID SG245485WLM ENVIRONMENT WLMENV1

-------------------------------------------------------------------------- SQL stored procedure SMP4LMS------------------------------------------------------------------------

206 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 223: Store Procedure

BEGINdeclare vvar1 integer;declare vvar2 smallint;

set vvar1 = 10;set pvar1 = vvar1;set vvar2 = 20;set pvar2 = vvar2;

END

A.2.17 SMP5LMS

This sample shows that variable and column names could be the same, but youneed to qualify the variable name with the label name (P1) and the column namewith the table name (staff).

CREATE PROCEDURE SMP5LMS(out pid integer )

LANGUAGE SQLCOLLID SG245485

-------------------------------------------------------------------------- SQL stored procedure smp5LMS------------------------------------------------------------------------

P1: BEGINdeclare id integer;set id = 100;select staff.id into p1.id from db2res1.staff where staff.id=p1.id;set pid = p1.id;

END P1

A.2.18 SMP5LMS2

This sample shows that parameter and column names could be the same, butyou need to qualify the column name with the table name (staff).

CREATE PROCEDURE SMP5LMS(inout id integer )

LANGUAGE SQLCOLLID SG245485

-------------------------------------------------------------------------- SQL stored procedure SMP5LMS------------------------------------------------------------------------

L1: BEGINSELECT staff.id INTO idFROM db2res1.staff WHERE staff.id=id;

END L1

A.2.19 SMP7LMS

This sample shows how to return the SQLSTATE and SQLCODE as parametersfrom the SQL procedure. Note the use of IF (1=1) within the handler declaration.

CREATE PROCEDURE SMP7LMS ( OUT PSQLST char(5),

Sample SQL stored procedure programs 207

Page 224: Store Procedure

OUT PSQLCO int )RESULT SETS 1LANGUAGE SQLCOLLID SG245485ASUTIME NO LIMIT

-------------------------------------------------------------------------- SQL stored procedure SYSPROC.SMP7LMS------------------------------------------------------------------------P1: BEGIN

DECLARE SQLSTATE CHAR(5) DEFAULT '00000';DECLARE SQLCODE INT DEFAULT 0;

-- Declare cursorDECLARE cursor1 CURSOR WITH RETURN FOR

SELECT * FROM db2res1.STAFF;

DECLARE EXIT HANDLER FOR SQLEXCEPTIONIF (1 = 1) THEN

SET PSQLST = SQLSTATE;SET PSQLCO = SQLCODE;

END IF;-- Cursor left open for client applicationOPEN cursor1;SET PSQLST = SQLSTATE;SET PSQLCO = SQLCODE;

END P1

A.2.20 SMP8LMS

This sample was used to test most column and scalar functions for version 5.

CREATE PROCEDURE DRDARES1.SMP8LMS (out v1 double,out v2 integer,out v3 integer,out v4 integer ,out v5 integer,out v6 char(15),out v7 char (5),out v8 decimal(15),out v9 char(10), out v10 double,out v11 char(5), out v12 integer, out v13 integer, out v14 char(5))

COLLID SG245485WLM ENVIRONMENT WLMENV1LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure SMP8LMS------------------------------------------------------------------------P1: BEGIN

SELECT AVG(SALARY),COUNT(*),MAX(SALARY),MIN(SALARY),SUM(SALARY)INTO v1,v2,v3,v4,v5FROM DB2RES1.STAFF;set v6 = char(current date);set v7 = coalesce('hello','');set v8 = decimal(10);set v9 = digits(12345);set v10 = float(123);SELECT HEX(ID),INTEGER(SALARY), LENGTH(NAME)INTO v11,v12,v13FROM DB2RES1.STAFF WHERE ID = 100;set v14 = nullif('hello','HELLO');

END P1

208 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 225: Store Procedure

A.2.21 SMP8LMS2

This sample was created to test the column and scalar functions for version 6.

CREATE PROCEDURE ADMF001.SMP8LMS2 (out v1 double,out v2 double,out v3 integer, out v5 decimal(10), out v7 varchar (27),out v8 integer,out v9 integer, out v10 integer,out v12 char(8), out v13 char(3), out v14 integer,out v15 integer, out v16 integer, out v17 char(12), out v18 integer)

COLLID SG245485WLM ENVIRONMENT WLMENV1LANGUAGE SQL

---------------------------------------------------------------------- SQL STORED PROCEDURE ADMF001.SMP8LMS2--------------------------------------------------------------------P1: BEGIN

SELECT STDDEV(SALARY),VAR(SALARY) INTO v1,v2 FROM DB2RES1.STAFF;SET v3 = ABS(-4356);SELECT CEIL(MAX(SALARY)/12) INTO v5 FROM DSN8710.EMP;SELECT CONCAT(FIRSTNME,LASTNAME) INTO v7 FROM DSN8710.EMP

WHERE EMPNO = '000140';SELECT DAYOFWEEK(HIREDATE) INTO v8 FROM DSN8710.EMP

WHERE EMPNO = '000140';SELECT AVG(DAYOFYEAR(HIREDATE)) INTO v9 FROM DSN8710.EMP;SELECT FLOOR(MAX(SALARY)/12) INTO v10 FROM DSN8710.EMP;SET v12 = LCASE('KATHLEEN');SET v13 = LEFT('JONATHAN',3);SELECT MIDNIGHT_SECONDS('24:00:00'),MIDNIGHT_SECONDS('00:00:00')

INTO v14,v15 FROM SYSIBM.SYSDUMMY1;SET v16 = QUARTER('1999-09-09');SET v17 = REPEAT('KATH',3);SET v18 = SIGN(-1000);

END P1

A.3 NT and AIX samples

A.3.1 SDK0LNS

This sample shows how RESULT SETS can be returned to the client.

CREATE PROCEDURE DRDARES1.SDK0LNS (OUT medianSalary DOUBLE)RESULT SETS 2SPECIFIC DRDARES1.S0265192LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDK0LNS------------------------------------------------------------------------BEGIN

DECLARE v_numRecords INT DEFAULT 1;DECLARE v_counter INT DEFAULT 0;

DECLARE c1 CURSOR FORSELECT CAST(salary AS DOUBLE) FROM staffORDER BY salary;

-- use WITH RETURN in DECLARE CURSOR to return a result setDECLARE c2 CURSOR WITH RETURN FORSELECT name, job, CAST(salary AS INTEGER)FROM staff

Sample SQL stored procedure programs 209

Page 226: Store Procedure

WHERE salary > medianSalaryORDER BY salary;

-- you can return as many result sets as you like, just-- ensure that the exact number is declared in the RESULT SETS-- clause of the CREATE PROCEDURE statement

-- use WITH RETURN in DECLARE CURSOR to return another result setDECLARE c3 CURSOR WITH RETURN FORSELECT name, job, CAST(salary AS INTEGER)FROM staffWHERE salary < medianSalaryORDER BY SALARY DESC;

DECLARE EXIT HANDLER FOR NOT FOUNDSET medianSalary = 6666;

-- initialize OUT parameterSET medianSalary = 0;

SELECT COUNT(*) INTO v_numRecords FROM STAFF;

OPEN c1;WHILE v_counter < (v_numRecords / 2 + 1) DOFETCH c1 INTO medianSalary;SET v_counter = v_counter + 1;

END WHILE;CLOSE c1;

-- return 1st result set, do not CLOSE cursorOPEN c2;

-- return 2nd result set, do not CLOSE cursorOPEN c3;

END

A.3.2 SDK1LNS

This sample shows the CASE statement.

CREATE PROCEDURE DRDARES1.SDK1LNS (IN employee_number CHAR(6),IN rating INT)

SPECIFIC DRDARES1.S1156162RESULT SETS 1LANGUAGE SQLBEGINDECLARE not_found CONDITION FOR SQLSTATE '02000';DECLARE EXIT HANDLER FOR not_foundSIGNAL SQLSTATE '02444';

CASE ratingWHEN 1 THENUPDATE employeeSET salary = salary * 1.10, bonus = 1000WHERE empno = employee_number;

WHEN 2 THENUPDATE employeeSET salary = salary * 1.05, bonus = 500

210 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 227: Store Procedure

WHERE empno = employee_number;ELSEUPDATE employeeSET salary = salary * 1.03, bonus = 0WHERE empno = employee_number;

END CASE;END

A.3.3 SDK2LNS

This sample is similar to the one above, but it is implemented using the IFstatement.

CREATE PROCEDURE DRDARES1.SDK2LNS (IN employee_number CHAR(6), IN ratingSMALLINT )

SPECIFIC DRDARES1.S030109LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDK2LNS------------------------------------------------------------------------

BEGINDECLARE not_found CONDITION FOR SQLSTATE '02000';DECLARE EXIT HANDLER FOR not_foundSET rating = -1;

IF rating = 1THEN UPDATE employeeSET salary = salary * 1.10, bonus = 1000WHERE empno = employee_number;

ELSEIF rating = 2THEN UPDATE employeeSET salary = salary * 1.05, bonus = 500WHERE empno = employee_number;

ELSE UPDATE employeeSET salary = salary * 1.03, bonus = 0WHERE empno = employee_number;

END IF;END

A.3.4 SDK3LNS

This sample shows use of DYNAMIC SQL statements.

CREATE PROCEDURE DRDARES1.SDK3LNS (IN deptNumber CHAR(4), OUT table_nameCHAR(31) )

SPECIFIC DRDARES1.S041662LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDK3LNS------------------------------------------------------------------------

BEGINDECLARE stmt VARCHAR(1000);

-- continue if sqlstate 42704 ('undefined object name')DECLARE CONTINUE HANDLER FOR SQLSTATE '42704'SET stmt = '';

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION

Sample SQL stored procedure programs 211

Page 228: Store Procedure

SET table_name = 'PROCEDURE_FAILED';

SET table_name = 'DEPT_'||deptNumber||'_T';SET stmt = 'DROP TABLE '||table_name;PREPARE s1 FROM stmt;EXECUTE s1;SET stmt = 'CREATE TABLE '||table_name||'( empno CHAR(6) NOT NULL, '||'firstnme VARCHAR(12) NOT NULL, '||'midinit CHAR(1) NOT NULL, '||'lastname CHAR(15) NOT NULL, '||'salary DECIMAL(9,2))';PREPARE s2 FROM STMT;EXECUTE s2;SET stmt = 'INSERT INTO '||table_name ||'SELECT empno, firstnme, midinit, lastname, salary '||'FROM employee '||'WHERE workdept = ?';

PREPARE s3 FROM stmt;EXECUTE s3 USING deptNumber;

END

A.3.5 SDK4LNS

This sample shows the LOOP, LEAVE and ITERATE statements.

CREATE PROCEDURE DRDARES1.SDK4LMS ( )SPECIFIC DRDARES1.S0202895LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDK4LMS------------------------------------------------------------------------

BEGINDECLARE v_dept CHAR(3);DECLARE v_deptname VARCHAR(29);DECLARE v_admdept CHAR(3);DECLARE at_end INT DEFAULT 0;

DECLARE not_found CONDITION FOR SQLSTATE '02000';DECLARE c1 CURSOR FORSELECT deptno, deptname, admrdeptFROM departmentORDER BY deptno;

DECLARE CONTINUE HANDLER FOR not_foundSET at_end = 1;

OPEN c1;ins_loop:LOOPFETCH c1 INTO v_dept, v_deptname, v_admdept;IF at_end = 1 THENLEAVE ins_loop;

ELSEIF v_dept = 'D11' THENITERATE ins_loop;

END IF;INSERT INTO department (deptno, deptname, admrdept)

212 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 229: Store Procedure

VALUES ('NEW', v_deptname, v_admdept);END LOOP;CLOSE c1;

END

A.3.6 SDK5LNS

This sample shows the LOOP and IF statements.

CREATE PROCEDURE DRDARES1.SDK5LNS (OUT counter INT )SPECIFIC DRDARES1.S0214278LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDK5LNS------------------------------------------------------------------------BEGINDECLARE v_firstnme VARCHAR(12);DECLARE v_midinit CHAR(1);DECLARE v_lastname VARCHAR(15);DECLARE at_end SMALLINT DEFAULT 0;DECLARE not_foundCONDITION for SQLSTATE '02000';

DECLARE c1 CURSOR FORSELECT firstnme, midinit, lastnameFROM employee;

DECLARE CONTINUE HANDLER for not_foundSET at_end = 1;

-- initialize OUT parameterSET counter = 0;OPEN c1;fetch_loop:LOOPFETCH c1 INTOv_firstnme, v_midinit, v_lastname;

SET counter = counter + 1;IF at_end <> 0 THEN LEAVE fetch_loop;END IF;

END LOOP fetch_loop;CLOSE c1;

END

A.3.7 SDK6LNS

This sample also shows the LOOP and LEAVE statements.

CREATE PROCEDURE DRDARES1.SDK6LNS (OUT counter INT )SPECIFIC DRDARES1.S0225562LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDK6LNS------------------------------------------------------------------------

BEGINDECLARE v_firstnme VARCHAR(12);DECLARE v_midinit CHAR(1);DECLARE v_lastname VARCHAR(15);DECLARE c1 CURSOR FOR

Sample SQL stored procedure programs 213

Page 230: Store Procedure

SELECT firstnme, midinit, lastnameFROM employee;

DECLARE CONTINUE HANDLER FOR NOT FOUNDSET counter = -1;

-- initialize OUT parameterSET counter = 0;OPEN c1;fetch_loop:LOOPFETCH c1 INTOv_firstnme, v_midinit, v_lastname;

SET counter = counter + 1;IF v_midinit = ' ' THENLEAVE fetch_loop;

END IF;END LOOP fetch_loop;CLOSE c1;

END

A.3.8 SDK7LNS

This sample shows nested CASE statements.

CREATE PROCEDURE DRDARES1.SDK7LNS (IN deptnumber SMALLINT )SPECIFIC DRDARES1.S0235345LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDK7LNS------------------------------------------------------------------------BEGIN

DECLARE v_salary DOUBLE;DECLARE v_id SMALLINT;DECLARE v_years SMALLINT;DECLARE at_end INT DEFAULT 0;DECLARE not_found CONDITION FOR SQLSTATE '02000';

-- CAST salary as DOUBLE because SQL procedures do not support DECIMALDECLARE C1 CURSOR FORSELECT id, CAST(salary AS DOUBLE), yearsFROM staffWHERE dept = deptnumber;

DECLARE CONTINUE HANDLER FOR not_foundSET at_end = 1;

OPEN C1;FETCH C1 INTO v_id, v_salary, v_years;WHILE at_end = 0 DOCASEWHEN (v_salary < 2000 * v_years)THEN UPDATE staffSET salary = 2150 * v_yearsWHERE id = v_id;

WHEN (v_salary < 5000 * v_years)THEN CASEWHEN (v_salary < 3000 * v_years)THEN UPDATE staffSET salary = 3000 * v_years

214 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 231: Store Procedure

WHERE id = v_id;ELSE UPDATE staffSET salary = v_salary * 1.10WHERE id = v_id;

END CASE;ELSE UPDATE staffSET job = 'PREZ'WHERE id = v_id;

END CASE;FETCH C1 INTO v_id, v_salary, v_years;

END WHILE;CLOSE C1;

END

A.3.9 SDK8LNS

This sample shows nested IF statement within a WHILE statement.

CREATE PROCEDURE DRDARES1.SDK8LNS (IN deptnumber SMALLINT )SPECIFIC DRDARES1.S0244956LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDK8LNS------------------------------------------------------------------------BEGIN

DECLARE v_salary DOUBLE;DECLARE v_years SMALLINT;DECLARE v_id SMALLINT;DECLARE at_end INT DEFAULT 0;DECLARE not_found CONDITION FOR SQLSTATE '02000';

-- CAST salary as DOUBLE because SQL procedures do not support DECIMALDECLARE C1 CURSOR FORSELECT id, CAST(salary AS DOUBLE), yearsFROM staff;

DECLARE CONTINUE HANDLER FOR not_foundSET at_end = 1;

OPEN C1;FETCH C1 INTO v_id, v_salary, v_years;WHILE at_end = 0 DOIF (v_salary < 2000 * v_years)THEN UPDATE staffSET salary = 2150 * v_yearsWHERE id = v_id;

ELSEIF (v_salary < 5000 * v_years)THEN IF (v_salary < 3000 * v_years)THEN UPDATE staffSET salary = 3000 * v_yearsWHERE id = v_id;

ELSE UPDATE staffSET salary = v_salary * 1.10WHERE id = v_id;

END IF;ELSE UPDATE staffSET job = 'PREZ'WHERE id = v_id;

END IF;

Sample SQL stored procedure programs 215

Page 232: Store Procedure

FETCH C1 INTO v_id, v_salary, v_years;END WHILE;CLOSE C1;

END

A.3.10 SDK9LNS

This sample shows the REPEAT statement.

CREATE PROCEDURE DRDARES1.SDK9LNS (OUT counter INT )SPECIFIC DRDARES1.S0254846LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDK9LNS------------------------------------------------------------------------BEGINDECLARE v_firstnme VARCHAR(12);DECLARE v_midinit CHAR(1);DECLARE v_lastname VARCHAR(15);DECLARE at_end SMALLINT DEFAULT 0;DECLARE not_foundCONDITION FOR SQLSTATE '02000';

DECLARE c1 CURSOR FORSELECT firstnme, midinit, lastnameFROM employee;

DECLARE CONTINUE HANDLER FOR not_foundSET at_end = 1;

-- initialize OUT parameterSET counter = 0;OPEN c1;fetch_loop:REPEATFETCH c1 INTOv_firstnme, v_midinit, v_lastname;

SET counter = counter + 1;UNTIL at_end <> 0

END REPEAT fetch_loop;CLOSE c1;

END

A.3.11 SDKALNS

This sample is similar to the previous one, but it is implemented using the WHILEstatement.

CREATE PROCEDURE DRDARES1.SDKALNS (IN deptNumber SMALLINT,OUT medianSalary DOUBLE )

SPECIFIC DRDARES1.S0304753LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SDKALNS------------------------------------------------------------------------BEGIN

DECLARE v_numRecords INT DEFAULT 1;DECLARE v_counter INT DEFAULT 0;

216 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 233: Store Procedure

DECLARE c1 CURSOR FORSELECT CAST(salary AS DOUBLE) FROM staffWHERE DEPT = deptNumberORDER BY salary;

DECLARE EXIT HANDLER FOR NOT FOUNDSET medianSalary = 6666;

-- initialize OUT parameterSET medianSalary = 0;

SELECT COUNT(*) INTO v_numRecords FROM staffWHERE DEPT = deptNumber;

OPEN c1;WHILE v_counter < (v_numRecords / 2 + 1) DOFETCH c1 INTO medianSalary;SET v_counter = v_counter + 1;

END WHILE;CLOSE c1;

END

A.3.12 SMP1LNS

This sample shows an IF statement within a LOOP statement.

CREATE PROCEDURE DRDARES1.SMP1LNS ( )SPECIFIC DRDARES1.S4141979LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SMP1LNS------------------------------------------------------------------------P1: BEGIN

DECLARE v_dept CHAR(3);DECLARE v_deptname VARCHAR(29);declare v_mgrno char(6);DECLARE v_admdept CHAR(3);declare at_end smallint default 0;DECLARE not_found CONDITION FOR SQLstate '02000';

-- Declare cursorDECLARE c1 CURSOR FOR

SELECTDRDARES1.DEPARTMENT.DEPTNO,DRDARES1.DEPARTMENT.DEPTNAME,DRDARES1.DEPARTMENT.MGRNO,DRDARES1.DEPARTMENT.ADMRDEPTFROM

DRDARES1.DEPARTMENT;DECLARE CONTINUE HANDLER FOR not_foundSET at_end = 1;

OPEN c1;loop1:LOOPFETCH c1 into v_dept, v_deptname, v_mgrno, v_admdept;IF at_end = 1 THENLEAVE loop1;

ELSEIF v_mgrno is null THEN

Sample SQL stored procedure programs 217

Page 234: Store Procedure

UPDATE department set mgrno = '000000' where deptno = v_dept;ELSEIF v_mgrno = '000000' THENUPDATE department set mgrno = null where deptno = v_dept;

END IF;ITERATE loop1;

END LOOP;END P1

A.3.13 SMP2LNS

This sample shows testing of various date and time functions.

CREATE PROCEDURE DRDARES1.SMP2LNS ( out v_user char(8), out v_date1 date,out v_date2 date, out v_days1 integer, out v_time1 time,out v_time2 time, out v_timest1 timestamp, out v_timest2 timestamp)

SPECIFIC DRDARES1.S5336343LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SMP2LNS------------------------------------------------------------------------P1: BEGIN

set v_user = user;set v_date1 = current date;set v_date2 = v_date1 - 10 days + 3 years;set v_days1 = days(v_date2);set v_time1 = current time;set v_time2 = v_time1 +1 hour - 30 minutes;set v_timest1 = current timestamp;set v_timest2 = v_timest1 - days(v_date1 - 10 days) days;

END P1

A.3.14 SMP3LNS

This sample shows testing of null and zero indicators.

CREATE PROCEDURE DRDARES1.SMP3LNS (out msg1 char(20), out msg2 char(20), outmsg3 char(20) )

SPECIFIC DRDARES1.S0535160LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SMP3LNS------------------------------------------------------------------------P1: BEGIN

declare v_var1 integer;

if v_var1 is null thenset msg1 = 'is null';

elseif v_var1 = 0 thenset msg1 = 'is zero';

end if;

set v_var1 = null;

if v_var1 is null thenset msg2 = 'is null';

end if;

218 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 235: Store Procedure

set v_var1 = 0;

if v_var1 is not null thenset msg3 = 'not null';

end if;END P1

A.3.15 SMP4LNS

This sample shows the same parameter and variable names, but they need to bequalified.

CREATE PROCEDURE DRDARES1.SMP4LNS (out v_var1 integer, out v_var2 double )SPECIFIC DRDARES1.S1473953LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SMP4LNS------------------------------------------------------------------------P1: BEGIN

declare v_var1 integer;declare v_var2 smallint;

set v_var1 = 10;set smp4lns.v_var1 = p1.v_var1;set v_var2 = 20;set smp4lns.v_var2 = p1.v_var2;

END P1

A.3.16 SMP5LNS

This sample shows the same variable and column names. Only the variableneeds to be qualified in the WHERE clause.

CREATE PROCEDURE DRDARES1.SMP5LNS (out p_id integer )LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SMP5LNS------------------------------------------------------------------------P1: BEGIN

declare id integer;set id = 100;select id into id from staff where id=p1.id;set p_id = id;

END P1

A.3.17 SMP7LNS

This sample tests SQLSTATE and SQLCODE. When run for a row that was notfound, only MSG3 was set to ’NOT FOUND’.

CREATE PROCEDURE DRDARES1.SMP7LNS (OUT PARM1 INTEGER, OUT MSG CHAR(10), OUTMSG1 CHAR(10), out msg2 char(10),OUT MSG3 CHAR(10), IN P_ID INTEGER)

SPECIFIC S1140197LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SMP7LNS

Sample SQL stored procedure programs 219

Page 236: Store Procedure

------------------------------------------------------------------------P1: BEGIN

DECLARE VAR1 CHAR(20);DECLARE SQLSTATE CHAR(5) DEFAULT '00000';DECLARE SQLCODE INT DEFAULT 0;

DECLARE NOT_FOUND CONDITION FOR SQLSTATE '02000';DECLARE CONTINUE HANDLER FOR NOT_FOUND SET MSG3='NOT FOUND';

SELECT NAME INTO VAR1 FROM STAFF WHERE ID=P_ID;

SET PARM1 = SQLCODE;IF SQLCODE = 100 THEN

SET MSG = 'NOT FOUND';END IF;IF PARM1 = 100 THEN

SET MSG1 = 'NOT FOUND';END IF;IF SQLSTATE = '02000' THEN

SET MSG2 = 'NOT FOUND';END IF;

END P1

A.3.18 SMP8LNS

This sample tests various scalar functions.

CREATE PROCEDURE DRDARES1.SMP8LNS (out v1 double, out v2 double, out v3integer,out v4 integer , out v5 integer, out v6 integer , out v7 char (5),out v8 char(10), out v9 char(10), out v10 char (20), out v11 char(5), out v12char(10))

SPECIFIC DRDARES1.S8389109LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SMP8LNS------------------------------------------------------------------------P1: BEGIN

set v1 = tan(.5) - (sin(.5)/cos(.5));set v2 = exp(sin(.3)) + exp(cos(.3));set v3 = rand();set v4 = ceil(5.2) + floor(4.3);set v5 = quarter(current date);set v6 = week(current date);set v7 = repeat('*',5);set v8 = lcase('ALINE');set v9 = replace('a1b1c1','1','2');set v10 = monthname(current date) || dayname(current date);set v11 = ltrim('felipe ');set v12 = substr('abcdefghijklmnopq',5,10);

END P1

A.3.19 SMP9LNS

This sample tests the SQLCODE. It has an interesting result, in that only PARM1and MSG1 were set correctly.

220 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 237: Store Procedure

CREATE PROCEDURE DRDARES1.SMP9LNS (OUT PARM1 INTEGER, OUT MSG CHAR(10), OUTMSG1 CHAR(10), out msg2 char(10),IN P_ID INTEGER)SPECIFIC S1230197LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SMP7LNS------------------------------------------------------------------------P1: BEGIN

DECLARE VAR1 CHAR(20);DECLARE SQLSTATE CHAR(5) DEFAULT '00000';DECLARE SQLCODE INT DEFAULT 0;

SELECT NAME INTO VAR1 FROM STAFF WHERE ID=P_ID;

SET PARM1 = SQLCODE;IF SQLCODE = 100 THEN

SET MSG = 'NOT FOUND';END IF;IF PARM1 = 100 THEN

SET MSG1 = 'NOT FOUND';END IF;IF SQLSTATE = '02000' THEN

SET MSG2 = 'NOT FOUND';END IF;

END P1

A.3.20 SMPALNS

This sample shows the SQLCODE being passed as an output parameter.

CREATE PROCEDURE DRDARES1.SMPALNS (in vid integer, out sqlc integer, out var1integer)

SPECIFIC DRDARES1.S1140337LANGUAGE SQL

-------------------------------------------------------------------------- SQL stored procedure DRDARES1.SMPALNS------------------------------------------------------------------------P1: BEGIN

DECLARE CONTINUE HANDLER FOR NOT FOUNDBEGINSET SQLC=SQLCODE;SET VAR1=1;

END;

SELECT id into vid FROM STAFF where id = vid;

END P1

Sample SQL stored procedure programs 221

Page 238: Store Procedure

222 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 239: Store Procedure

Appendix B. Special notices

This publication is intended to help database administrators implement DB2 SQLStored Procedures and the Stored Procedures Builder in a client/serverenvironment. The information in this publication is not intended as thespecification of any programming interfaces that are provided by the DB2 familyof products. See the PUBLICATIONS section of the IBM ProgrammingAnnouncement for Stored Procedure Builder and the DB2 UDB SQL Proceduressupport for more information about what publications are considered to beproduct documentation.

References in this publication to IBM products, programs or services do not implythat IBM intends to make these available in all countries in which IBM operates.Any reference to an IBM product, program, or service is not intended to state orimply that only IBM's product, program, or service may be used. Any functionallyequivalent program that does not infringe any of IBM's intellectual property rightsmay be used instead of the IBM product, program or service.

Information in this book was developed in conjunction with use of the equipmentspecified, and is limited in application to those specific hardware and softwareproducts and levels.

IBM may have patents or pending patent applications covering subject matter inthis document. The furnishing of this document does not give you any license tothese patents. You can send license inquiries, in writing, to the IBM Director ofLicensing, IBM Corporation, North Castle Drive, Armonk, NY 10504-1785.

Licensees of this program who wish to have information about it for the purposeof enabling: (i) the exchange of information between independently createdprograms and other programs (including this one) and (ii) the mutual use of theinformation which has been exchanged, should contact IBM Corporation, Dept.600A, Mail Drop 1329, Somers, NY 10589 USA.

Such information may be available, subject to appropriate terms and conditions,including in some cases, payment of a fee.

The information contained in this document has not been submitted to any formalIBM test and is distributed AS IS. The information about non-IBM ("vendor")products in this manual has been supplied by the vendor and IBM assumes noresponsibility for its accuracy or completeness. The use of this information or theimplementation of any of these techniques is a customer responsibility anddepends on the customer's ability to evaluate and integrate them into thecustomer's operational environment. While each item may have been reviewedby IBM for accuracy in a specific situation, there is no guarantee that the same orsimilar results will be obtained elsewhere. Customers attempting to adapt thesetechniques to their own environments do so at their own risk.

Any pointers in this publication to external Web sites are provided forconvenience only and do not in any manner serve as an endorsement of theseWeb sites.

Any performance data contained in this document was determined in a controlledenvironment, and therefore, the results that may be obtained in other operating

© Copyright IBM Corp. 1999 223

Page 240: Store Procedure

environments may vary significantly. Users of this document should verify theapplicable data for their specific environment.

Reference to PTF numbers that have not been released through the normaldistribution process does not imply general availability. The purpose of includingthese reference numbers is to alert IBM customers to specific information relativeto the implementation of the PTF when it becomes available to each customeraccording to the normal IBM PTF distribution process.

The following terms are trademarks of the International Business MachinesCorporation in the United States and/or other countries:

The following terms are trademarks of other companies:

C-bus is a trademark of Corollary, Inc. in the United States and/or other countries.

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

Microsoft, Windows, Windows NT, and the Windows logo are trademarks ofMicrosoft Corporation in the United States and/or other countries.

PC Direct is a trademark of Ziff Communications Company in the United Statesand/or other countries and is used by IBM Corporation under license.

ActionMedia, LANDesk, MMX, Pentium and ProShare are trademarks of IntelCorporation in the United States and/or other countries.

ACF/VTAM AD/CycleAIX AS/400AT CTCICS CICS/ESAC/370 DATABASE 2DataGuide DataJoinerDataPropagator DB2DFSMS DFSMS/MVSDFSORT GDDMESCON ES/9000Hiperspace IBMBMLink IMSInformation Warehouse Integrated Language EnvironmentIntelligent Miner Language EnvironmentMultiprise MVS/ESANet.Data NetfinityOS/2 OS/390OS/400 Parallel SysplexPR/SM QMFRACF RAMACRETAIN RMFRS/6000 SPSP1 SP2S/390 S/390 Parallel Enterprise ServerSystem/390 VisualAgeVisualGen Visual WarehouseVM/ESA VSE/ESAVTAM WebSphereXT 400

224 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 241: Store Procedure

UNIX is a registered trademark in the United States and/or other countrieslicensed exclusively through X/Open Company Limited.

SET and the SET logo are trademarks owned by SET Secure ElectronicTransaction LLC.

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

Special notices 225

Page 242: Store Procedure

226 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 243: Store Procedure

Appendix C. Related publications

The publications listed in this section are considered particularly suitable for amore detailed discussion of the topics covered in this redbook.

C.1 International Technical Support Organization publications

For information on ordering these ITSO publications see “How to get ITSOredbooks” on page 229.

• Getting Started with DB2 Stored Procedures: Give Them a Call through theNetwork, SG24-4693

• DB2 Server for OS/390 Version 5 Recent Enhancements - Reference Guide,SG24-5421

• DB2/400 Advanced Database Functions, SG24-4249

• DB2 DRDA Supports TCP/IP, SG24-2212

C.2 Redbooks on CD-ROMs

Redbooks are also available on the following CD-ROMs. Click the CD-ROMsbutton at http://www.redbooks.ibm.com/ for information about all the CD-ROMsoffered, updates and formats.

C.3 Other publications

These publications are also relevant as further information sources:

• DB2 for OS/390 V5 Preview os SQL Procedures, (*)

• DB2 for OS/390 V5 Application Programming and SQL Guide, SC26-8958

• DB2 for OS/390 V5 SQL Reference, SC26-8966

• DB2 UDB for OS/390 V6 Preview os SQL Procedures, (*)

• DB2 UDB for OS/390 V6 Application Programming and SQL Guide,SC26-9004

• DB2 UDB for OS/390 V6 SQL Reference, SC26-9014

• DB2 UDB Version 6 SQL Reference, Volume 1 and Volume 2, SBOF-8923

• DB2 UDB Version 6 Application Development, SC09-2845

CD-ROM Title Collection KitNumber

System/390 Redbooks Collection SK2T-2177Networking and Systems Management Redbooks Collection SK2T-6022Transaction Processing and Data Management Redbooks Collection SK2T-8038Lotus Redbooks Collection SK2T-8039Tivoli Redbooks Collection SK2T-8044AS/400 Redbooks Collection SK2T-2849Netfinity Hardware and Software Redbooks Collection SK2T-8046RS/6000 Redbooks Collection (BkMgr Format) SK2T-8040RS/6000 Redbooks Collection (PDF Format) SK2T-8043Application Development Redbooks Collection SK2T-8037IBM Enterprise Storage and Systems Management Solutions SK3T-3694

© Copyright IBM Corp. 1999 227

Page 244: Store Procedure

• Debug Tool: User’s Guide and Reference, SC09-2137

• AS/400 Toolbox for Java Setup Guide", SC41-5438

• Understanding SQL’s Stored Procedures: A Complete Guide to SQL/PSM, JimMelton, Norgan Kaufmann Publishers, Inc., ISBN 1-55860-461-8.

(*) download throuth the Web:

http://www.software.ibm.com/db2/os390/sqlproc

228 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 245: Store Procedure

How to get ITSO redbooks

This section explains how both customers and IBM employees can find out about ITSO redbooks, redpieces, andCD-ROMs. A form for ordering books and CD-ROMs by fax or e-mail is also provided.

• Redbooks Web Site http://www.redbooks.ibm.com/

Search for, view, download, or order hardcopy/CD-ROM redbooks from the redbooks Web site. Also readredpieces and download additional materials (code samples or diskette/CD-ROM images) from this redbookssite.

Redpieces are redbooks in progress; not all redbooks become redpieces and sometimes just a few chapters willbe published this way. The intent is to get the information out much quicker than the formal publishing processallows.

• E-mail Orders

Send orders by e-mail including information from the redbooks fax order form to:

• Telephone Orders

• Fax Orders

This information was current at the time of publication, but is continually subject to change. The latest informationmay be found at the redbooks Web site.

In United StatesOutside North America

e-mail [email protected] information is in the “How to Order” section at this site:http://www.elink.ibmlink.ibm.com/pbl/pbl/

United States (toll free)Canada (toll free)Outside North America

1-800-879-27551-800-IBM-4YOUCountry coordinator phone number is in the “How to Order” section atthis site:http://www.elink.ibmlink.ibm.com/pbl/pbl/

United States (toll free)CanadaOutside North America

1-800-445-92691-403-267-4455Fax phone number is in the “How to Order” section at this site:http://www.elink.ibmlink.ibm.com/pbl/pbl/

IBM employees may register for information on workshops, residencies, and redbooks by accessing the IBMIntranet Web site at http://w3.itso.ibm.com/ and clicking the ITSO Mailing List button. Look in the Materialsrepository for workshops, presentations, papers, and Web pages developed and written by the ITSO technicalprofessionals; click the Additional Materials button. Employees may access MyNews at http://w3.ibm.com/ forredbook, residency, and workshop announcements.

IBM Intranet for Employees

© Copyright IBM Corp. 1999 229

Page 246: Store Procedure

IBM Redbook Fax Order FormPlease send me the following:

We accept American Express, Diners, Eurocard, Master Card, and Visa. Payment by credit card notavailable in all countries. Signature mandatory for credit card payment.

Title Order Number Quantity

First name Last name

Company

Address

City Postal code

Telephone number Telefax number VAT number

Invoice to customer number

Country

Credit card number

Credit card expiration date SignatureCard issued to

230 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 247: Store Procedure

List of abbreviations

ACEE access control environmentelement

ADK application developmenttoolkit

ADO ActiveX Data Objects

ANN artificial neural network

ANSI American National StandardsInstitute

APAR authorized program analysisreport

APPC advanced program to programcommunication

API application programminginterface

AR application requester

ARM automatic restart manager

ASCII American National StandardCode for InformationInterchange

BV Business View

CAE client application enabler

CAF call attachment facility

CBIPO custom-build installationprocess offering

CBPDO custom-build product deliveryoffering

CCSID coded character set identifier

CFRM coupling facility resourcemanagement

CLIST command list

DAM data access module

DARM data archive retrievalmanager

DASD direct access storage device

DBMS database managementsystem

DBRM database request module

DB2PM DB2 performance monitor

DCE Distributed ComputingEnvironment

DCL data control language

DDF distributed data facility

DDL data definition language

DES Data Encryption Standard

© Copyright IBM Corp. 1999

DLL dynamic link library

DML data manipulation language

DMS database managedstoragespace

DPropR DataPropagator Relational

DRDA distributed relational databasearchitecture

DUW distributed unit of work

DW data warehouse

DSS decision support system

EIS executive information system

ESO expanded service option

ERP enterprise resource planning

FTP File Transfer Protocol

GBP group buffer pool

GID group ID

GUI graphical user interface

GWAPI Domino Go Web serverapplication programminginterface

HLQ high level qualifier

H-OLAP hybrid OLAP

HTML hypertext markup language

IBM International BusinessMachines Corporation

ICAPI internet connectionapplication programminginterface

ICF integrated coupling facility

IDS intelligent decision support

IFI instrumentation facilityinterface

IRLM internal resource lockmanager

ISO International Organization forStandardization

I/O input/output

IM Intelligent Miner

IMS Information ManagementSystem

IT information technology

ITSO International TechnicalSupport Organization

231

Page 248: Store Procedure

JCL job control language

JDBC Java Database Connectivity

JDK Java Developers Kit

JIT just in time compiler

JRE java runtime environment

JVM Java Virtual Machine

LE Language Environment

LIS large item set

LOB large object

LPP licensed program product

LRO linked reporting object

LRU last recently used

MDIS Metadata InterchangeSpecification

MLP multilayer perceptron

M-OLAP multidimensional OLAP

MPP massive parallel processing

NCF IBM Network ComputingFramework

ODBA IMS open database access

ODBC open database connectivity

OEM original equipmentmanufacturer

OLAP online analytical processing

OLE object linking and embedding

OLTP online transaction processing

OMG Object Management Group

OSA open systems adapter

PSM persistent stored module

PSP preventive service planning

RACF OS/VS2 MVS ResourceAccess Control Facility

RAM random access memory

RBA relative byte address

RBF radial basis function

RBFN radial basis function network

RDBMS relational databasemanagement system

ROI return on investment

R-OLAP relational OLAP

RDS relational data system

RRS recoverable resourcemanager services

RRSAF recoverable resourcemanager services attachmentfacility

RUW remote unit of work

SCA shared communication area

SDSF system display and searchfacility

SEU source entry utility

SMP symmetrical multiprocessor

SMP/E system modificationprogram/enhanced

SMS storage management system

SNA systems network architecture

SQL Structured query language

SQLDA SQL descriptor area

SWA scheduler work area

TCP/IP Transmission ControlProtocol/Internet Protocol

UDA user defined attribute

UDB Universal Database

UDF user defined function

UDT user-defined type

URL Universal Resource Locator

VSAM Virtual Storage AccessMethod

VWP Visual Warehouse Program

XES MVS Cross-system extendedservices

XMI XML Metadata Interchange

XML extended markup language

232 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 249: Store Procedure

Index

Numerics5250 emulation 1715250 tools 170

AADO 169ALLOCATE statement 28, 30

definition 31sample 32

ALTER 3Ambiguous names 38Assignment statement 18

definition 20sample 20SET 18

ASSOCIATE statement 28, 30definition 31sample 31

ATOMIC compound statement 27Nested 37sample 27

Authorization behavior 37OS/390 120

BBASIC 16Bind

dynamic invocation 110, 111bind option

PATH 3Build 76

CC 3, 7, 10, 11, 14, 15, 16, 17, 31, 42, 43

comment 38C++ 3, 7, 16, 18CALL statement 1, 17, 28, 30

definition 31sample 31

CASE statement 18definition 21sample 21

character variablelength 38

CLI 3, 4, 7, 11, 30, 37, 42CLOSE 28, 30COBOL 3, 6, 7, 10, 14, 15, 16, 17, 31, 43COMMENT ON 28COMMIT 37Compound statement 18

ATOMICdefinition 27sample 27

BEGIN 18definition 27

© Copyright IBM Corp. 1999

END 18NOT ATOMIC

definition 27sample 27

order of statements 27condition handler 27, 33, 36

CONTINUEdefinition 34

EXITdefinition 34

RESIGNAL statement 26SIGNAL statement 25specification 18UNDO

definition 34CONNECT 37CREATE 3, 28Create 75CREATE MODULE 9CREATE PROCEDURE 5, 38, 116, 117, 119, 127, 138

AS/400 169, 170, 171, 177, 180CURRENT PATH 3

DDatabase Connection 77DataJunction 40, 41DATE arithmetic 38DB2 Connect 60, 61DB2 SDK 61, 64, 65, 81, 105DB2CLI.PROCEDURES 3DB2DARI 5DB2SPB.INI file 66DBRM 119, 122, 127, 128, 130, 131, 138DECIMAL data types 38DECLARE CURSOR 28DECLARE GLOBAL TEMPORARY TABLE 28DECLARE PROCEDURE 5DECLARE RESULT SET LOCATOR 30DELETE 28Dirty Procedures 77DRDA 2, 3, 60DROP 3, 28DROP PROCEDURE

AS/400 180, 181DSNDPSM 112DSNHSQL 110, 118, 136, 137, 140, 143DSNPSMX1 112DSNPSMX2 112DSNPXMOX1 112DSNSPSM 112DSNTIJSG 113DSNTIJSQ 110, 111, 112, 113DSNTPSMP

BUILD 129DESTROY 130input parameters 126PL/1 client program 131

233

Page 250: Store Procedure

sample 131REBIND 131REBUILD 131REXX 110, 120

DSNWLMP 110DSNWSPM 124, 125dynamic calls 37Dynamic SQL

definition 25EXECUTE 25EXECUTE IMMEDIATE 25PREPARE 25sample 25

Eerror code

-060 39-061 39-775 39-776 39-777 39-778 39-779 39-780 39-781 39-782 39-783 39-785 39

error messages 39EXECUTE 25, 28EXECUTE IMMEDIATE 25, 28external stored procedure 7, 10, 11, 14, 16, 17, 42

FFETCH 28, 30Filter 82, 84FOR statement 18, 37

definition 23sample 23

Fortran 3, 7, 16

GGenerate 75Get Source 76GOTO 38GRANT 3, 28, 37

HHandling errors

definition 33NOT FOUND 33sample 35SQLEXCEPTION 33SQLSTATE 33SQLWARNING 33WHENEVER statement 33

Handling result sets 29DECLARE CURSOR 29

sample 29WITH RETURN TO CALLER clause 29WITH RETURN TO CLIENT clause 29

host variables 19

IIBM DataJoiner 41IBM VisualAge for Java 62IF statement 18

definition 21sample 21, 22

IMSDBCTL 3Open Database Access 3

InfoModelers InfoModeler 40Informix 40, 41, 43, 55INSERT 28INVSDK2LMS 186, 187ISO/ANSI 1, 9, 10ITERATE statement 18, 24, 38

definition 22sample 22

JJava 7, 10, 16, 31, 37, 42, 43

stored procedure 17JDBC 4, 7, 37, 169, 174, 188, 190

KKEEPDARI 61

LLABEL ON 28LEAVE statement 18

definition 22sample 22

LOCK TABLE 28LOOP statement 18

definition 24sample 24

MMicrosoft 6Microsoft SQL Server 40, 43, 45Microsoft Visual Basic 62, 65Microsoft Visual Studio 62, 64Migrating

business logic 41control statements 43database data 41database structure 40tools 40, 41

Module 9module 2, 7, 10, 18, 36, 49multi-rowed result sets 37

234 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 251: Store Procedure

NNested

ATOMIC compound statement 37NOT ATOMIC compound statement 37stored procedure 37

New line markers 38NOT ATOMIC compound statement 27

Nested 37sample 27

OODBC 3, 4, 37, 42, 169, 174OPEN 28Operations Navigator 6Oracle 6, 9, 40, 41, 42, 48, 49, 50

FORMS 41OS/390 Procedures Processor 112OS/390 SQL Procedure Processor 109

Pparameter names

length 38PASCAL 16PATH 3Persistent Stored Module 6, 9PL/SQL 6, 9, 15, 40, 42, 48Platinum ERwin ERX 40PowerBuilder 41PREPARE 25PREPARE FROM 28Processing result sets 32

sample 32Project 75

sharing SPB projects 82

QQSQLSRC 171

Rreadme file 110Register 76RELEASE 29RELEASE SAVEPOINT 29RENAME 29REPEAT statement 18

definition 24sample 24

RESIGNAL statement 19, 37definition 26sample 26

result sets 2, 37Retrieving result sets 30

sample 30REVOKE 3, 29, 37REXX 3, 7, 16

DSNTPSMP 110, 120language support 110, 111

stored procedure 116stored procedure support 110, 111

REXX stored procedure 5ROLLBACK 29, 37ROLLBACK TO SAVEPOINT 29RPG 6Run 76RUNSQLSTM 6, 170, 171, 172, 174, 182, 183

SSAVEPOINT 29Savepoint 36SDK2LMS 171, 173, 175, 178, 179, 180, 183, 186, 188SELECT INTO 29SET statement 38SIGNAL statement 19, 37

definition 25sample 26

Single statement procedure 38SmartGuide 78, 79, 85, 86sored procedure

processing return sets 37SPB

concepts and terminologyBuild 76Create 75Database Connection 77Dirty Procedures 77Generate 75Get Source 76Modify 76Project 75Register 76Run 76

configuring your environment 65CREATE PROCEDURE 83, 88, 92DB2 parameter

KEEPDARI 61DB2SPB.INI file 66

entries 72sample 66

DRDA 60DSNTPSMP 93, 94, 102IBM VisualAge for Java 62JDBC stored procedure

sample 59managing projects 82Microsoft Visual Basic 65Microsoft Visual Studio 64pre-requisites 60programming languages supported 58sharing projects 82SQL Costing Information 111SQL stored procedure

sample 58SQLJ stored procedure

sample 59supported tasks 7tasks

actual costs 90

235

Page 252: Store Procedure

building stored procedures 101copying and pasting stored procedures 104creating new stored procedures 85debugging stored procedures 105modifying existing stored procedures 102viewing existing stored procedures 83

SQL Assistant 74, 76, 78, 79, 86, 94, 96, 97, 99, 100,101SQL Conversion Workbench 42SQL Convertion Workbench 41SQL Costing Information 111, 124SQL function 7SQL local variables

declaration 19sample 19

SQL ProceduresOS/390

Declared Temporary Table 111External Savepoint 111Identity Columns 111

portability across DB2 platforms 36restrictions 36SPB 38statements supported 18stored procedure builder 17, 18

SQL Script 176, 177, 179, 180, 181SQL script 170, 178SQL stored procedure 7

AS/400Operations Navigator GUI 170Operations Navigator SQL 170Traditional 5250 170

creating result sets 29declaring SQL local variables 19handling errors 33migrating from OEM DBMSs 42OS/390

Method 1 109Method 2 109Method 3 109SPB 109

processing result sets 32retrieving result sets 30source code size limit 36

SQL Windows 41SQL/PSM 1, 9, 14, 19, 36, 44, 49, 55

7SQL_API_FN 5SQL3 7, 9, 10SQLCODE 37SQLDA 3, 5SQLJ 4, 7SQLPROCS 171SQLSTATE 26, 33, 37, 39, 40, 49SQLVARs 3, 4, 5Static DDL 38stored procedure

address spaces 2evolution

DB2 for Distributed Platforms 3

DB2 for OS/390 2DB2 UDB for AS/400 5

parameterIN 5INOUT 5OUT 5

parameter styleDB2DARI 4DB2GENERAL 4DB2SQL 4GENERAL 4GENERAL WITH NULLS 4JAVA 4

returning result sets 37stored procedure monitor program 124STRSEU 171Sybase 9, 40, 41, 43, 45

APIs 42SYSCAT.PROCEDURES 4, 5SYSFUNCS 174SYSIBM.SYSPARMS 119, 129, 130, 137, 138SYSIBM.SYSPROCEDURES 116, 117, 119, 120, 129,130, 137, 138, 145, 160, 167SYSIBM.SYSPROCOPTIONS 145SYSIBM.SYSPROCPARMS 145, 160SYSIBM.SYSPROCPARMSOPTIONS 145SYSIBM.SYSPSM 112, 113SYSIBM.SYSPSMOPTS 112, 113, 119, 120, 129, 130,142SYSIBM.SYSPSMOUT 112, 114SYSIBM.SYSROUTINES 119, 129, 130, 137, 138SYSPARMS 170, 174, 181SYSPROCS 170, 174SYSROUTINES 170, 174, 181

TT/SQL 6, 9, 15, 40, 42, 43, 48TCP/IP 2

UUPDATE 29

VVALUES INTO 29variables

declaration order 19Visual Basic 15VisualAge for Java 62VisualAge Remote Debugger 79

WWHILE statement 18

definition 24sample 24

WLMDDNAMES 127stored procedure address space 2

236 Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure Builder

Page 253: Store Procedure

© Copyright IBM Corp. 1999 237

ITSO redbook evaluation

Developing Cross-Platform DB2 Stored Procedures: SQL Procedures and the DB2 Stored Procedure BuilderSG24-5485-00

Your feedback is very important to help us maintain the quality of ITSO redbooks. Please complete thisquestionnaire and return it using one of the following methods:

• Use the online evaluation form found at http://www.redbooks.ibm.com/• Fax this form to: USA International Access Code + 1 914 432 8264• Send your comments in an Internet note to [email protected]

Which of the following best describes you?_ Customer _ Business Partner _ Solution Developer _ IBM employee_ None of the above

Please rate your overall satisfaction with this book using the scale:(1 = very good, 2 = good, 3 = average, 4 = poor, 5 = very poor)

Overall Satisfaction __________

Please answer the following questions:

Was this redbook published in time for your needs? Yes___ No___

If no, please explain:

What other redbooks would you like to see published?

Comments/Suggestions: (THANK YOU FOR YOUR FEEDBACK!)

Page 254: Store Procedure

SG24-5485-00

Printed in the U.S.A.

Developing

Cross-P

latformD

B2

StoredP

rocedures:SQL

Proceduresand

theD

B2

StoredP

rocedureB

uilderSG

24-5485-00