0% found this document useful (0 votes)
449 views1,157 pages

DB2 V9 Application Programming&SQL Guide Dsnapk13

This edition applies to DB2 Version 9. For z / OS, product number 5635-DB2. Specific changes are indicated by a vertical bar to the left of a change. Editorial changes that have no technical significance are not noted.

Uploaded by

Sergio Molina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
449 views1,157 pages

DB2 V9 Application Programming&SQL Guide Dsnapk13

This edition applies to DB2 Version 9. For z / OS, product number 5635-DB2. Specific changes are indicated by a vertical bar to the left of a change. Editorial changes that have no technical significance are not noted.

Uploaded by

Sergio Molina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DB2 Version 9.

1 for z/OS
Application Programming and SQL Guide
SC18-9841-03

DB2 Version 9.1 for z/OS


Application Programming and SQL Guide
SC18-9841-03

Note
Before using this information and the product it supports, be sure to read the general information under Notices at the
end of this information.
Fourth edition (December 2008)
This edition applies to DB2 Version 9.1 for z/OS (DB2 V9.1 for z/OS), product number 5635-DB2, and to any
subsequent releases until otherwise indicated in new editions. Make sure you are using the correct edition for the
level of the product.
Specific changes are indicated by a vertical bar to the left of a change. A vertical bar to the left of a figure caption
indicates that the figure has changed. Editorial changes that have no technical significance are not noted.
Copyright International Business Machines Corporation 1983, 2008.
US Government Users Restricted Rights Use, duplication or disclosure restricted by GSA ADP Schedule Contract
with IBM Corp.
Contents
About this information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Who should read this information . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
DB2 Utilities Suite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Terminology and citations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Accessibility features for DB2 Version 9.1 for z/OS . . . . . . . . . . . . . . . . . . . . . . xiv
How to send your comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
How to read syntax diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Chapter 1. Planning for and designing DB2 applications . . . . . . . . . . . . . . . 1
Application and SQL release incompatibilities . . . . . . . . . . . . . . . . . . . . . . . . 1
Determining the value of any SQL processing options that affect the design of your program . . . . . . . . 13
Determining the binding method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Changes that invalidate plans or packages . . . . . . . . . . . . . . . . . . . . . . . . 16
Determining the value of any bind options that affect the design of your program . . . . . . . . . . . 18
Designing your application to promote concurrency . . . . . . . . . . . . . . . . . . . . . . 18
Designing your application for recovery . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Unit of work in TSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Unit of work in CICS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Planning for program recovery in IMS programs . . . . . . . . . . . . . . . . . . . . . . 21
Undoing selected changes within a unit of work by using savepoints . . . . . . . . . . . . . . . 28
Planning for recovery of table spaces that are not logged . . . . . . . . . . . . . . . . . . . 30
Designing your application to access distributed data . . . . . . . . . . . . . . . . . . . . . 31
Remote servers and distributed data . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Advantages of DRDA access. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Preparing for coordinated updates to two or more data sources . . . . . . . . . . . . . . . . . 33
Forcing restricted system rules in your program . . . . . . . . . . . . . . . . . . . . . . 34
Maximizing the performance of an application that accesses distributed data . . . . . . . . . . . . 34
Chapter 2. Connecting to DB2 from your application program . . . . . . . . . . . . 45
Invoking the call attachment facility . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Call attachment facility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Making the CAF language interface (DSNALI) available . . . . . . . . . . . . . . . . . . . 52
Requirements for programs that use CAF . . . . . . . . . . . . . . . . . . . . . . . . 53
How CAF modifies the content of registers . . . . . . . . . . . . . . . . . . . . . . . . 54
Implicit connections to CAF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
CALL DSNALI statement parameter list . . . . . . . . . . . . . . . . . . . . . . . . . 55
Summary of CAF behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
CAF connection functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Turning on a CAF trace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
CAF return codes and reason codes . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Sample CAF scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Examples of invoking CAF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Invoking the Resource Recovery Services attachment facility . . . . . . . . . . . . . . . . . . . 77
Resource Recovery Services attachment facility . . . . . . . . . . . . . . . . . . . . . . 79
Making the RRSAF language interface (DSNRLI) available . . . . . . . . . . . . . . . . . . 83
Requirements for programs that use RRSAF . . . . . . . . . . . . . . . . . . . . . . . 84
How RRSAF modifies the content of registers . . . . . . . . . . . . . . . . . . . . . . . 85
Implicit connections to RRSAF . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
CALL DSNRLI statement parameter list . . . . . . . . . . . . . . . . . . . . . . . . . 86
Summary of RRSAF behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
RRSAF connection functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
RRSAF return codes and reason codes . . . . . . . . . . . . . . . . . . . . . . . . . 118
Sample RRSAF scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Program examples for RRSAF . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Controlling the CICS attachment facility from an application . . . . . . . . . . . . . . . . . . 123
Copyright IBM Corp. 1983, 2008 iii
||
||
Detecting whether the CICS attachment facility is operational . . . . . . . . . . . . . . . . . 124
Improving thread reuse in CICS applications . . . . . . . . . . . . . . . . . . . . . . . 124
Chapter 3. Including DB2 queries in an application program . . . . . . . . . . . . 127
Declaring table and view definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . 128
DCLGEN (declarations generator) . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Generating table and view declarations by using DCLGEN . . . . . . . . . . . . . . . . . . 129
Including declarations from DCLGEN in your program . . . . . . . . . . . . . . . . . . . 136
Example: Adding DCLGEN declarations to a library . . . . . . . . . . . . . . . . . . . . 137
Defining the items that your program can use to check whether an SQL statement executed successfully. . . . 140
Defining the SQL communications area. . . . . . . . . . . . . . . . . . . . . . . . . 140
Declaring SQLCODE and SQLSTATE host variables . . . . . . . . . . . . . . . . . . . . 141
Defining SQL descriptor areas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Declaring host variables, host variable arrays, and host structures . . . . . . . . . . . . . . . . . 144
Host variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Host variable arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Host structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Defining indicator variables, arrays, and structures . . . . . . . . . . . . . . . . . . . . . 203
Declaring pointer host variables in C and C++ programs . . . . . . . . . . . . . . . . . . . 210
Setting the CCSID for host variables. . . . . . . . . . . . . . . . . . . . . . . . . . 212
Determining what caused an error when retrieving data into a host variable . . . . . . . . . . . . 214
Compatibility of SQL and language data types . . . . . . . . . . . . . . . . . . . . . . . 216
Equivalent SQL and assembler data types . . . . . . . . . . . . . . . . . . . . . . . . 218
Equivalent SQL and C data types. . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Equivalent SQL and COBOL data types . . . . . . . . . . . . . . . . . . . . . . . . 228
Equivalent SQL and Fortran data types. . . . . . . . . . . . . . . . . . . . . . . . . 232
Equivalent SQL and PL/I data types . . . . . . . . . . . . . . . . . . . . . . . . . 234
Determining equivalent SQL and REXX data types . . . . . . . . . . . . . . . . . . . . . 238
Data types that DB2 assigns to REXX input . . . . . . . . . . . . . . . . . . . . . . . 238
Embedding SQL statements in your application . . . . . . . . . . . . . . . . . . . . . . . 240
Embedding SQL statements in assembler applications . . . . . . . . . . . . . . . . . . . . 240
Embedding SQL statements in C or C++ applications . . . . . . . . . . . . . . . . . . . . 243
Embedding SQL statements in COBOL applications . . . . . . . . . . . . . . . . . . . . 245
Embedding SQL statements in Fortran applications. . . . . . . . . . . . . . . . . . . . . 249
Embedding SQL statements in PL/I applications . . . . . . . . . . . . . . . . . . . . . 250
Embedding SQL statements in REXX procedures . . . . . . . . . . . . . . . . . . . . . 253
Delimiting an SQL statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Rules for host variables in an SQL statement . . . . . . . . . . . . . . . . . . . . . . . 255
Referencing pointer host variables in C and C++ programs . . . . . . . . . . . . . . . . . . 256
Retrieving a single row of data into host variables . . . . . . . . . . . . . . . . . . . . . 257
Determining whether a retrieved value in a host variable is null or truncated . . . . . . . . . . . . 259
Determining whether a column value is null . . . . . . . . . . . . . . . . . . . . . . . 261
Updating data by using host variables . . . . . . . . . . . . . . . . . . . . . . . . . 262
Inserting a single row by using use host variables . . . . . . . . . . . . . . . . . . . . . 263
Inserting null values into columns by using indicator variables or arrays . . . . . . . . . . . . . 263
Host variable arrays in an SQL statement . . . . . . . . . . . . . . . . . . . . . . . . 264
Retrieving multiple rows of data into host variable arrays . . . . . . . . . . . . . . . . . . 265
Inserting multiple rows of data from host variable arrays. . . . . . . . . . . . . . . . . . . 265
Retrieving a single row of data into a host structure . . . . . . . . . . . . . . . . . . . . 266
Including dynamic SQL in your program . . . . . . . . . . . . . . . . . . . . . . . . 266
Conventions used in examples of coding SQL statements. . . . . . . . . . . . . . . . . . . 305
Macros for assembler applications . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Accessing the DB2 REXX language support application programming interfaces . . . . . . . . . . . 305
Ensuring that DB2 correctly interprets character input data in REXX programs . . . . . . . . . . . 306
Passing the data type of an input data type to DB2 for REXX programs . . . . . . . . . . . . . . 307
Setting the isolation level of SQL statements in a REXX procedure. . . . . . . . . . . . . . . . 308
Checking the execution of SQL statements. . . . . . . . . . . . . . . . . . . . . . . . . 308
Checking the execution of SQL statements by using the SQLCA . . . . . . . . . . . . . . . . 309
Checking the execution of SQL statements by using SQLCODE and SQLSTATE . . . . . . . . . . . 313
Checking the execution of SQL statements by using the WHENEVER statement . . . . . . . . . . . 313
Checking the execution of SQL statements by using the GET DIAGNOSTICS statement . . . . . . . . 314
iv Application Programming and SQL Guide
Handling SQL error codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Arithmetic and conversion errors . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
Writing applications that enable users to create and modify tables. . . . . . . . . . . . . . . . . 327
Saving SQL statements that are translated from end user requests . . . . . . . . . . . . . . . . . 328
Retrieving data from DB2 tables in REXX programs . . . . . . . . . . . . . . . . . . . . . 328
XML data in embedded SQL applications . . . . . . . . . . . . . . . . . . . . . . . . . 329
Host variable data types for XML data in embedded SQL applications . . . . . . . . . . . . . . 330
XML column updates in embedded SQL applications . . . . . . . . . . . . . . . . . . . . 334
XML data retrieval in embedded SQL applications . . . . . . . . . . . . . . . . . . . . . 337
Object-oriented extensions in COBOL . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Cursors and statement names in REXX . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Programming examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
Sample dynamic and static SQL in a C program. . . . . . . . . . . . . . . . . . . . . . 341
Sample COBOL dynamic SQL program. . . . . . . . . . . . . . . . . . . . . . . . . 344
Sample COBOL program using DRDA access with CONNECT statements . . . . . . . . . . . . . 355
Sample COBOL program using private protocol access . . . . . . . . . . . . . . . . . . . 361
Sample DB2 REXX application. . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Example programs that call stored procedures . . . . . . . . . . . . . . . . . . . . . . 377
Chapter 4. Creating and modifying DB2 objects . . . . . . . . . . . . . . . . . 395
Creating tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
Storing LOB data in a table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Identity columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
Creating tables for data integrity . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
Creating work tables for the EMP and DEPT sample tables . . . . . . . . . . . . . . . . . . 412
Creating created temporary tables . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Creating declared temporary tables . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Providing a unique key for a table . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
Fixing tables with incomplete definitions . . . . . . . . . . . . . . . . . . . . . . . . . 418
Dropping tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
Defining a view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Dropping a view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Creating a common table expression. . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Common table expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
Examples of recursive common table expressions . . . . . . . . . . . . . . . . . . . . . 423
Creating triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
Invoking stored procedures and user-defined functions from triggers. . . . . . . . . . . . . . . 435
Inserting, updating, and deleting data in views by using INSTEAD OF triggers . . . . . . . . . . . 436
Trigger packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
Trigger cascading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
Order of multiple triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
Interactions between triggers and referential constraints . . . . . . . . . . . . . . . . . . . 439
Interactions between triggers and tables that have multilevel security with row-level granularity . . . . . 441
Triggers that return inconsistent results. . . . . . . . . . . . . . . . . . . . . . . . . 441
Sequence objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
DB2 object relational extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
Creating a distinct type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Distinct types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Example of distinct types, user-defined functions, and LOBs . . . . . . . . . . . . . . . . . 448
Defining a user-defined function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
User-defined functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
Components of a user-defined function definition . . . . . . . . . . . . . . . . . . . . . 455
Writing an external user-defined function . . . . . . . . . . . . . . . . . . . . . . . . 457
Making a user-defined function reentrant . . . . . . . . . . . . . . . . . . . . . . . . 480
Using special registers in a user-defined function or a stored procedure . . . . . . . . . . . . . . 481
Accessing transition tables in a user-defined function or stored procedure . . . . . . . . . . . . . 483
Preparing an external user-defined function for execution . . . . . . . . . . . . . . . . . . 487
Abnormal termination of an external user-defined function . . . . . . . . . . . . . . . . . . 487
Saving information between invocations of a user-defined function by using a scratchpad. . . . . . . . 487
Contents v
||
||
Example of creating and using a user-defined scalar function . . . . . . . . . . . . . . . . . 489
User-defined function samples that ship with DB2 . . . . . . . . . . . . . . . . . . . . . 489
Determining the authorization cache size for stored procedures and user-defined functions . . . . . . . 490
Creating a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
Stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
Setting up the stored procedures environment . . . . . . . . . . . . . . . . . . . . . . 504
Creating a native SQL procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
Changing an existing version of a native SQL procedure . . . . . . . . . . . . . . . . . . . 536
Regenerating an existing version of a native SQL procedure . . . . . . . . . . . . . . . . . . 536
Removing an existing version of a native SQL procedure . . . . . . . . . . . . . . . . . . . 537
Deploying a native SQL procedure to other DB2 for z/OS servers . . . . . . . . . . . . . . . . 537
Creating an external SQL procedure . . . . . . . . . . . . . . . . . . . . . . . . . . 538
Creating an external stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . 551
Creating multiple versions of external procedures and external SQL procedures . . . . . . . . . . . 563
COMMIT and ROLLBACK statements in a stored procedure . . . . . . . . . . . . . . . . . 563
Special registers in a stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . 564
Restrictions for stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . 564
Writing a program or stored procedure to receive the result sets from a stored procedure . . . . . . . . 564
Chapter 5. Adding and modifying data . . . . . . . . . . . . . . . . . . . . . 571
Inserting data into tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
Inserting rows by using the INSERT statement . . . . . . . . . . . . . . . . . . . . . . 571
Inserting data and updating data in a single operation . . . . . . . . . . . . . . . . . . . 577
Selecting values while inserting data . . . . . . . . . . . . . . . . . . . . . . . . . 579
Adding data to the end of a table . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
Storing data that does not have a tabular format . . . . . . . . . . . . . . . . . . . . . . 586
Updating table data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
Selecting values while updating data . . . . . . . . . . . . . . . . . . . . . . . . . 587
Updating thousands of rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
Deleting data from tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
Selecting values while deleting data . . . . . . . . . . . . . . . . . . . . . . . . . . 590
Chapter 6. Accessing data . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
Determining which tables you have access to. . . . . . . . . . . . . . . . . . . . . . . . 593
Displaying information about the columns for a given table . . . . . . . . . . . . . . . . . . . 593
Retrieving data by using the SELECT statement . . . . . . . . . . . . . . . . . . . . . . . 594
Selecting derived columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
Selecting XML data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
Formatting the result table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
Combining result tables from multiple SELECT statements . . . . . . . . . . . . . . . . . . 603
Summarizing group values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
Finding rows that were changed within a specified period of time . . . . . . . . . . . . . . . 610
Joining data from more than one table . . . . . . . . . . . . . . . . . . . . . . . . . 610
Optimizing retrieval for a small set of rows . . . . . . . . . . . . . . . . . . . . . . . 621
Creating recursive SQL by using common table expressions . . . . . . . . . . . . . . . . . . 622
Updating data as it is retrieved from the database . . . . . . . . . . . . . . . . . . . . . 623
Avoiding decimal arithmetic errors . . . . . . . . . . . . . . . . . . . . . . . . . . 623
Implications of using SELECT * . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Restrictions when using distinct types with UNION, EXCEPT, and INTERSECT . . . . . . . . . . . 633
Comparison of distinct types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
Nested SQL statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
Retrieving a set of rows by using a cursor . . . . . . . . . . . . . . . . . . . . . . . . . 636
Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
Accessing data by using a row-positioned cursor . . . . . . . . . . . . . . . . . . . . . 641
Accessing data by using a rowset-positioned cursor . . . . . . . . . . . . . . . . . . . . 646
Retrieving rows by using a scrollable cursor . . . . . . . . . . . . . . . . . . . . . . . 651
Accessing XML or LOB data quickly by using FETCH WITH CONTINUE . . . . . . . . . . . . . 656
Determining the attributes of a cursor by using the SQLCA . . . . . . . . . . . . . . . . . . 659
Determining the attributes of a cursor by using the GET DIAGNOSTICS statement . . . . . . . . . . 660
vi Application Programming and SQL Guide
||
||
||
||
||
||
||
||
||
Scrolling through previously retrieved data . . . . . . . . . . . . . . . . . . . . . . . 660
Updating previously retrieved data . . . . . . . . . . . . . . . . . . . . . . . . . . 662
FETCH statement interaction between row and rowset positioning . . . . . . . . . . . . . . . 662
Examples of fetching rows by using cursors . . . . . . . . . . . . . . . . . . . . . . . 663
Specifying direct row access by using row IDs . . . . . . . . . . . . . . . . . . . . . . . 668
ROWID columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
Ways to manipulate LOB data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
LOB host variable, LOB locator, and LOB file reference variable declarations . . . . . . . . . . . . 671
LOB materialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
Saving storage when manipulating LOBs by using LOB locators . . . . . . . . . . . . . . . . 677
Deferring evaluation of a LOB expression to improve performance . . . . . . . . . . . . . . . 679
LOB file reference variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
Referencing a sequence object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
Retrieving thousands of rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
Determining when a row was changed . . . . . . . . . . . . . . . . . . . . . . . . . . 684
Checking whether an XML column contains a certain value . . . . . . . . . . . . . . . . . . . 685
Accessing DB2 data that is not in a table . . . . . . . . . . . . . . . . . . . . . . . . . 685
Ensuring that queries perform sufficiently . . . . . . . . . . . . . . . . . . . . . . . . . 685
Items to include in a batch DL/I program. . . . . . . . . . . . . . . . . . . . . . . . . 686
Chapter 7. Invoking a user-defined function . . . . . . . . . . . . . . . . . . . 689
Determining the authorization ID for invoking user-defined functions . . . . . . . . . . . . . . . 690
Ensuring that DB2 executes the intended user-defined function. . . . . . . . . . . . . . . . . . 691
Function resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
Checking how DB2 resolves functions by using DSN_FUNCTION_TABLE . . . . . . . . . . . . . 695
Restrictions when passing arguments with distinct types to functions . . . . . . . . . . . . . . . 698
Cases when DB2 casts arguments for a user-defined function . . . . . . . . . . . . . . . . . . 699
Maximizing the number of user-defined functions and stored procedures that can run concurrently . . . . . 701
Chapter 8. Calling a stored procedure from your application . . . . . . . . . . . . 703
Parameter list for stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . 706
Linkage conventions for stored procedures . . . . . . . . . . . . . . . . . . . . . . . . 707
Improving stored procedure performance by using indicator variables . . . . . . . . . . . . . . . 722
Compatible data types for parameters that are passed to stored procedures . . . . . . . . . . . . . 723
Preparing a client program for a stored procedure . . . . . . . . . . . . . . . . . . . . . . 731
How DB2 determines which stored procedure to run . . . . . . . . . . . . . . . . . . . . . 732
Calling different versions of a stored procedure from a single application . . . . . . . . . . . . . . 732
Invoking multiple instances of a stored procedure . . . . . . . . . . . . . . . . . . . . . . 733
Stored procedures that access non-DB2 resources . . . . . . . . . . . . . . . . . . . . . . 734
Designating the active version of a native SQL procedure . . . . . . . . . . . . . . . . . . . 735
Temporarily overriding the active version of a native SQL procedure. . . . . . . . . . . . . . . . 736
Specifying the number of stored procedures that can run concurrently . . . . . . . . . . . . . . . 736
DB2-supplied stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
WLM environment refresh stored procedure (WLM_REFRESH) . . . . . . . . . . . . . . . . 739
DSNACICS stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741
DSNAIMS stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749
The DB2 EXPLAIN stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . 754
Deprecated: Store an XML document from an MQ message queue in DB2 tables (DXXMQINSERT) . . . . 756
Deprecated: Store an XML document from an MQ message queue in DB2 tables (DXXMQSHRED) . . . . . 759
Deprecated: Store a large XML document from an MQ message queue in DB2 tables (DXXMQINSERTCLOB) 761
Deprecated: Store a large XML document from an MQ message queue in DB2 tables (DXXMQSHREDCLOB) 764
Deprecated: Store XML documents from an MQ message queue in DB2 tables (DXXMQINSERTALL) . . . . 766
Deprecated: Store XML documents from an MQ message queue in DB2 tables (DXXMQSHREDALL) . . . . 768
Deprecated: Store large XML documents from an MQ message queue in DB2 tables
(DXXMQSHREDALLCLOB) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771
Deprecated: Store large XML documents from an MQ message queue in DB2 tables
(DXXMQINSERTALLCLOB) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
Deprecated: Send XML documents to an MQ message queue (DXXMQGEN) . . . . . . . . . . . . 776
Deprecated: Send XML documents to an MQ message queue (DXXMQRETRIEVE) . . . . . . . . . . 779
Deprecated: Send large XML documents to an MQ message queue (DXXMQGENCLOB) . . . . . . . . 783
Contents vii
||
||
||
||
Deprecated: Send XML documents to an MQ message queue (DXXMQRETRIEVECLOB) . . . . . . . . 787
The XML schema registration stored procedure (XSR_REGISTER) . . . . . . . . . . . . . . . . 790
The add XML schema document stored procedure (XSR_ADDSCHEMADOC). . . . . . . . . . . . 792
The XML schema registration completion stored procedure (XSR_COMPLETE) . . . . . . . . . . . 793
The XML schema removal stored procedure (XSR_REMOVE) . . . . . . . . . . . . . . . . . 795
The XML decomposition stored procedure (XDBDECOMPXML) . . . . . . . . . . . . . . . . 796
Chapter 9. Coding methods for distributed data . . . . . . . . . . . . . . . . . 799
Accessing distributed data by using three-part table names . . . . . . . . . . . . . . . . . . . 799
Accessing remote declared temporary tables by using three-part table names . . . . . . . . . . . . 801
Accessing distributed data by using explicit CONNECT statements . . . . . . . . . . . . . . . . 801
Specifying a location alias name for multiple sites . . . . . . . . . . . . . . . . . . . . . 802
Releasing connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
Transmitting mixed data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
Identifying the server at run time . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
SQL limitations at dissimilar servers. . . . . . . . . . . . . . . . . . . . . . . . . . . 804
Support for executing long SQL statements in a distributed environment . . . . . . . . . . . . . . 804
Distributed queries against ASCII or Unicode tables . . . . . . . . . . . . . . . . . . . . . 805
Restrictions when using scrollable cursors to access distributed data . . . . . . . . . . . . . . . . 805
Restrictions when using rowset-positioned cursors to access distributed data . . . . . . . . . . . . . 806
WebSphere MQ with DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
WebSphere MQ messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
DB2 MQ functions and DB2 MQ XML stored procedures . . . . . . . . . . . . . . . . . . . 810
Generating XML documents from existing tables and sending them to an MQ message queue . . . . . . 816
Shredding XML documents from an MQ message queue . . . . . . . . . . . . . . . . . . . 816
DB2 MQ tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 816
Converting applications to use the MQI functions . . . . . . . . . . . . . . . . . . . . . 825
Basic messaging with WebSphere MQ . . . . . . . . . . . . . . . . . . . . . . . . . 826
Sending messages with WebSphere MQ . . . . . . . . . . . . . . . . . . . . . . . . 827
Retrieving messages with WebSphere MQ. . . . . . . . . . . . . . . . . . . . . . . . 827
Application to application connectivity with WebSphere MQ . . . . . . . . . . . . . . . . . 829
Asynchronous messaging in DB2 for z/OS . . . . . . . . . . . . . . . . . . . . . . . 832
Chapter 10. DB2 as a Web services consumer and provider . . . . . . . . . . . . 845
The SOAPHTTPV and SOAPHTTPC user-defined functions . . . . . . . . . . . . . . . . . . . 845
The SOAPHTTPNV and SOAPHTTPNC user-defined functions . . . . . . . . . . . . . . . . . 847
SQLSTATEs for DB2 as a Web services consumer . . . . . . . . . . . . . . . . . . . . . . 847
Chapter 11. Preparing an application to run on DB2 for z/OS . . . . . . . . . . . . 851
Setting the DB2I defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853
Processing SQL statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854
Processing SQL statements by using the DB2 precompiler . . . . . . . . . . . . . . . . . . 856
Processing SQL statements by using the DB2 coprocessor. . . . . . . . . . . . . . . . . . . 862
Translating command-level statements in a CICS program . . . . . . . . . . . . . . . . . . 865
Differences between the DB2 precompiler and the DB2 coprocessor . . . . . . . . . . . . . . . 866
Options for SQL statement processing . . . . . . . . . . . . . . . . . . . . . . . . . 867
Program preparation options for remote packages . . . . . . . . . . . . . . . . . . . . . 877
Compiling and link-editing an application. . . . . . . . . . . . . . . . . . . . . . . . . 879
Binding an application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880
Binding a DBRM to a package. . . . . . . . . . . . . . . . . . . . . . . . . . . . 881
Binding an application plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . 886
Bind process for remote access . . . . . . . . . . . . . . . . . . . . . . . . . . . 890
Binding a batch program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894
Converting an existing plan into packages to run remotely . . . . . . . . . . . . . . . . . . 894
Setting the program level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
DYNAMICRULES bind option . . . . . . . . . . . . . . . . . . . . . . . . . . . 896
Determining the authorization cache size for plans . . . . . . . . . . . . . . . . . . . . . 897
Determining the authorization cache size for packages . . . . . . . . . . . . . . . . . . . 898
Dynamic plan selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 898
Rebinding an application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900
viii Application Programming and SQL Guide
||
||
||
||
||
||
Rebinding a package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900
Rebinding a plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901
Rebinding lists of plans and packages . . . . . . . . . . . . . . . . . . . . . . . . . 902
Generating lists of REBIND commands . . . . . . . . . . . . . . . . . . . . . . . . . 902
Automatic rebinding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908
Specifying the rules that apply to SQL behavior at run time . . . . . . . . . . . . . . . . . . . 910
DB2 program preparation overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 911
Input and output data sets for DL/I batch jobs . . . . . . . . . . . . . . . . . . . . . . . 913
DB2-supplied JCL procedures for preparing an application . . . . . . . . . . . . . . . . . . . 916
JCL to include the appropriate interface code when using the DB2-supplied JCL procedures . . . . . . . 916
Tailoring DB2-supplied JCL procedures for preparing CICS programs . . . . . . . . . . . . . . 917
DB2I primary option menu. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918
DB2I panels that are used for program preparation. . . . . . . . . . . . . . . . . . . . . . 919
DB2 Program Preparation panel . . . . . . . . . . . . . . . . . . . . . . . . . . . 921
DB2I Defaults Panel 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925
DB2I Defaults Panel 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
Precompile panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 928
Bind Package panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931
Bind Plan panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 934
Defaults for Bind Package panel and Defaults for Bind Plan panel. . . . . . . . . . . . . . . . 937
System Connection Types panel . . . . . . . . . . . . . . . . . . . . . . . . . . . 942
Panels for entering lists of values. . . . . . . . . . . . . . . . . . . . . . . . . . . 943
Program Preparation: Compile, Link, and Run panel . . . . . . . . . . . . . . . . . . . . 944
DB2I panels that are used to rebind and free plans and packages . . . . . . . . . . . . . . . . . 946
Bind/Rebind/Free Selection panel . . . . . . . . . . . . . . . . . . . . . . . . . . 946
Rebind Package panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 948
Rebind Trigger Package panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949
Rebind Plan panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 951
Free Package panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 953
Free Plan panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954
Chapter 12. Running an application on DB2 for z/OS . . . . . . . . . . . . . . . 955
DSN command processor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955
DB2I Run panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 956
Running a program in TSO foreground. . . . . . . . . . . . . . . . . . . . . . . . . . 957
Running a DB2 REXX application . . . . . . . . . . . . . . . . . . . . . . . . . . . 958
Invoking programs through the Interactive System Productivity Facility. . . . . . . . . . . . . . . 958
ISPF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
Invoking a single SQL program through ISPF and DSN . . . . . . . . . . . . . . . . . . . 960
Invoking multiple SQL programs through ISPF and DSN. . . . . . . . . . . . . . . . . . . 961
Loading and running a batch program . . . . . . . . . . . . . . . . . . . . . . . . . . 962
Authorization for running a batch DL/I program . . . . . . . . . . . . . . . . . . . . . 963
Restarting a batch program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 963
Running stored procedures from the command line processor . . . . . . . . . . . . . . . . . . 966
Command line processor CALL statement . . . . . . . . . . . . . . . . . . . . . . . . 966
Example of running a batch DB2 application in TSO . . . . . . . . . . . . . . . . . . . . . 967
Example of calling applications in a command procedure . . . . . . . . . . . . . . . . . . . 968
Chapter 13. Testing and debugging an application program on DB2 for z/OS . . . . . 971
Designing a test data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 971
Analyzing application data needs . . . . . . . . . . . . . . . . . . . . . . . . . . 971
Authorization for test tables and applications. . . . . . . . . . . . . . . . . . . . . . . 972
Example SQL statements to create a comprehensive test structure . . . . . . . . . . . . . . . . 973
Populating the test tables with data . . . . . . . . . . . . . . . . . . . . . . . . . . . 974
Methods for testing SQL statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 974
Executing SQL by using SPUFI . . . . . . . . . . . . . . . . . . . . . . . . . . . . 975
SPUFI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 978
Content of a SPUFI input data set . . . . . . . . . . . . . . . . . . . . . . . . . . 979
The SPUFI panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 979
Changing SPUFI defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 981
Contents ix
||
||
Setting the SQL terminator character in a SPUFI input data set . . . . . . . . . . . . . . . . . 986
Controlling toleration of warnings in SPUFI . . . . . . . . . . . . . . . . . . . . . . . 987
Output from SPUFI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 987
Testing an external user-defined function . . . . . . . . . . . . . . . . . . . . . . . . . 989
Testing a user-defined function by using the Debug Tool for z/OS . . . . . . . . . . . . . . . 989
Testing a user-defined function by routing the debugging messages to SYSPRINT . . . . . . . . . . 991
Testing a user-defined function by using driver applications. . . . . . . . . . . . . . . . . . 991
Testing a user-defined function by using SQL INSERT statements . . . . . . . . . . . . . . . . 992
Debugging a stored procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 992
Debugging stored procedures with the Debug Tool and IBM VisualAge COBOL . . . . . . . . . . . 993
Debugging a C language stored procedure with the Debug Tool and C/C++ Productivity Tools for z/OS . . 994
Debugging with the Unified Debugger . . . . . . . . . . . . . . . . . . . . . . . . . 994
Debugging stored procedures with the Debug Tool for z/OS . . . . . . . . . . . . . . . . . 995
Recording stored procedure debugging messages in a file . . . . . . . . . . . . . . . . . . 997
Driver applications for debugging procedures . . . . . . . . . . . . . . . . . . . . . . 997
DB2 tables that contain debugging information . . . . . . . . . . . . . . . . . . . . . . 997
Debugging an application program . . . . . . . . . . . . . . . . . . . . . . . . . . . 998
Locating the problem in an application . . . . . . . . . . . . . . . . . . . . . . . . . 998
Techniques for debugging programs in TSO. . . . . . . . . . . . . . . . . . . . . . . 1003
Techniques for debugging programs in IMS . . . . . . . . . . . . . . . . . . . . . . . 1003
Techniques for debugging programs in CICS . . . . . . . . . . . . . . . . . . . . . . 1004
Finding a violated referential or check constraint . . . . . . . . . . . . . . . . . . . . . . 1008
Chapter 14. DB2 sample applications and data . . . . . . . . . . . . . . . . . 1009
DB2 sample tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1009
Activity table (DSN8910.ACT) . . . . . . . . . . . . . . . . . . . . . . . . . . . 1009
Department table (DSN8910.DEPT) . . . . . . . . . . . . . . . . . . . . . . . . . . 1010
Employee table (DSN8910.EMP) . . . . . . . . . . . . . . . . . . . . . . . . . . . 1011
Employee photo and resume table (DSN8910.EMP_PHOTO_RESUME) . . . . . . . . . . . . . . 1015
Project table (DSN8910.PROJ) . . . . . . . . . . . . . . . . . . . . . . . . . . . 1016
Project activity table (DSN8910.PROJACT) . . . . . . . . . . . . . . . . . . . . . . . 1017
Employee to project activity table (DSN8910.EMPPROJACT) . . . . . . . . . . . . . . . . . 1018
Unicode sample table (DSN8910.DEMO_UNICODE) . . . . . . . . . . . . . . . . . . . . 1019
Relationships among the sample tables . . . . . . . . . . . . . . . . . . . . . . . . 1020
Views on the sample tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1021
Storage of sample application tables . . . . . . . . . . . . . . . . . . . . . . . . . 1025
DB2 sample applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1029
Types of sample applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1031
Application languages and environments for the sample applications . . . . . . . . . . . . . . 1033
Sample applications in TSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1034
Sample applications in IMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1036
Sample applications in CICS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1037
DSNTIAUL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1037
DSNTIAD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1042
DSNTEP2 and DSNTEP4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1044
Information resources for DB2 for z/OS and related products . . . . . . . . . . . 1049
How to obtain DB2 information . . . . . . . . . . . . . . . . . . . . . . . . 1055
How to use the DB2 library . . . . . . . . . . . . . . . . . . . . . . . . . . 1059
Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1063
Programming Interface Information . . . . . . . . . . . . . . . . . . . . . . . . . . 1064
General-use Programming Interface and Associated Guidance Information . . . . . . . . . . . . 1064
Product-sensitive Programming Interface and Associated Guidance Information. . . . . . . . . . . 1065
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1065
Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1067
x Application Programming and SQL Guide
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1111
Contents xi
xii Application Programming and SQL Guide
About this information
This information discusses how to design and write application programs that
access DB2

for z/OS

(DB2), a highly flexible relational database management


system (DBMS).
Visit the following Web site for information about ordering DB2 books and
obtaining other valuable information about DB2 for z/OS: http://
publib.boulder.ibm.com/infocenter/imzic
This information assumes that your DB2 subsystem is running in Version 9.1
new-function mode. Generally, new functions that are described, including changes
to existing functions, statements, and limits, are available only in new-function
mode. Two exceptions to this general statement are new and changed utilities and
optimization enhancements, which are also available in conversion mode unless
stated otherwise.
Who should read this information
This information is for DB2 application developers who are familiar with
Structured Query Language (SQL) and who know one or more programming
languages that DB2 supports.
DB2 Utilities Suite
Important: In this version of DB2 for z/OS, the DB2 Utilities Suite is available as
an optional product. You must separately order and purchase a license to such
utilities, and discussion of those utility functions in this publication is not intended
to otherwise imply that you have a license to them.
The DB2 Utilities Suite is designed to work with the DFSORT

program, which
you are licensed to use in support of the DB2 utilities even if you do not otherwise
license DFSORT for general use. If your primary sort product is not DFSORT,
consider the following informational APARs mandatory reading:
v II14047/II14213: USE OF DFSORT BY DB2 UTILITIES
v II13495: HOW DFSORT TAKES ADVANTAGE OF 64-BIT REAL
ARCHITECTURE
These informational APARs are periodically updated.
Related information
DB2 utilities packaging (Utility Guide)
Terminology and citations
In this information, DB2 Version 9.1 for z/OS is referred to as DB2 for z/OS. In
cases where the context makes the meaning clear, DB2 for z/OS is referred to as
DB2. When this information refers to titles of DB2 for z/OS books, a short title is
used. (For example, See DB2 SQL Reference is a citation to IBM

DB2 Version 9.1


for z/OS SQL Reference.)
Copyright IBM Corp. 1983, 2008 xiii
When referring to a DB2 product other than DB2 for z/OS, this information uses
the products full name to avoid ambiguity.
The following terms are used as indicated:
DB2 Represents either the DB2 licensed program or a particular DB2 subsystem.
OMEGAMON

Refers to any of the following products:


v IBM Tivoli

OMEGAMON XE for DB2 Performance Expert on z/OS


v IBM Tivoli OMEGAMON XE for DB2 Performance Monitor on z/OS
v IBM DB2 Performance Expert for Multiplatforms and Workgroups
v IBM DB2 Buffer Pool Analyzer for z/OS
C, C++, and C language
Represent the C or C++ programming language.
CICS

Represents CICS Transaction Server for z/OS.


IMS

Represents the IMS Database Manager or IMS Transaction Manager.


MVS

Represents the MVS element of the z/OS operating system, which is


equivalent to the Base Control Program (BCP) component of the z/OS
operating system.
RACF

Represents the functions that are provided by the RACF component of the
z/OS Security Server.
Accessibility features for DB2 Version 9.1 for z/OS
Accessibility features help a user who has a physical disability, such as restricted
mobility or limited vision, to use information technology products successfully.
Accessibility features
The following list includes the major accessibility features in z/OS products,
including DB2 Version 9.1 for z/OS. These features support:
v Keyboard-only operation.
v Interfaces that are commonly used by screen readers and screen magnifiers.
v Customization of display attributes such as color, contrast, and font size
Tip: The Information Management Software for z/OS Solutions Information
Center (which includes information for DB2 Version 9.1 for z/OS) and its related
publications are accessibility-enabled for the IBM Home Page Reader. You can
operate all features using the keyboard instead of the mouse.
Keyboard navigation
You can access DB2 Version 9.1 for z/OS ISPF panel functions by using a keyboard
or keyboard shortcut keys.
For information about navigating the DB2 Version 9.1 for z/OS ISPF panels using
TSO/E or ISPF, refer to the z/OS TSO/E Primer, the z/OS TSO/E Users Guide, and
the z/OS ISPF Users Guide. These guides describe how to navigate each interface,
including the use of keyboard shortcuts or function keys (PF keys). Each guide
includes the default settings for the PF keys and explains how to modify their
functions.
xiv Application Programming and SQL Guide
|
Related accessibility information
Online documentation for DB2 Version 9.1 for z/OS is available in the Information
Management Software for z/OS Solutions Information Center, which is available at
the following Web site: http://publib.boulder.ibm.com/infocenter/dzichelp
IBM and accessibility
See the IBM Accessibility Center at http://www.ibm.com/able for more information
about the commitment that IBM has to accessibility.
How to send your comments
Your feedback helps IBM to provide quality information. Please send any
comments that you have about this book or other DB2 for z/OS documentation.
You can use the following methods to provide comments:
v Send your comments by e-mail to [email protected] and include the name
of the product, the version number of the product, and the number of the book.
If you are commenting on specific text, please list the location of the text (for
example, a chapter and section title or a help topic title).
v You can send comments from the Web. Visit the DB2 for z/OS - Technical
Resources Web site at:
http://www.ibm.com/support/docview.wss?&uid=swg27011656
This Web site has an online reader comment form that you can use to send
comments.
v You can also send comments by using the feedback link at the footer of each
page in the Information Management Software for z/OS Solutions Information
Center at http://publib.boulder.ibm.com/infocenter/db2zhelp.
How to read syntax diagrams
Certain conventions apply to the syntax diagrams that are used in IBM
documentation.
Apply the following rules when reading the syntax diagrams that are used in DB2
for z/OS documentation:
v Read the syntax diagrams from left to right, from top to bottom, following the
path of the line.
The symbol indicates the beginning of a statement.
The symbol indicates that the statement syntax is continued on the next
line.
The symbol indicates that a statement is continued from the previous line.
The symbol indicates the end of a statement.
v Required items appear on the horizontal line (the main path).
required_item
v Optional items appear below the main path.
About this information xv
required_item
optional_item

If an optional item appears above the main path, that item has no effect on the
execution of the statement and is used only for readability.

optional_item
required_item
v If you can choose from two or more items, they appear vertically, in a stack.
If you must choose one of the items, one item of the stack appears on the main
path.
required_item required_choice1
required_choice2

If choosing one of the items is optional, the entire stack appears below the main
path.
required_item
optional_choice1
optional_choice2

If one of the items is the default, it appears above the main path and the
remaining choices are shown below.
required_item
default_choice
optional_choice
optional_choice

v An arrow returning to the left, above the main line, indicates an item that can be
repeated.
required_item

repeatable_item
If the repeat arrow contains a comma, you must separate repeated items with a
comma.
required_item

,
repeatable_item
A repeat arrow above a stack indicates that you can repeat the items in the
stack.
v Sometimes a diagram must be split into fragments. The syntax fragment is
shown separately from the main syntax diagram, but the contents of the
fragment should be read as if they are on the main path of the diagram.
required_item fragment-name
xvi Application Programming and SQL Guide
|
|
|
|||||||||||||
|
fragment-name:
required_item
optional_name
v With the exception of XPath keywords, keywords appear in uppercase (for
example, FROM). Keywords must be spelled exactly as shown. XPath keywords
are defined as lowercase names, and must be spelled exactly as shown. Variables
appear in all lowercase letters (for example, column-name). They represent
user-supplied names or values.
v If punctuation marks, parentheses, arithmetic operators, or other such symbols
are shown, you must enter them as part of the syntax.
About this information xvii
|
||||||||||||||||
|
|
|
|
xviii Application Programming and SQL Guide
Chapter 1. Planning for and designing DB2 applications
Whether you are writing a new DB2 application or migrating an existing
application from a previous release of DB2, you need to make some planning and
design decisions before you write or run the program.
If you are migrating an existing application from a previous release of DB2, read
the application and SQL release incompatibilities and make any necessary changes
in the application.
If you are writing a new DB2 application, first determine the following items:
v the value of some of the SQL processing options
v the binding method
v the value of some of the bind options
Then make sure that your program implements the appropriate recommendations
so that it promotes concurrency, can handle recovery and restart situations, and can
efficiently access distributed data.
Application and SQL release incompatibilities
When you migrate to Version 9.1, be aware of the following application and SQL
release incompatibilities.
Changes in BIND PACKAGE and BIND PLAN defaults
The default value for bind option CURRENTDATA is changed from YES to NO.
This applies to the BIND PLAN and the BIND PACKAGE subcommands, as well
as the CREATE TRIGGER for trigger packages, and the CREATE PROCEDURE and
the ALTER PROCEDURE ADD VERSION SQL statements for SQL PL procedure
packages. Specifying NO for CURRENTDATA is the best option for performance.
The default value for bind option ISOLATION is changed from RR to CS. This
applies to the BIND PLAN and the remote BIND PACKAGE subcommands. For
the BIND PACKAGE subcommand, the current default (plan value) stays. The
default change does not apply to implicitly-built CTs (for example, DISTSERV CTs).
Although you can specify DBPROTOCOL(PRIVATE) for the DBPROTOCOL
parameter of the BIND option, DB2 issues a new warning message, DSNT226I.
All BIND statements for plans and packages that are bound during the installation
or migration process specify the ISOLATION parameter explicitly, except for
routines that do not fetch data. The current settings are maintained for
compatibility.
Plan for the XML data type
Drop any user-defined data types with the name XML to prevent problems with
the new Version 9 built-in XML data type. You can recreate the existing
user-defined data types with new names.
Copyright IBM Corp. 1983, 2008 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Changes to XMLNAMESPACES
In Version 8, in the XMLNAMESPACES function, if the XML-namespace-uri
argument had a value of http://www.w3.org/XML/1998/namespace or
http://www.w3.org/2000/xmlns/, DB2 did not issue an error. In Version 9.1,
starting in conversion mode, DB2 issues an error.
Changes to serialization of empty elements
In Version 8, DB2 serialized empty XML elements in a different way than it
serializes them in Version 9.1. In Version 8, empty element a was serialized as
<a></a>. In Version 9.1, starting in conversion mode, empty element a is
serialized as <a/>.
Availability of LOB or XML values in JDBC or SQLJ applications
with progressive streaming
In previous releases, if a JDBC or SQLJ application retrieved LOB data into an
application variable, the contents of the application variable were still available
after the cursor was moved or closed. DB2 Version 9.1 for z/OS supports
streaming. The IBM Data Server Driver for JDBC and SQLJ uses progressive
streaming as the default for retrieval of LOB or XML values. When progressive
streaming is in effect, the contents of LOB or XML variables are no longer available
after the cursor is moved or closed.
Adjust applications that depend on error information that is
returned from DB2-supplied stored procedures
Adjust any applications that call one of the following stored procedures and then
check and process the specific SQLCODE or SQLSTATE that is returned by the
CALL statement:
v SQLJ.INSTALL_JAR
v SQLJ.REMOVE_JAR
v SQLJ.REPLACE_JAR
v SQLJ.DB2_INSTALL_JAR
v SQLJ.DB2_REPLACE_JAR
v SQLJ.DB2_REMOVE_JAR
v SQLJ.DB2_UPDATEJARINFO
In Version 9.1, these stored procedures return more meaningful SQLCODEs and
SQLSTATEs than they returned in previous releases of DB2. The other input and
output parameters of these stored procedures have not changed.
For example, the following application needs to change, because the SQLCODE
that is returned is no longer -20201. Successful execution (SQLCODE 0) is not
affected.
CALL SQLJ.REMOVE_JAR(...)
IF (SQLCODE = -20201) THEN
DO;
...
END;
2 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Qualify user-defined function names
If you use a user-defined function that has the same name as a built in function
that has been added to Version 9.1, ensure that you fully qualify the function
name. If the function name is unqualified and SYSIBM precedes the schema that
you used for this function in the SQL path, DB2 invokes one of the built-in
functions. For a list of built-in functions, including those that have been added in
Version 9.1, see the topic Functions.
Fully define objects
Ensure that you do not have any incomplete object definitions in your DB2 Version
8 catalog. For example, if a table has a primary or unique key defined but the
enforcing primary or unique key index does not exist, the table definition is
considered incomplete. You need to complete or drop all such objects before you
begin migration because their behavior will be different in Version 9.1. For
example, if you attempt to create an enforcing primary key index to complete a
table definition in Version 9.1 and the residing table space is implicitly created, the
index will be treated as a regular index instead of an enforcing index.
SQL reserved words
Version 9.1 has several new SQL reserved words. Refer to DB2 SQL Reference for
the list, and adjust your applications accordingly.
Changes to PL/I applications with no DECLARE VARIABLE
statements
For PL/I applications with no DECLARE VARIABLE statements, the rules for host
variables and string constants in the FROM clause of a PREPARE or EXECUTE
IMMEDIATE statement have changed. A host variable must be a varying-length
string variable that is preceded by a colon. A PL/I string cannot be preceded by a
colon.
Automatic rebind of plans and packages created before DB2
Version 4
If you have plans and packages that were bound before DB2 Version 4 and you
specified YES or COEXIST in the AUTO BIND field of panel DSNTIPO, DB2
Version 9.1 autobinds these packages. Thus, you might experience an execution
delay the first time that such a plan is loaded. Also, DB2 might change the access
path due to the autobind, potentially resulting in a more efficient access path.
If you specified NO in the AUTO BIND field of panel DSNTIPO, DB2 Version 9.1
returns SQLCODE -908, SQLSTATE 23510 for each attempt to use such a package
or plan until it is rebound.
Changed behavior of the INSERT statement with the
OVERRIDING USER VALUES clause
When the INSERT statement is specified with the OVERRIDING USER VALUES
clause, the value for the insert operation is ignored for columns that are defined
with the GENERATED BY DEFAULT attribute.
Chapter 1. Planning for and designing DB2 applications 3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
DESCRIBE no longer returns LONG type values
Because DB2 no longer stores LONG type values in the catalog, when you execute
a DESCRIBE statement against a column with a LONG VARCHAR or LONG
VARGRAPHIC data type, the DESCRIBE statement returns the values as
VARCHAR or VARGRAPHIC data type.
The DSNTIAUL sample program was updated through APAR PK46518 to account
for this change. You need to apply APAR PK46518 and precompile, bind compile,
and link-edit DSNTIAUL to make it compatible with the changed DESCRIBE
behavior.
DB2 enforces the restrictions about where a host variable array
can be specified
host-variable-array is the meta-variable for host variable arrays in syntax diagrams.
host-variable-array is included only in the syntax for multi-row FETCH, multi-row
INSERT, multi-row MERGE, and EXECUTE in support of a dynamic multi-row
INSERT or MERGE statement. host-variable-array is not included in the syntax
diagram for expression , so a host variable array cannot be used in other contexts.
In previous releases, if you specified host-variable-array in an unsupported context,
you received no errors. In Version 9.1, if a host variable array is referenced in an
unsupported context, DB2 issues an error.
For more information about where you can specify the host-variable-array variable,
see DB2 SQL Reference.
DEBUGSESSION system privilege required for continued
debugging of SQL procedures
After you migrate to new-function mode, users that debug external SQL
procedures need the DEBUGSESSION system privilege. (External SQL procedures
were previously called SQL procedures in Version 8.) Only users of the new
Unified Debugger enabled client platforms need this system privilege. Users of the
Version 8 SQL Debugger-enabled client platforms do not need this system
privilege.
Changes to the result length of the DECRYPT function
The result length of the DECRYPT function is shortened to 8 bytes less than the
length of the input value. If the result expands because of a difference between
input and result CCSIDs, you must cast the encrypted data to a larger VARCHAR
value before the DECRYPT function is run.
COLTYPE column in SYSIBM.SYSCOLUMNS and
SYSIBM.SYSCOLUMNS_HIST for LONG column types
When new tables are created with LONG VARCHAR or LONG VARGRAPHIC
columns, the COLTYPE values in SYSIBM.SYSCOLUMNS and
SYSIBM.SYSCOLUMNS_HIST contain VARCHAR or VARG.
4 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
CREATEDBY column in SYSIBM.SYSDATATYPES,
SYSIBM.SYSROUTINES, SYSIBM.SYSSEQUENCES, and
SYSIBM.SYSTRIGGERS
The CREATEDBY column might contain a different value than in previous releases
of DB2. The column might contain a different value in static CREATE statements
for distinct types, functions, and procedures or when a dynamic SQL statement
sets the CURRENT SQLID value to a value other than USER.
Drop and recreate SYSPROC.DSNWZP
Drop and recreate SYSPROC.DSNWZP as part of running job DSNTIJSG or alter it
to specify READS SQL DATA, as shown in the following SQL statement:
ALTER PROCEDURE SYSPROC.DSNWZP READS SQL DATA;
On data sharing systems, SYSPROC.DSNWZP needs to be dropped and recreated
as part of migrating the first member, but not for subsequent members. DSNTIJSG
grants execute access on DSNWZP to PUBLIC. If necessary, change PUBLIC to a
specific authorization ID.
DB2 returns all DSNWZP output in the same format as DB2
parameters
In previous releases, DSNWZP returned the current setting of several system
parameters in a format other than the one used by the system parameter macros.
For example, DSN6SPRM expected the setting for EDMPOOL in kilobytes, and
DSNWZP returned it in bytes. In Version 9.1, DB2 returns all DSNWZP output in
the same format as DB2 parameters. Modify programs that call DSNWZP if they
compensate for the format differences.
DB2 enforces the restriction that row IDs are not compatible with
character strings when they are used with a set operator
In previous releases, DB2 did not always enforce the restriction that row IDs are
not compatible with character strings. In Version 9.1, DB2 enforces the restriction
that row IDs are not compatible with string types when they are used with a set
operator (UNION, INTERSECT, or EXCEPT).
You can no longer explicitly create a database name as
DSNxxxxx
After you migrate to conversion mode, if you explicitly create a database name
with eight characters that begins with DSN and is followed by exactly five digits,
DB2 issues an SQLCODE -20074 (SQLSTATE 42939).
Database privileges on the DSNDB04 database now give you
those privileges on all implicitly-created databases
Because database privileges on the DSNDB04 database now give you those
privileges on all implicitly created databases, careful consideration is needed before
you grant database privileges on DSNDB04. For example, in Version 9.1, if you
have the STOPDB privilege on DSNDB04, you also have the STOPDB privilege on
all implicitly-created databases.
Chapter 1. Planning for and designing DB2 applications 5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Implicitly-created objects that are associated with LOB columns
require additional privileges
In previous releases, implicitly-created objects that are associated with LOB
columns did not require CREATETAB and CREATETS privileges on the database
of the base table or USE privilege on the buffer pool and storage group that is
used by the LOB objects. In Version 9.1, these privileges are required.
Adjust applications to use LRHCLR instead of LGDISCLR
The LGDISCLR field in the DSNDQJ00 macro has been removed. Update
applications that used the LGDISCLR value in the DSNDQJ00 mapping macro to
determine whether a log record is a compensation log record to use the LRHCLR
value instead.
Changed behavior for the CREATE statement
You can no longer create databases with the AS TEMP clause or table spaces that
specify TEMP as the target database. The TEMP database is no longer used by
DB2. The WORKFILE database is the only temporary database.
The DECLARE statement and the work file database
If you have applications in Version 8 that issue DECLARE SENSITIVE STATIC
SCROLL CURSOR or DECLARE GLOBAL TEMPORARY TABLE statements,
ensure that the work file database exists and that it has at least one table space
with a 32-KB page size to avoid errors.
Adjust monitor programs that access OP buffers
Adjust assignment strategies of monitor programs that access OP buffers. In
Version 8, traces were left in a disabled state, which consumed CPU for trace data
that could not be retrieved. In Version 9.1, traces that are started with a destination
of OPX choose the next available buffer that is not in use and traces are no longer
left in a disabled state.
In addition, in Version 8, when the thread that owned an OP buffer terminated, OP
traces were left in a disabled state and could be reactivated by starting another
trace to that buffer. In Version 9.1, if an OP buffer terminates and the only
destinations for the trace records are OP buffers, the traces that are started to that
buffer are stopped. If an OP buffer terminates and the trace is started to both OP
and non-OP destinations, the traces that are started to that buffer are modified to
use non-OP destinations only.
The message format of DSNW128I and DSNW129I has changed, so modify
automation that is based on those message formats.
Changed behavior for system-required objects
After you migrate to Version 9.1 new-function mode, if the containing table space
is implicitly-created, you cannot drop any system-required objects, except for the
LOB table space, even if you explicitly created these objects in a previous release.
The following statements will not work properly if the system-required objects
were implicitly created by DB2:
6 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
CREATE AUXILIARY TABLE
If you issue a CREATE AUXILIARY TABLE statement and an auxiliary
table that was implicitly created by DB2 already exists for the same base
table, the CREATE AUXILIARY TABLE statement fails and DB2 issues
SQLCODE -646, SQLSTATE 55017, and reason code 3.
CREATE LOB TABLESPACE
If you issue a CREATE LOB TABLESPACE statement to create a LOB table
space in an implicitly created database, the CREATE LOB TABLESPACE
statement fails and DB2 issues SQLCODE -20355, SQLSTATE 429BW, and
reason code 1.
CREATE DATABASE
If you specify a database name with eight characters that begins with DSN
and is followed by exactly five digits in a CREATE DATABASE statement,
the CREATE DATABASE statement fails and DB2 issues SQLCODE -20074,
SQLSTATE 42939.
CREATE INDEX
If you create an index on a primary key, unique key, or ROWID column
that is defined as GENERATED BY DEFAULT, the index will be treated as
a regular index instead of an enforcing index.
CREATE AUXILIARY INDEX
If you issue a CREATE AUXILIARY INDEX statement and an auxiliary
index that was implicitly created by DB2 already exists for the same base
table, the CREATE AUXILIARY INDEX statement fails and DB2 issues
SQLCODE -748, SQLCODE 54048, and reason code 3.
CREATE
If you issue a CREATE statement and do not specify an IN clause or table
space name, and the default buffer pool is not large enough, DB2 chooses a
4-KB, 8-KB, 16-KB, or 32-KB buffer pool, depending on the record size. If
you issue a CREATE statement and do not specify an IN clause or table
space name, DB2 implicitly creates a partitioned-by-growth table space. If
you drop the table, DB2 also drops the containing table space.
DROP TABLE
If you issue a DROP TABLE statement to drop an auxiliary table from a
table space that was implicitly created by DB2, the DROP TABLE statement
fails and DB2 issues SQLCODE -20355, SQLSTATE 429BW, and reason code
2.
DROP TABLESPACE
If you issue a DROP TABLESPACE statement to drop an implicitly-created
LOB table space, the DROP TABLESPACE statement fails and DB2 issues
SQLCODE -20355, SQLSTATE 429BW, and reason code 2.
DROP INDEX
If you issue a DROP INDEX statement to drop an enforcing primary key,
unique key, or ROWID index from a table space that was implicitly
created, the DROP INDEX statement fails and DB2 issues SQLCODE -669,
SQLSTATE 42917, and reason code 2. If you issue a DROP INDEX
statement to drop an auxiliary index from a table space that was implicitly
created, the DROP INDEX statement fails and DB2 issues SQLCODE
-20355, SQLSTATE 429BW, and reason code 2.
Chapter 1. Planning for and designing DB2 applications 7
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Changes to INSERT, UPDATE, or DELETE statements on some
indexes
In Version 9.1, you cannot execute INSERT, UPDATE, or DELETE statements that
affect an index in the same commit scope as ALTER INDEX statements on that
index.
LOBs with a maximum length greater than 1 GB can now be
logged
In previous releases, only LOBs with a maximum length of 1 GB or less could be
logged. In Version 9.1, LOBs with a maximum length that is greater than 1 GB can
be logged.
DB2 returns an error when a LOB value is specified for an
argument to a stored procedure and the argument value is
longer than the target parameter and the excess is not trailing
blanks
In previous releases, DB2 did not return an error when a LOB value was specified
for an argument to a stored procedure and the argument value was longer than the
target parameter and the excess was not trailing blanks. DB2 truncated the data
and the procedure executed. In Version 9.1, DB2 returns an error.
Changes to VARCHAR function formatting of decimal data
In Version 9.1, the formatting of decimal data has changed for the VARCHAR
function and CAST specification with a VARCHAR result type. When the input
data is decimal, any leading zeroes in the input value are removed, and leading
zeroes are not added to an input value that did not already contain leading zeroes.
Changes to VARCHAR_FORMAT function length attribute
In Version 9.1, the length attribute of the result is the length attribute of the format
string, up to a maximum of 100.
W is no longer recognized as a valid format element of the
VARCHAR_FORMAT function format string
DB2 Version 9.1 no longer recognizes W as a valid format element of the
VARCHAR_FORMAT function format string. Version 8 never recognized W as a
valid format element
Use WW instead. Drop and recreate existing views and materialized queries that
are defined with Version 9.1 and that use the W format element with the
VARCHAR_FORMAT function. Rebind existing bound statements that are bound
with Version 9.1 and that use the W format element with the
VARCHAR_FORMAT function.
Leading or trailing blanks from the VARCHAR_FORMAT function
format string are no longer removed
Leading or trailing blanks from the format string for the VARCHAR_FORMAT
function are no longer removed. Existing view definitions are recalculated as part
of Version 9.1, so the new rules take effect. You can continue to use existing
materialized query statements, but they use the old rules and remove leading and
8 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
trailing blanks. Existing references to the VARCHAR_FORMAT function in bound
statements only get the new behavior when they have been bound or rebound in
Version 9.1.
DB2 issues warnings when some BEFORE or AFTER triggers are
created
DB2 Version 9.1 for z/OS issues a warning when a BEFORE or AFTER trigger is
created and a trigger transition variable is passed as an argument for a parameter
on a CALL statement that is within the trigger body.
DB2 drops certain indexes when a unique constraint is dropped
In previous releases, if a unique constraint was dropped, DB2 did not drop the
index that enforced uniqueness. In Version 9.1, if a table is in an implicitly-created
table space, and a unique constraint on that table is dropped, DB2 drops the index
that enforces uniqueness.
Changes to the upper limit to the size of the row that is used by
sort to evaluate column functions
The maximum limit of a row (data and key columns) that is used by sort to
evaluate MULTIPLE DISTINCT and GROUP BY column functions is decreased to
32600. If you exceed the limit, DB2 issues an error.
DB2 enforces restriction on specifying a CAST FROM clause for
some forms of CREATE FUNCTION statements
The CAST FROM clause is included only in the syntax diagram for the CREATE
FUNCTION statement for an external scalar function. The CAST FROM clause is
not included in the syntax diagrams for the other variations of CREATE
FUNCTION (external table function, sourced function, or SQL function); the clause
cannot be used for these other variations. In previous releases, if you specified a
CAST FROM clause in an unsupported context, you received no errors. In Version
9.1 if a CAST FROM clause is specified in an unsupported context, DB2 issues an
error.
DB2 enforces restrictions on specifying the AS LOCATOR clause
and TABLE LIKE clause
The AS LOCATOR clause for LOBs is included in the syntax diagram for the
CREATE FUNCTION statement for an SQL function. This clause is not supported
in other contexts when identifying an existing SQL function such as in an ALTER,
COMMENT, DROP, GRANT, or REVOKE statement. In previous releases, if you
specified an AS LOCATOR clause for LOBs in an unsupported context, you might
not have received an error. In Version 9.1 if an AS LOCATOR clause for LOBs is
specified in an unsupported context, DB2 issues an error.
The TABLE LIKE clause for a trigger transition table is included only in the syntax
diagram for the CREATE FUNCTION statement for an external scalar function,
external table function, or sourced function. This clause is not supported for SQL
functions or in other contexts when identifying an existing function such as in an
ALTER, COMMENT, DROP, GRANT, or REVOKE statement, or in the SOURCE
clause of a CREATE FUNCTION statement. In previous releases, if you specified a
TABLE LIKE clause for a trigger transition table in an unsupported context, you
might not have received an error. In Version 9.1 if a TABLE LIKE clause for a
Chapter 1. Planning for and designing DB2 applications 9
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
trigger transition table is specified in an unsupported context, DB2 issues an error.
DB2 enforces restriction on the CCSID parameter for the
DECRYPT_BIT and DECRYPT_BINARY functions
The CCSID parameter is not supported by the DECRYPT_BIT and
DECRYPT_BINARY built-in functions. In previous releases, if you specified an
argument for the CCSID parameter for these functions, you received no errors. In
Version 9.1 if an argument is specified for the CCSID parameter in an unsupported
context, DB2 issues an error.
Changed behavior of CREATE PROCEDURE for an SQL
procedure
With the introduction of native SQL procedures in Version 9.1, the semantics of the
CREATE PROCEDURE statement for an SQL procedure has changed. Starting in
Version 9.1, all SQL procedures that are created without the FENCED option or the
EXTERNAL option in the CREATE PROCEDURE statement are native SQL
procedures. In previous releases of DB2, if you did not specify either of these
options, the procedures were created as external SQL procedures.
If you do specify FENCED or EXTERNAL, the meanings are the same as in
previous releases of DB2. Both of these keywords mean that an external SQL
procedure is to be created.
Explicitly qualify names of variables, parameters, and columns in
SQL procedures
In Version 9.1, the rules used for name resolution within a native SQL procedure
differ from the rules that were used for SQL procedures in prior releases. Because
an SQL parameter or SQL variable can have the same name as a column name,
you should explicitly qualify the names of any SQL parameters, SQL variables or
columns that have non-unique names. For more information about how the names
of these items are resolved, see the topic References to SQL parameters and SQL
variables. The rules used for name resolution within external SQL procedures
remains unchanged.
Make any necessary program changes for possibly different
values for RETURNED_SQLSTATE and
DB2_RETURNED_SQLCODE
In Version 9.1, when an SQL statement other than GET DIAGNOSTICS or
compound-statement is processed, the current diagnostics area is cleared before
DB2 processes the SQL statement. Clearing of the diagnostics area can result in
different values being returned for RETURNED_SQLSTATE and
DB2_RETURNED_SQLCODE for a GET DIAGNOSTICS statement than what
would be returned if the GET DIAGNOSTICS statement were issued from within
an external SQL procedure. Additionally, there might be some differences in the
values returned for the SQLSTATE and SQLCODE SQL variables than would have
been returned from an external SQL procedure. (External SQL procedures were
previously called SQL procedures in Version 8.)
10 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
SQLSTATE and SQLCODE SQL variables after a GET
DIAGNOSTICS statement
In Version 9.1, the SQLSTATE and SQLCODE SQL variables are not cleared
following a GET DIAGNOSTICS statement.
Coding multiple SQL statements in a handler body
Previous releases of DB2 did not allow for a compound statement within a handler.
A workaround to include multiple statements within a handler (without support
for a compound statement in a handler) was to use another control statement, such
as an IF statement, which in turn contained multiple statements. Version 9.1 now
supports a compound statement within a handler body. The compound statement
is recommended for including multiple statements within a handler body.
Unhandled warnings
In Version 9.1, when a native SQL procedure completes processing with an
unhandled warning, DB2 returns the unhandled warning to the calling application.
The behavior of an external SQL procedure is unchanged from releases prior to
Version 9.1. When such a procedure completes processing with an unhandled
warning, DB2 does not return the unhandled warning to the calling application.
Change your programs to handle any changed messages from
SQL procedures
In Version 9.1, DB2 issues different messages for the new native SQL procedures
than it does for external SQL procedures. (External SQL procedures were
previously called SQL procedures in Version 8.) For external SQL procedures, DB2
continues to issue DSNHxxxx messages. For native SQL procedures, DB2 issues
SQL return codes. The relationship between these messages is shown in the
following table:
Table 1. Relationship between DSNHxxxx messages that are issued for external SQL
procedures and SQLCODEs that are issued for native SQL procedures
DSNHxxxx message
1
SQLCODE
2
DSNH051I -051
DSNH385I +385
DSNH590I -590
DSNH4408I -408
DSNH4777I -777
DSNH4778I -778
DSNH4779I -779
DSNH4780I -780
DSNH4781I -781
DSNH4782I -782
DSNH4785I -785
DSNH4787I -787
Note:
Chapter 1. Planning for and designing DB2 applications 11
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
||
||
||
||
||
||
||
||
||
||
||
||
||
|
|
1. These messages are used for external SQL procedures, which can be defined by
specifying EXTERNAL or FENCED in Version 9.1.
2. These messages are used for native SQL procedures in Version 9.1.
Enhanced data type checking for zero-length characters
In Version 9.1, when you specify a CHAR data type with a length of 0 in the
SQLDA, DB2 issues SQLCODE -804 regardless of the null indicator value.
Adding a column generates a new table space version
In previous releases, adding a column to a table did not generate a new table space
version. In Version 9.1, adding a column to a table with an ALTER TABLE ADD
COLUMN statement generates a new table space version.
You cannot add a column and issue SELECT, INSERT, UPDATE,
DELETE, or MERGE statements in the same commit scope
You cannot have a version-generating ALTER TABLE ADD COLUMN statement
and SELECT, INSERT, UPDATE, DELETE, or MERGE statements in the same
commit scope. If a version-generating ALTER TABLE ADD COLUMN statement
follows SELECT, INSERT, UPDATE, DELETE, or MERGE statements in the same
commit scope, SQLCODE -910 is issued. SQLCODE -910 is also issued if SELECT,
INSERT, UPDATE, DELETE, or MERGE statements follow a version-generating
ALTER TABLE ADD COLUMN statement in the same commit scope.
CAST FROM clause of CREATE FUNCTION statement for SQL
functions is no longer supported
The CAST FROM clause of the CREATE FUNCTION statement for SQL functions
is no longer supported. If you issue a CREATE FUNCTION statement for an SQL
function with a CAST FROM clause, DB2 issues an error.
GRAPHIC and NOGRAPHIC SQL processing options are
deprecated
If you specify the SQL processing options GRAPHIC or NOGRAPHIC, DB2 ignores
them. These options are superseded by the CCSID SQL processing option.
Specifying ALTER DATABASE STOGROUP for work file
databases
In previous releases of DB2, you could not execute ALTER DATABASE
STOGROUP on a work file database. Beginning with DB2 Version 9.1 conversion
mode, this restriction is removed.
DB2 enforces restrictions about where an INTO clause can be
specified
The INTO clause (as related to queries) is included only in the syntax diagram for
the SELECT INTO statement. The INTO clause is not included in the syntax
diagrams for select-clause, subselect, fullselect, or select-statement. In previous
releases, if you specified an INTO clause in an unsupported context in a query, you
might not have received an error. In Version 9.1 if an INTO clause is specified in
an unsupported context, DB2 issues an error.
12 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Determining the value of any SQL processing options that affect the
design of your program
When you process SQL statements in an application program, you can specify
options that describe the basic characteristics of the program or indicate how you
want the output listings to look. Although most of these options do not affect how
you design or code the program, a few options do.
SQL processing options specify program characteristics such as the following items:
v The host language in which the program is written
v The maximum precision of decimal numbers in the program
v How many lines are on a page of the precompiler listing
In many cases, you may want to accept the default value provided.
To determine the value of any SQL processing options that affect the design of
your program:
Review the list of SQL processing options and decide the values for any options
that affect the way that you write your program. For example, you need to know if
you are using NOFOR or STDSQL(YES) before you begin coding.
Related concepts
DB2 program preparation overview on page 911
Related reference
Descriptions of SQL processing options on page 868
Determining the binding method
Before you can run an application, you must bind a plan. You can bind all of your
database request modules (DBRMs) into a single application plan or you can first
bind packages and then bind those packages into a plan. The bind method that
you choose can affect your application design.
You can choose one of the following binding methods:
v Bind all of your DBRMs into a single application plan.
v Bind all of your DBRMs into separate packages. Then bind all those packages
into a single application plan.
v Bind some of your DBRMs into separate packages. Then bind those packages
and any other DBRMs for that program into an application plan.
The use of packages affects your application design. For example, you might
decide to put certain SQL statements together in the same program, precompile
them into the same DBRM, and then bind them into a single package.
To determine the binding method:
Consider the advantages and disadvantages of each binding method, which are
described in the following table.
Chapter 1. Planning for and designing DB2 applications 13
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Table 2. Advantages and disadvantages of each binding method
Binding method Advantages Disadvantages
Bind all of your DBRMs
into a single application
plan.
This method has fewer steps and is appropriate in
some cases. This method is suitable for small
applications that are unlikely to change or that require
all resources to be acquired when the plan is allocated,
rather than when your program first uses them.
Maintenance is difficult. This
method has the disadvantage
that a change to one DBRM
requires rebinding the entire
plan, even though most DBRMs
are unchanged.
14 Application Programming and SQL Guide
||
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Table 2. Advantages and disadvantages of each binding method (continued)
Binding method Advantages Disadvantages
Bind all of your DBRMs
into separate packages.
Then bind all those
packages into a single
application plan
Maintenance is easier. When you use packages, you do
not need to bind the entire plan again when you
change one SQL statement. You need to bind only the
package that is associated with the changed SQL
statement.
You can incrementally develop your program without
rebinding the plan. A collection is a group of associated
packages. Binding packages into package collections
enables you to add packages to an existing application
plan without having to bind the plan again. If you
include a collection name in the package list when you
bind a plan, any package in the collection becomes
available to the plan. The collection can be empty when
you first bind the plan. Later, you can add packages to
the collection and drop or replace existing packages
without binding the plan again.
You can maintain several versions of a package within
the same plan. Maintaining several versions of a plan
without using packages requires a separate plan for
each version, and therefore, separate plan names and
RUN commands. Isolating separate versions of a
program into packages requires only one plan and
helps to simplify program migration and fallback. For
example, you can maintain separate development, test,
and production levels of a program by binding each
level of the program as a separate version of a package,
all within a single plan. You cannot bind or rebind a
package or a plan while it is running. However, you
can bind a different version of a package that is
running.
You can use different bind options for different
DBRMs. The options of the BIND PLAN command
apply to all DBRMs that are bound directly to the plan.
The options of the BIND PACKAGE command apply to
only the single DBRM that is bound to that package.
The package options need not all be the same as the
plan options, and they need not be the same as the
options for other packages that are used by the same
plan.
You can use different name qualifiers for different
groups of SQL statements. You can use a bind option
to name a qualifier for the unqualified object names in
SQL statements in a plan or package. By using
packages, you can use different qualifiers for SQL
statements in different parts of your application. By
rebinding, you can redirect your SQL statements, for
example, from a test table to a production table.
Unused packages are not locked. Packages and plans
are locked when you bind or run them. Packages that
run under a plan are not locked until the plan uses
them. If you run a plan and some packages in the
package list never run, those packages are never
locked.
Too many packages might be
difficult to track. Input to
binding a package is a single
DBRM only. A one-to-one
correspondence between
programs and packages might
easily enable you to keep track
of each. However, your
application might consist of too
many packages to track easily.
Chapter 1. Planning for and designing DB2 applications 15
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Table 2. Advantages and disadvantages of each binding method (continued)
Binding method Advantages Disadvantages
Bind some of your
DBRMs into separate
packages. Then bind
those packages and any
other DBRMs for that
program into an
application plan.
This method helps you migrate to using packages.
Binding DBRMs directly to the plan and specifying a
package list is a suitable method for maintaining
existing applications. You can add a package list when
you rebind an existing plan. To migrate gradually to
the use of packages, bind DBRMs as packages when
you need to make changes.
Depending on your application
design, you might not gain some
of the advantages of using
packages.
Related concepts
DB2 program preparation overview on page 911
Related tasks
Binding an application on page 880
Changes that invalidate plans or packages
Changes to your program or database objects can invalidate plans and packages.
Consider the effect of these changes when you determine the binding method for
your program.
A change to your program probably invalidates one or more of your packages and
perhaps your entire plan. For some changes, you must bind a new object; for
others, rebinding is sufficient.
A plan or package can also become invalid for reasons that do not depend on
operations in your program. For example, when an index is dropped that is used
in an access path by one of your queries, a plan or package can become invalid. In
those cases, DB2 might rebind the plan or package automatically the next time that
the plan or package is used.
The following table lists the actions that you must take when changes are made to
your program or database objects.
Table 3. Changes that require plans or packages to be rebound.
Change made Required action
Run RUNSTATS to update catalog statistics Rebind the package or plan by using the
REBIND command. Rebinding might
improve the access path that DB2 uses.
Add an index to a table Rebind the package or plan by using the
REBIND command. Rebinding causes DB2 to
consider using the index when accessing this
table.
Change the bind options
1
Rebind the package or plan by using the
REBIND command and specifying the new
value for the bind option. If the option that
you want to change is not available for the
REBIND command, issue the BIND
command with ACTION(REPLACE) instead.
Change both statements in the host language
and SQL statements
Precompile, compile, and link the application
program. Issue the BIND command with
ACTION(REPLACE) for the package or plan.
16 Application Programming and SQL Guide
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
||
||
|
|
||
|
|
|
||
|
|
|
|
|
|
|
|
|
|
Table 3. Changes that require plans or packages to be rebound. (continued)
Change made Required action
Drop a table, index, or other object, and
recreate the object
If a table with a trigger is dropped, recreate
the trigger if you recreate the table.
Otherwise, no change is required. DB2
attempts to automatically rebind the plan or
package the next time it is run.
Drop an object that a package depends on No action is required. If the package or plan
becomes invalid, DB2 automatically rebinds
the plan or package the next time that it is
allocated.
The package might become invalid according
to the following criteria:
v If the package is not appended to any
running plan, the package becomes
invalid.
v If the package is appended to a running
plan, and the drop occurs within that plan,
the package becomes invalid. However, if
the package is appended to a running
plan, and the drop occurs outside of that
plan, the object is not dropped, and the
package does not become invalid.
In all cases, the plan does not become invalid
until it has a DBRM that references the
dropped object.
Revoke an authorization to use an object No action is required. DB2 attempts to
automatically rebind the plan or package the
next time it is run. Automatic rebind fails if
authorization is still not available. In this
case, you must rebind the package or plan by
using the REBIND command.
Rename a column in a table on which a plan
or package is dependent
No action is required. DB2 automatically
rebinds invalidated plans and packages. If
automatic rebind is unsuccessful, modify,
recompile, and rebind the affected
applications.
Note:
1. In the case of changing the bind options, the change is not actually made until
you perform the required action.
Related concepts
Automatic rebinding on page 908
Trigger packages on page 437
Related tasks
Rebinding an application on page 900
Chapter 1. Planning for and designing DB2 applications 17
|
||
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Determining the value of any bind options that affect the design of
your program
Several options of the BIND PACKAGE and BIND PLAN commands can affect
your program design. For example, you can use a bind option to ensure that a
package or plan can run only from a particular CICS connection or IMS region;
your code does not need to enforce this situation.
To determine the value of any bind options that affect the design of your program:
Review the list of bind options and decide the values for any options that affect
the way that you write your program. For example, you should decide the values
of the ACQUIRE and RELEASE options before you write your program. These
options determine when your application acquires and releases locks on the objects
it uses.
Related reference
BIND and REBIND options (DB2 Command Reference)
Designing your application to promote concurrency
You should design your program so that it protects the integrity of the data, but
does not prevent other processes from accessing the same data for long periods of
time.
Concurrency is the ability of more than one application process to access the same
data at essentially the same time. Concurrency must be controlled to prevent lost
updates and such possibly undesirable effects as unrepeatable reads and access to
uncommitted data.
To design your application to promote concurrency:
1. Understand the techniques that DB2 uses to control concurrency.
One basic way that DB2 controls concurrency is by using locks for units of
work. When a unit of work completes, all locks that were implicitly acquired
by that unit of work are released, which enables a new unit of work to begin.
The amount of processing time that is used by a unit of work in your program
affects the length of time that DB2 prevents other users from accessing that
locked data. When several programs try to use the same data concurrently, each
programs unit of work should be as short as possible to minimize the
interference between the programs.
Other techniques are discussed in the performance information about
improving concurrency.
2. Follow the recommendations for application design for concurrency.
Related tasks
Programming for concurrency (DB2 Performance Monitoring and Tuning
Guide)
Programming your applications for concurrency (DB2 Performance
Monitoring and Tuning Guide)
18 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Designing your application for recovery
If your application fails or DB2 terminates abnormally, you need to ensure the
integrity of any data that was manipulated in your application. You should
consider possible recovery situations when you design your application.
To design your application for recovery:
1. Put any changes that logically need to be made at the same time in the same
unit of work. This action ensures that in case DB2 terminates abnormally or
your application fails, the data is left in a consistent state.
A unit of work is a logically distinct procedure that contains steps that change
the data. If all the steps complete successfully, you want the data changes to
become permanent. But, if any of the steps fail, you want all modified data to
return to the original value before the procedure began. For example, suppose
two employees in the sample table DSN8910.EMP exchange offices. You need to
exchange their office phone numbers in the PHONENO column. You need to
use two UPDATE statements to make each phone number current. Both
statements, taken together, are a unit of work. You want both statements to
complete successfully. For example, if only one statement is successful, you
want both phone numbers rolled back to their original values before attempting
another update.
2. Consider how often you should commit any changes to the data.
If your program abends or the system fails, DB2 backs out all uncommitted
data changes. Changed data returns to its original condition without interfering
with other system activities.
For IMS and CICS applications, if the system fails, DB2 data does not always
return to a consistent state immediately. DB2 does not process indoubt data
(data that is neither uncommitted nor committed) until you restart IMS or the
CICS attachment facility. To ensure that DB2 and IMS are synchronized, restart
both DB2 and IMS. To ensure that DB2 and CICS are synchronized, restart both
DB2 and the CICS attachment facility.
3. Consider whether your application should intercept abends.
If your application intercepts abends, DB2 commits work, because it is unaware
that an abend has occurred. If you want DB2 to roll back work automatically
when an abend occurs in your program, do not let the program or run-time
environment intercept the abend. If your program uses Language
Environment

, and you want DB2 to roll back work automatically when an


abend occurs in the program, specify the run-time options
ABTERMENC(ABEND) and TRAP(ON).
4. For TSO applications only: Issue COMMIT statements before you connect to
another DBMS.
If the system fails at this point, DB2 cannot know whether your transaction is
complete. In this case, as in the case of a failure during a one-phase commit
operation for a single subsystem, you must make your own provision for
maintaining data integrity.
5. For TSO applications only: Determine if you want to provide an abend exit
routine in your program.
If you provide this routine, it must use tracking indicators to determine if an
abend occurs during DB2 processing. If an abend does occur when DB2 has
control, you must allow task termination to complete. DB2 detects task
termination and terminates the thread with the ABRT parameter. Do not re-run
the program.
Chapter 1. Planning for and designing DB2 applications 19
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Allowing task termination to complete is the only action that you can take for
abends that are caused by the CANCEL command or by DETACH. You cannot
use additional SQL statements at this point. If you attempt to execute another
SQL statement from the application program or its recovery routine,
unexpected errors can occur.
Related concepts
Unit of work (DB2 SQL Reference)
Unit of work in TSO
Applications that use the TSO attachment facility can explicitly define units of
work by using the SQL COMMIT and ROLLBACK statements.
In TSO applications, a unit of work starts when the first updates of a DB2 object
occur. A unit of work ends when one of the following conditions occurs:
v The program issues a subsequent COMMIT statement. At this point in the
processing, your program has determined that the data is consistent; all data
changes that were made since the previous commit point were made correctly.
v The program issues a subsequent ROLLBACK statement. At this point in the
processing, your program has determined that the data changes were not made
correctly and, therefore, should not be permanent. A ROLLBACK statement
causes any data changes that were made since the last commit point to be
backed out.
v The program terminates and returns to the DSN command processor, which
returns to the TSO Terminal Monitor Program (TMP).
The first and third conditions in the preceding list are called a commit point. A
commit point occurs when you issue a COMMIT statement or your program
terminates normally.
Related reference
COMMIT (DB2 SQL Reference)
ROLLBACK (DB2 SQL Reference)
Unit of work in CICS
CICS applications can explicitly define units of work by using the CICS
SYNCPOINT command. Alternatively, units of work are defined implicitly by
several logic breaking points.
All the processing that occurs in your program between two commit points is
known as a logical unit of work (LUW) or unit of work. In CICS applications, a
unit of work is marked as complete by a commit or synchronization (sync) point,
which is defined in one of following ways:
v Implicitly at the end of a transaction, which is signaled by a CICS RETURN
command at the highest logical level.
v Explicitly by CICS SYNCPOINT commands that the program issues at logically
appropriate points in the transaction.
v Implicitly through a DL/I PSB termination (TERM) call or command.
v Implicitly when a batch DL/I program issues a DL/I checkpoint call. This call
can occur when the batch DL/I program shares a database with CICS
applications through the database sharing facility.
For example, consider a program that subtracts the quantity of items sold from an
inventory file and then adds that quantity to a reorder file. When both transactions
20 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
complete (and not before) and the data in the two files is consistent, the program
can then issue a DL/I TERM call or a SYNCPOINT command. If one of the steps
fails, you want the data to return to the value it had before the unit of work began.
That is, you want it rolled back to a previous point of consistency. You can achieve
this state by using the SYNCPOINT command with the ROLLBACK option.
By using a SYNCPOINT command with the ROLLBACK option, you can back out
uncommitted data changes. For example, a program that updates a set of related
rows sometimes encounters an error after updating several of them. The program
can use the SYNCPOINT command with the ROLLBACK option to undo all of the
updates without giving up control.
The SQL COMMIT and ROLLBACK statements are not valid in a CICS
environment. You can coordinate DB2 with CICS functions that are used in
programs, so that DB2 and non-DB2 data are consistent.
Planning for program recovery in IMS programs
To be prepared for recovery situations for IMS programs that access DB2 data, you
need to make several design decisions that are specific to IMS programs. These
decisions are in addition to the general recommendations that you should follow
when designing your application for recovery.
Both IMS and DB2 handle recovery in an IMS application program that accesses
DB2 data. IMS coordinates the process, and DB2 handles recovery for DB2 data.
To plan for program recovery in IMS programs:
1. For a program that processes messages as its input, decide whether to specify
single-mode or multiple-mode transactions on the TRANSACT statement of the
APPLCTN macro for the program.
Single-mode
Indicates that a commit point in DB2 occurs each time the program
issues a call to retrieve a new message. Specifying single-mode can
simplify recovery; if the program abends, you can restart the program
from the most recent call for a new message. When IMS restarts the
program, the program starts by processing the next message.
Multiple-mode
Indicates that a commit point occurs when the program issues a
checkpoint call or when it terminates normally. Those two events are
the only times during the program that IMS sends the programs
output messages to their destinations. Because fewer commit points are
processed in multiple-mode programs than in single-mode programs,
multiple-mode programs could perform slightly better than
single-mode programs. When a multiple-mode program abends, IMS
can restart it only from a checkpoint call. Instead of having only the
most recent message to reprocess, a program might have several
messages to reprocess. The number of messages to process depends on
when the program issued the last checkpoint call.
DB2 does some processing with single- and multiple-mode programs. When a
multiple-mode program issues a call to retrieve a new message, DB2 performs
an authorization check and closes all open cursors in the program.
2. Decide whether to issue checkpoint calls (CHKP) and if so, how often to issue
them. Each call indicates to IMS that the program has reached a sync point and
establishes a place in the program from which you can restart the program.
Chapter 1. Planning for and designing DB2 applications 21
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Consider the following factors when deciding when to use checkpoint calls:
v How long it takes to back out and recover that unit of work. The program
must issue checkpoints frequently enough to make the program easy to back
out and recover.
v How long database resources are locked in DB2 and IMS.
v For multiple-mode programs: How you want the output messages grouped.
Checkpoint calls establish how a multiple-mode program groups its output
messages. Programs must issue checkpoints frequently enough to avoid
building up too many output messages.
Restriction: You cannot use SQL COMMIT and ROLLBACK statements in the
DB2 DL/I batch support environment, because IMS coordinates the unit of
work.
3. Issue CLOSE CURSOR statements before any checkpoint calls or GU calls to
the message queue, not after.
4. After any checkpoint calls, set the value of any special registers that were reset
if their values are needed after the checkpoint:
A CHKP call causes IMS to sign on to DB2 again, which resets the special
registers that are shown in the following table.
Table 4. Special registers that are reset by a checkpoint call.
Special register
Value to which it is reset after a checkpoint
call
CURRENT PACKAGESET blanks
CURRENT SERVER blanks
CURRENT SQLID blanks
CURRENT DEGREE 1
5. After any commit points, reopen the cursors that you want and re-establish
positioning
6. Decide whether to specify the WITH HOLD option for any cursors. This option
determines whether the program retains the position of the cursor in the DB2
database after you issue IMS CHKP calls. You always lose the program
database positioning in DL/I after an IMS CHKP call.
The program database positioning in DB2 is affected according to the following
criteria:
v If you do not specify the WITH HOLD option for a cursor, you lose the
position of that cursor.
v If you specify the WITH HOLD option for a cursor and the application is
message-driven, you lose the position of that cursor.
v If you specify the WITH HOLD option for a cursor and the application is
operating in DL/I batch or DL/I BMP, you retain the position of that cursor.
7. Use IMS rollback calls, ROLL and ROLB, to back out DB2 and DL/I changes to
the last commit point. These options have the following differences:
ROLL
Specifies that all changes since the last commit point are to be backed out
and the program is to be terminated. IMS terminates the program with user
abend code U0778 and without a storage dump.
When you issue a ROLL call, the only option you supply is the call
function, ROLL.
22 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
||
||
||
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ROLLB
Specifies that all changes since the last commit point are to be backed out
and control is to be returned to the program so that it can continue
processing.
A ROLB call has the following options:
v The call function, ROLB
v The name of the I/O PCB
How ROLL and ROLB calls effect DL/I changes in a batch environment
depends on the IMS system log and back out options that are specified, as
shown in the following table.
Table 5. Effects of ROLL and ROLLB calls on DL/I changes in a batch environment
Options specified
Result Rollback call System log option Backout option
ROLL tape any DL/I does not back
out updates, and
abend U0778 occurs.
DB2 backs out
updates to the
previous checkpoint.
disk BKO=NO
disk BKO=YES DL/I backs out
updates, and abend
U0778 occurs. DB2
backs out updates to
the previous
checkpoint.
Chapter 1. Planning for and designing DB2 applications 23
|
|
|
|
|
|
|
|
|
|
||
|
||||
||||
|
|
|
|
|
||
|||
|
|
|
|
|
Table 5. Effects of ROLL and ROLLB calls on DL/I changes in a batch
environment (continued)
Options specified
Result Rollback call System log option Backout option
ROLB tape any DL/I does not back
out updates, and an
AL status code is
returned in the PCB.
DB2 backs out
updates to the
previous checkpoint.
The DB2 DL/I
support causes the
application program
to abend when ROLB
fails.
disk BKO=NO
disk BKO=YES DL/I backs out
database updates,
and control is passed
back to the
application program.
DB2 backs out
updates to the
previous checkpoint.
Restriction: You
cannot specify the
address of an I/O
area as one of the
options on the call; if
you do, your
program receives an
AD status code.
However, you must
have an I/O PCB for
your program.
Specify CMPAT=YES
on the CMPAT
keyword in the
PSBGEN statement
for your programs
PSB.
Related concepts
Checkpoints in IMS programs on page 26
Unit of work in IMS online programs
IMS applications can explicitly define units of work by using a CHKP, SYNC,
ROLL, or ROLB call, or, for single-mode transactions, a GU call.
In IMS, a unit of work starts when one of the following events occurs:
v When the program starts
v After a CHKP, SYNC, ROLL, or ROLB call has completed
v For single-mode transactions, when a GU call is issued to the I/O PCB
A unit of work ends when one of the following events occurs:
24 Application Programming and SQL Guide
|
|
|
||||
||||
|
|
|
|
|
|
|
|
|
|
|
||
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
v The program issues either a subsequent CHKP or SYNC call, or, for single-mode
transactions, a GU call to the I/O PCB. At this point in the processing, the data
is consistent. All data changes that were made since the previous commit point
are made correctly.
v The program issues a subsequent ROLB or ROLL call. At this point in the
processing, your program has determined that the data changes are not correct
and, therefore, that the data changes should not become permanent.
v The program terminates.
Restriction: The SQL COMMIT and ROLLBACK statements are not valid in an
IMS environment.
A commit point occurs in a program as the result of any one of the following
events:
v The program terminates normally. Normal program termination is always a
commit point.
v The program issues a checkpoint call. Checkpoint calls are a programs means of
explicitly indicating to IMS that it has reached a commit point in its processing.
v The program issues a SYNC call. A SYNC call is a Fast Path system service call
to request commit-point processing. You can use a SYNC call only in a
non-message-driven Fast Path program.
v For a program that processes messages as its input, a commit point can occur
when the program retrieves a new message. This behavior depends on the mode
that you specify in the APPLCTN macro for the program:
If you specify single-mode transactions, a commit point in DB2 occurs each
time the program issues a call to retrieve a new message.
If you specify multiple-mode transactions or you do not specify a mode, a
commit point occurs when the program issues a checkpoint call or when it
terminates normally.
At the time of a commit point, the following actions occur:
v IMS and DB2 can release locks that the program has held since the last commit
point. Releasing these locks makes the data available to other application
programs and users. However, when you define a cursor as WITH HOLD in a
BMP program, DB2 holds those locks until the cursor closes or the program
ends.
v DB2 closes any open cursors that the program has been using.
v IMS and DB2 make the programs changes to the database permanent.
v If the program processes messages, IMS sends the output messages that the
application program produces to their final destinations. Until the program
reaches a commit point, IMS holds the programs output messages at a
temporary destination.
If the program abends before reaching the commit point, the following actions
occur:
v Both IMS and DB2 back out all the changes the program has made to the
database since the last commit point.
v IMS deletes any output messages that the program has produced since the last
commit point (for nonexpress PCBs).
v If the program processes messages, people at terminals and other application
programs receive information from the terminating application program.
Chapter 1. Planning for and designing DB2 applications 25
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
If the system fails, a unit of work resolves automatically when DB2 and IMS batch
programs reconnect. Any indoubt units of work are resolved at reconnect time.
Specifying checkpoint frequency in IMS programs
A checkpoint indicates a commit point in IMS programs. You should specify
checkpoint frequency in your program in a way that makes changing it easy in
case the frequency you initially specify is not right.
To specify checkpoint frequency in IMS programs:
1. Use a counter in your program to keep track of one of the following items:
v Elapsed time
v The number of root segments that your program accesses
v The number of updates that your program performs
2. Issue a checkpoint call after a certain time interval, number of root segments, or
number of updates.
Checkpoints in IMS programs:
Issuing checkpoint calls releases locked resources and establishes a place in the
program from which you can restart the program. The decision about whether
your program should issue checkpoints (and if so, how often) depends on your
program.
Generally, the following types of programs should issue checkpoint calls:
v Multiple-mode programs
v Batch-oriented BMPs
v Nonmessage-driven Fast Path programs. (These programs can use a special Fast
Path call, but they can also use symbolic checkpoint calls.)
v Most batch programs
v Programs that run in a data sharing environment. (Data sharing makes it
possible for online and batch application programs in separate IMS systems, in
the same or separate processors, to access databases concurrently. Issuing
checkpoint calls frequently in programs that run in a data sharing environment
is important, because programs in several IMS systems access the database.)
You do not need to issue checkpoints in the following types of programs:
v Single-mode programs
v Database load programs
v Programs that access the database in read-only mode (defined with the
processing option GO during a PSBGEN) and are short enough to restart from
the beginning
v Programs that, by their nature, must have exclusive use of the database
A CHKP call causes IMS to perform the following actions:
v Inform DB2 that the changes that your program made to the database can
become permanent. DB2 makes the changes to DB2 data permanent, and IMS
makes the changes to IMS data permanent.
v Send a message that contains the checkpoint identification that is given in the
call to the system console operator and to the IMS master terminal operator.
v Return the next input message to the programs I/O area if the program
processes input messages. In MPPs and transaction-oriented BMPs, a checkpoint
call acts like a call for a new message.
26 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
v Sign on to DB2 again.
Programs that issue symbolic checkpoint calls can specify as many as seven data
areas in the program that is to be restored at restart. DB2 always recovers to the
last checkpoint. You must restart the program from that point.
If you use symbolic checkpoint calls, you can use a restart call (XRST) to restart a
program after an abend. This call restores the programs data areas to the way they
were when the program terminated abnormally, and it restarts the program from
the last checkpoint call that the program issued before terminating abnormally.
Restriction: For BMP programs that process DB2 databases, you can restart the
program only from the latest checkpoint and not from any checkpoint, as in IMS.
Checkpoints in MPPs and transaction-oriented BMPs
In single-mode programs, checkpoint calls and message retrieval calls (called
get-unique calls) both establish commit points. The checkpoint calls retrieve input
messages and take the place of get-unique calls. BMPs that access non-DL/I
databases and MPPs can issue both get unique calls and checkpoint calls to
establish commit points. However, message-driven BMPs must issue checkpoint
calls rather than get-unique calls to establish commit points, because they can
restart from a checkpoint only. If a program abends after issuing a get-unique call,
IMS backs out the database updates to the most recent commit point, which is the
get-unique call.
In multiple-mode BMPs and MPPs, the only commit points are the checkpoint calls
that the program issues and normal program termination. If the program abends
and it has not issued checkpoint calls, IMS backs out the programs database
updates and cancels the messages that it has created since the beginning of the
program. If the program has issued checkpoint calls, IMS backs out the programs
changes and cancels the output messages it has created since the most recent
checkpoint call.
Checkpoints in batch-oriented BMPs
If a batch-oriented BMP does not issue checkpoints frequently enough, IMS can
abend that BMP or another application program for one of the following reasons:
v Other programs cannot get to the data that they need within a specified amount
of time.
If a BMP retrieves and updates many database records between checkpoint calls,
it can monopolize large portions of the databases and cause long waits for other
programs that need those segments. (The exception to this situation is a BMP
with a processing option of GO; IMS does not enqueue segments for programs
with this processing option.) Issuing checkpoint calls releases the segments that
the BMP has enqueued and makes them available to other programs.
v Not enough storage is available for the segments that the program has read and
updated.
If IMS is using program isolation enqueuing, the space that is needed to
enqueue information about the segments that the program has read and updated
must not exceed the amount of storage that is defined for the IMS system. (The
amount of storage available is specified during IMS system definition. ) If a BMP
enqueues too many segments, the amount of storage that is needed for the
enqueued segments can exceed the amount of available storage. In that case,
Chapter 1. Planning for and designing DB2 applications 27
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
IMS terminates the program abnormally. You then need to increase the
programs checkpoint frequency before rerunning the program.
When you issue a DL/I CHKP call from an application program that uses DB2
databases, IMS processes the CHKP call for all DL/I databases, and DB2 commits
all the DB2 database resources. No checkpoint information is recorded for DB2
databases in the IMS log or the DB2 log. The application program must record
relevant information about DB2 databases for a checkpoint, if necessary. One way
to record such information is to put it in a data area that is included in the DL/I
CHKP call.
Performance might be slowed by the commit processing that DB2 does during a
DL/I CHKP call, because the program needs to re-establish position within a DB2
database. The fastest way to re-establish a position in a DB2 database is to use an
index on the target table, with a key that matches one-to-one with every column in
the SQL predicate.
Recovering data in IMS programs
In an online IMS system, recovery and restart are part of the IMS system. For a
batch region, your locations operational procedures control recovery and restart.
To recover data in IMS programs:
Take one or more of the following actions depending on the type of program:
Program type Recommended action
DL/I batch applications Use the DL/I batch backout utility to back
out DL/I changes. DB2 automatically backs
out changes whenever the application
program abends.
Applications that use symbolic checkpoints Use a restart call (XRST) to restart a program
after an abend. This call restores the
programs data areas to the way they were
when the program terminated abnormally,
and it restarts the program from the last
checkpoint call that the program issued
before terminating abnormally.
BMP programs that access DB2 databases Restart the program from the latest
checkpoint.
Restriction: You can restart the program
only from the latest checkpoint and not from
any checkpoint, as in IMS.
Applications that use online IMS systems No action needed. Recovery and restart are
part of the IMS system
Applications that reside in the batch region Follow your locations operational
procedures to control recovery and restart.
Undoing selected changes within a unit of work by using
savepoints
Savepoints enable you to undo selected changes within a unit of work. Your
application can set any number of savepoints and then specify a specific savepoint
to indicate which changes to undo within the unit of work.
To undo selected changes within a unit of work by using savepoints:
28 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
||
|
|
|
||
|
|
|
|
|
|
||
|
|
|
|
||
|
||
|
|
|
|
|
|
|
|
1. Set any savepoints by using SQL SAVEPOINT statements. Savepoints set a
point to which you can undo changes within a unit of work.
Consider the following abilities and restrictions when setting savepoints:
v You can set a savepoint with the same name multiple times within a unit of
work. Each time that you set the savepoint, the new value of the savepoint
replaces the old value.
v If you do not want a savepoint to have different values within a unit of
work, use the UNIQUE option in the SAVEPOINT statement. If an
application executes a SAVEPOINT statement with the same name as a
savepoint that was previously defined as unique, an SQL error occurs.
v If you set a savepoint before you execute a CONNECT statement, the scope
of that savepoint is the local site. If you set a savepoint after you execute the
CONNECT statement, the scope of that savepoint is the site to which you are
connected.
v When savepoints are active, which they are until the unit of work completes,
you cannot access remote sites by using three-part names or aliases for
three-part names. You can, however, use DRDA

access with explicit


CONNECT statements.
v You cannot use savepoints in global transactions, triggers, user-defined
functions, or stored procedures that are nested within triggers or
user-defined functions.
2. Specify the changes that you want to undo within a unit of work by using the
SQL ROLLBACK TO SAVEPOINT statement.
DB2 undoes all changes since the specified savepoint. If you do not specify a
savepoint name, DB2 rolls back work to the most recently created savepoint.
3. Optional: If you no longer need a savepoint, delete it by using the SQL
RELEASE SAVEPOINT statement.
Recommendation: If you no longer need a savepoint before the end of a
transaction, release it. Otherwise, savepoints are automatically released at the
end of a unit of work. Releasing savepoints is essential if you need to use
three-part names to access remote locations, because you cannot perform this
action while savepoints are active.
Examples
Rolling back to the most recently created savepoint: When the ROLLBACK TO
SAVEPOINT statement is executed in the following code, DB2 rolls back work to
savepoint B.
EXEC SQL SAVEPOINT A;
...
EXEC SQL SAVEPOINT B;
...
EXEC SQL ROLLBACK TO SAVEPOINT;
Setting savepoints during distributed processing: An application performs the
following tasks:
1. Sets savepoint C1.
2. Does some local processing.
3. Executes a CONNECT statement to connect to a remote site.
4. Sets savepoint C2.
Chapter 1. Planning for and designing DB2 applications 29
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Because savepoint C1 is set before the application connects to a remote site,
savepoint C1 is known only at the local site. However, because savepoint C2 is set
after the application connects to the remote site, savepoint C2 is known only at the
remote site.
Setting multiple savepoints with the same name: Suppose that the following
actions occur within a unit of work:
1. Application A sets savepoint S.
2. Application A calls stored procedure P.
3. Stored procedure P sets savepoint S.
4. Stored procedure P executes the following statement: ROLLBACK TO SAVEPOINT S
When DB2 executes the ROLLBACK statement, DB2 rolls back work to the
savepoint that was set in the stored procedure, because that value is the most
recent value of savepoint S.
Related reference
SAVEPOINT (DB2 SQL Reference)
ROLLBACK (DB2 SQL Reference)
RELEASE SAVEPOINT (DB2 SQL Reference)
Planning for recovery of table spaces that are not logged
To suppress logging, you can specify the NOT LOGGED option when you create
or alter a table space. However, because logs are generally used in recovery,
planning for recovery of table spaces for which changes are not logged requires
some additional planning.
Although you can plan for recovery, you still need to take some corrective actions
after any system failures to recover the data and fix any affected table spaces. For
example, if a table space that is not logged was open for update at the time that
DB2 terminates, the subsequent restart places that table space in LPL and marks it
with RECOVER-pending status. You need to take corrective action to clear the
RECOVER-pending status.
To plan for recovery of table spaces that are not logged:
1. Ensure that you can recover lost data by performing one of the following
actions:
v Ensure that you have a data recovery source that does not rely on a log
record to recreate any lost data.
v Limit modifications that are not logged to easily repeatable changes that can
be quickly repeated.
2. Avoid placing a table space that is not logged in a RECOVER-pending status.
The following actions place a table space in RECOVER-pending status:
v Issuing a ROLLBACK statement or ROLLBACK TO SAVEPOINT statement
after modifying a table in a table space that is not logged.
v Causing duplicate keys or referential integrity violations when you modify a
table space that is not logged.
If the table space is placed in RECOVER-pending status, it is unavailable until
you manually fix it.
3. For table spaces that are not logged and have associated LOB or XML table
spaces, take image copies as a recovery set.
30 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
This action ensures that the base table space and all the associated LOB or XML
table spaces are copied at the same point in time. A subsequent RECOVER TO
LASTCOPY operation for the entire set results in consistent data across the base
table space and all of the associated LOB and XML table spaces.
Related tasks
Clearing the RECOVER-pending status (DB2 Administration Guide)
Related reference
RECOVER (DB2 Utility Guide and Reference)
Designing your application to access distributed data
For applications that access data on another database management system (DBMS)
other than your local system, use DRDA access. You should also consider the
limitations and recommendations for such programs when designing them.
If your system is not already set up to use DRDA access, you must first prepare
your system to use DRDA access. One of the tools that can help you during this
process is the private to DRDA protocol REXX

tool (DSNTP2DP).
To design your application to access distributed data:
1. Ensure that the appropriate authorization ID has been granted authorization at
the remote server to connect to that server and use resources from it.
2. If your application contains SQL statements that run at the requester, include at
the requester a database request module (DBRM) that is bound either directly
to a plan or to a package that is included in the plans package list.
3. Include a package at the remote server for any SQL statements that run at that
server.
4. For TSO and batch applications that update data at a remote server, ensure that
one of the following conditions is true:
v No other connections exist.
v All existing connections are to servers that are restricted to read-only
operations.
Restriction: If neither of these conditions are met, the application is restricted
to read-only operations.
If one of these conditions is met, and if the first connection in a logical unit of
work is to a server that supports two-phase commit, that server and all servers
that support two-phase commit can update data. However, if the first
connection is to a server that does not support two-phase commit, only that
server is allowed to update data.
5. For programs that access at least one restricted system, ensure that your
program does not violate any of the limitations for accessing restricted systems.
A restricted system is a DBMS that does not implement two-phase commit
processing.
Accessing restricted systems has the following limitations:
v For programs that access CICS or IMS, you cannot update data on restricted
systems.
v Within a unit of work, you cannot update a restricted system after updating
a non-restricted system.
v Within a unit of work, if you update a restricted system, you cannot update
any other systems.
Chapter 1. Planning for and designing DB2 applications 31
|
|
|
|
|
|
|
|
If you are accessing a mixture of systems, some of which might be restricted,
you can perform the following actions:
v Read from any of the systems at any time.
v Update any one system many times in one unit of work.
v Update many systems, including CICS or IMS, in one unit of work, provided
that none of them is a restricted system. If the first system you update in a
unit of work is not restricted, any attempt to update a restricted system in
that unit of work returns an error.
v Update one restricted system in a unit of work, provided that you do not try
to update any other system in the same unit of work. If the first system you
update in a unit of work is restricted, any attempt to update any other
system in that unit of work returns an error.
Related tasks
Preparing your system for DRDA access (DB2 Installation Guide)
Related reference
The private to DRDA protocol REXX tool (DSNTP2DP) (DB2 Installation
Guide)
Remote servers and distributed data
Distributed data is data that resides on a database management system (DBMS)
other than your local system. Your local DBMS is the one on which you bind your
application plan. All other DBMSs are remote.
If you are requesting services from a remote DBMS, that DBMS is a server, and
your local system is a requester or client.
Your application can be connected to many DBMSs at one time; the one that is
currently performing work is the current server. When the local system is
performing work, it also is called the current server.
A remote server can be physically remote, or it can be another subsystem of the
same operating system that your local DBMS runs under. A remote server might be
an instance of DB2 for z/OS, or it might be an instance of one of another product.
A DBMS, whether local or remote, is known to your DB2 system by its location
name. The location name of a remote DBMS is recorded in the communications
database.
Related tasks
Choosing names for the local subsystem (DB2 Installation Guide)
Advantages of DRDA access
Programs that access distributed data should use DRDA access. Not only does
DRDA access have many advantages over DB2 private protocol access, but also
private protocol support will be removed in a future release of DB2.
DRDA access has the following advantages over DB2 private protocol access:
v Integration: DRDA access is available to all DBMSs that implement Distributed
Relational Database Architecture

(DRDA). Those DBMSs include supported


releases of DB2 for z/OS, other members of the DB2 family of IBM products,
and many products of other companies.
DB2 private protocol access is available only to supported releases of DB2 for
z/OS.
32 Application Programming and SQL Guide
v SQL compatibility: DRDA access allows any SQL statement that the server can
execute.
DB2 private protocol access supports only data manipulation statements:
INSERT, UPDATE, DELETE, SELECT, OPEN, FETCH, and CLOSE. In addition,
you cannot use any syntax of an SQL statement that was introduced after DB2
Version 5. You also cannot invoke user-defined functions and stored procedures
or use LOBs or distinct types.
v Reduced network load: DRDA access uses a more compact format for sending
data over the network. This process improves the performance on slow network
links.
v Reduced bind processing: A DBRM for statements that are executed by DRDA
access is bound to a package at the server only once. Those statements can
include PREPARE and EXECUTE, so your application can accept dynamic
statements that are to be executed at the server.
Queries that are executed by DB2 private protocol access are bound at the server
whenever they are first executed in a unit of work. Repeated binds can reduce
the performance of a query that is executed often.
v Stored procedures: You can use stored procedures with DRDA access. Because
stored procedures require no message traffic over the network while they are
running, they reduce the biggest obstacle to high performance for distributed
data.
v Scrollable cursors: You can use scrollable cursors if you use DRDA access.
v Savepoints: You can set savepoints only if you use DRDA access with explicit
CONNECT statements. If you set a savepoint and then execute an SQL
statement with a three-part name, an SQL error occurs.
Related tasks
Undoing selected changes within a unit of work by using savepoints on page
28
Preparing for coordinated updates to two or more data
sources
Two or more updates are coordinated if they must all commit or all roll back in the
same unit of work.
This situation is common in banking. Suppose that an amount is subtracted from
one account and added to another. The two actions must either both commit or
both roll back at the end of the unit of work.
To prepare for coordinated updates to two or more data sources:
Ensure that all systems that your program accesses implement two-phase commit
processing. This processing ensures that updates to two or more DBMSs are
coordinated automatically.
For example, DB2 and IMS, and DB2 and CICS, jointly implement a two-phase
commit process. You can update an IMS database and a DB2 table in the same unit
of work. If a system or communication failure occurs between committing the
work on IMS and on DB2, the two programs restore the two systems to a
consistent point when activity resumes.
You cannot do true coordinated updates within a DBMS that does not implement
two-phase commit processing, because DB2 prevents you from updating such a
DBMS and any other system within the same unit of work. In this context, update
includes the statements INSERT, UPDATE, MERGE, DELETE, CREATE, ALTER,
DROP, GRANT, REVOKE, RENAME, COMMENT, and LABEL.
Chapter 1. Planning for and designing DB2 applications 33
However, if you cannot implement two-phase commit processing on all systems
that your program accesses, you can simulate the effect of coordinated updates by
performing the following actions:
1. Update one system and commit that work.
2. Update the second system and commit its work.
3. Ensure that your program has code to undo the first update if a failure occurs
after the first update is committed and before the second update is committed.
No automatic provision exists for bringing the two systems back to a consistent
point.
Related concepts
Two-phase commit process (DB2 Administration Guide)
Forcing restricted system rules in your program
A restricted system is a DBMS that does not implement two-phase commit
processing. These systems have a number of update restrictions. You can restrict
your program completely to the rules for these restricted systems, regardless of
whether the program is accessing restricted systems or non-restricted systems.
Accessing restricted systems has the following limitations:
v For programs that access CICS or IMS, you cannot update data on restricted
systems.
v Within a unit of work, you cannot update a restricted system after updating a
non-restricted system.
v Within a unit of work, if you update a restricted system, you cannot update any
other systems.
To force restricted system rules in your program:
When you prepare your program, specify the SQL processing option
CONNECT(1). This option applies type 1 CONNECT statement rules.
Restriction: Do not use packages that are precompiled with the CONNECT(1)
option and packages that are precompiled with the CONNECT(2) option in the
same package list. The first CONNECT statement that is executed by your
program determines which rules are in effect for the entire execution: type 1 or
type 2. If your program attempts to execute a later CONNECT statement that is
precompiled with the other type, DB2 returns an error.
Related concepts
Options for SQL statement processing on page 867
Maximizing the performance of an application that accesses
distributed data
They key to improving the performance of applications that access remote data is
to limit the number of network transmissions. You should consider if any of the
recommendations for reducing these transmissions makes sense for your
application.
To maximize the performance of an application that accesses distributed data:
1. Write any queries that access distributed data according to the following
recommendations to limit the number of messages that these queries send over
the network:
34 Application Programming and SQL Guide
v Reduce the number of columns and rows in the result table by keeping the
select lists as short as possible and using the WHERE, GROUP BY, and
HAVING clauses to eliminate unwanted data at the remote server.
v Specify the FOR FETCH ONLY or FOR READ ONLY clause when possible.
Retrieving thousands of rows as a continuous stream is reasonable. Sending a
separate message for each one can be significantly slower.
However, be aware the a query that is sent to a remote subsystem almost
always takes longer to execute than the same query that accesses tables of the
same size on the local subsystem for the following reasons:
v Overhead processing, including startup, negotiating session limits, and, for
DB2 private protocol access, the bind required at the remote location
v The time required to send messages across the network
2. For any of the following situations, use the OPTIMIZE FOR n ROWS clause in
your SELECT statements and query result sets from stored procedures:
v The application fetches only a small number of rows from the query result
set.
v The application fetches a large number of rows from a read-only query.
v The application rarely closes the SQL cursor before fetching the entire query
result set.
v The application does not issue statements other than the FETCH statement to
the DB2 server while the SQL cursor is open.
v The application does not execute FETCH statements for multiple cursors that
are open concurrently and defined with the OPTIMIZE FOR n ROWS clause.
v The application does not need to scroll randomly through the data.
The OPTIMIZE FOR n ROWS clause limits the number of data rows that the
server returns on each DRDA network transmission.
Restriction: This clause has no effect on scrollable cursors.
In a DRDA environment, if you specify 1, 2, or 3 for n , DB2 uses the value 16
(instead of n) for network blocking and prefetches 16 rows. As a result,
network usage is more efficient even though DB2 uses the small value of n for
query optimization.
For example, the following SQL statement causes DB2 to prefetch 16 rows of
the result table even though n has a value of 1.
SELECT * FROM EMP OPTIMIZE FOR 1 ROW ONLY;
3. For queries that have potentially large result tables, but need only a limited
number of rows, specify the FETCH FIRST n ROWS ONLY clause. This clause
limits the number of rows that are returned to a client program.
For example, suppose that you need only one row of the result table. You can
add the FETCH FIRST 1 ROW ONLY clause, as shown in the following
example:
SELECT * FROM EMP OPTIMIZE FOR 1 ROW ONLY FETCH FIRST 1 ROW ONLY;
In this case, the FETCH FIRST 1 ROW ONLY clause prevents 15 unnecessary
prefetches.
4. If your program accesses LOB columns in a remote table, use the following
techniques to minimize the number of bytes that are transferred between the
client and the server:
v Use LOB locators instead of LOB host variables.
If you need to store only a portion of a LOB value at the client, or if your
client program manipulates the LOB data but does not need a copy of it,
Chapter 1. Planning for and designing DB2 applications 35
LOB locators are a good choice. When a client program retrieves a LOB
column from a server into a locator, DB2 transfers only the 4-byte locator
value to the client, not the entire LOB value.
v Use stored procedure result sets.
When you return LOB data to a client program from a stored procedure, use
result sets rather than passing the LOB data to the client in parameters.
Using result sets to return data causes less LOB materialization and less
movement of data among address spaces.
v Set the CURRENT RULES special register to DB2.
When a DB2 server receives an OPEN request for a cursor, the server uses
the value in the CURRENT RULES special register to determine the type of
host variables that the associated statement uses to retrieve LOB values. If
you specify a value of DB2 for the CURRENT RULES special register before
you perform a CONNECT, and the first FETCH statement for the cursor uses
a LOB locator to retrieve LOB column values, DB2 lets you use only LOB
locators for all subsequent FETCH statements for that column until you close
the cursor. If the first FETCH statement uses a host variable, DB2 lets you
use only host variables for all subsequent FETCH statements for that column
until you close the cursor. However, if you set the value of CURRENT
RULES to STD, DB2 lets you use the same open cursor to fetch a LOB
column into either a LOB locator or a host variable.
Although a value of STD for the CURRENT RULES special register gives you
more programming flexibility when you retrieve LOB data, you get better
performance if you use a value of DB2. With the STD option, the server must
send and receive network messages for each FETCH statement to indicate
whether the data that is being transferred is a LOB locator or a LOB value.
With the DB2 option, the server knows the size of the LOB data after the first
FETCH, so an extra message about LOB data size is unnecessary. The server
can send multiple blocks of data to the requester at one time, which reduces
the total time for data transfer.
For example, suppose that an end user wants to browse through a large set of
employee records and look at pictures of only a few of those employees. At the
server, you set the CURRENT RULES special register to DB2. In the application,
you declare and open a cursor to select employee records. The application then
fetches all picture data into 4-byte LOB locators. Because DB2 knows that 4
bytes of LOB data is returned for each FETCH statement, DB2 can fill the
network buffers with locators for many pictures. When a user wants to see a
picture for a particular person, the application can retrieve the picture from the
server by assigning the value that is referenced by the LOB locator to a LOB
host variable. This situation is implemented in the following code:
SQL TYPE IS BLOB my_blob[1M];
SQL TYPE IS BLOB AS LOCATOR my_loc;
.
.
.
FETCH C1 INTO :my_loc; /* Fetch BLOB into LOB locator */
.
.
.
SET :my_blob = :my_loc; /* Assign BLOB to host variable */
Restriction: You must use DRDA access to access LOB columns in a remote
table.
5. Minimize the use of parameter markers.
When using DRDA access, DB2 can streamline the processing of dynamic
queries that do not have parameter markers. When a DB2 requester encounters
a PREPARE statement for such a query, it anticipates that the application is
going to open a cursor. DB2 therefore sends a single message to the server that
36 Application Programming and SQL Guide
contains a combined request for the PREPARE, DESCRIBE, and OPEN
operations. A server that receives this message sequence returns a reply
message sequence that includes the output from the PREPARE, DESCRIBE, and
OPEN operations. As a result, the number of network messages sent and
received for these operations is reduced from two to one. DB2 combines
messages for these queries regardless of whether the bind option
DEFER(PREPARE) is specified.
6. Ensure that each cursor meets one of the following conditions when possible,
so that DB2 uses block fetch to minimize the number of messages that are sent
across the network:
v The cursor is declared with either the FOR FETCH ONLY or FOR READ
ONLY clause.
v The cursor is a non-scrollable cursor, and the result table of the cursor is
read-only.
v The cursor is a scrollable cursor that is declared as INSENSITIVE, and the
result table of the cursor is read-only.
v The cursor is a scrollable cursor that is declared as SENSITIVE, the result
table of the cursor is read-only, and the value of the CURRENTDATA bind
option is NO.
v The result table of the cursor is not read-only, but the cursor is ambiguous,
and the value of the CURRENTDATA bind option is NO.
A cursor is ambiguous when any of the following conditions are true:
It is not defined with the clauses FOR FETCH ONLY, FOR READ ONLY,
or FOR UPDATE.
It is not defined on a read-only result table.
It is not the target of a WHERE CURRENT clause on an SQL UPDATE or
DELETE statement.
It is in a plan or package that contains the SQL statements PREPARE or
EXECUTE IMMEDIATE.
7. For ODBC and JDBC applications, use the rowset parameter to limit the
number of rows that are returned from a fetch operation.
If a DRDA requester sends the rowset parameter to a DB2 server, the server
performs the following actions:
v Returns no more than the number of rows in the rowset parameter
v Returns extra query blocks if the value of the EXTRA BLOCKS SRV field on
the DISTRIBUTED DATA FACILITY PANEL 2 installation panel on the server
allows extra query blocks to be returned
v Processes the FETCH FIRST n ROWS ONLY clause, if it is specified
v Does not process the OPTIMIZE FOR n ROWS clause
8. Use the recommended values for the following bind options:
Table 6. Recommended bind option values for applications that access distributed data
Bind option Recommended value and actions Reason
CURRENTDATA CURRENTDATA(NO) Use this bind option to force block fetch for
ambiguous queries.
Chapter 1. Planning for and designing DB2 applications 37
Table 6. Recommended bind option values for applications that access distributed data (continued)
Bind option Recommended value and actions Reason
DBPROTOCOL DBPROTOCOL(DRDA) If the value of the installation default
database protocol is not DRDA, use this
bind option to cause DB2 to use DRDA
access to execute SQL statements with
three-part names. Statements that use
DRDA access perform better at execution
time for the following reasons:
v Binding occurs when the package is
bound, not during program execution.
v DB2 does not destroy static statement
information at commit time, as it does
with DB2 private protocol access. With
DRDA access, if a commit occurs
between two executions of a statement,
DB2 does not need to prepare the
statement twice.
ISOLATION Anything but ISOLATION (RR) When possible, do not bind application
plans and packages with ISOLATION(RR).
If your application does not need to
reference rows that it has already read,
another isolation level might reduce lock
contention and message overhead during
commit processing.
KEEPDYNAMIC KEEPDYNAMIC(YES) Use this bind option to improve
performance for queries that use cursors
that are defined with the WITH HOLD
option. With KEEPDYNAMIC(YES), DB2
automatically closes the cursor when no
more data exists for retrieval. The client
does not need to send a network message
to tell DB2 to close the cursor.
NODEFER and DEFER DEFER(PREPARE) This option reduces network traffic, because
the PREPARE and EXECUTE statements
and responses are transmitted together.
38 Application Programming and SQL Guide
Table 6. Recommended bind option values for applications that access distributed data (continued)
Bind option Recommended value and actions Reason
PKLIST and NOPKLIST PKLIST
Specify the package collections for this bind
option according to the following
recommendations:
v Reduce the number of packages per
collection that DB2 must search. The
following example specifies only one
package in each collection:
PKLIST(S1.COLLA.PGM1, S1.COLLB.PGM2)
v Reduce the number of package
collections at each location that DB2 must
search. The following example specifies
only one package collection at each
location:
PKLIST(S1.COLLA.*, S2.COLLB.*)
v Reduce the number of collections that are
used for each application. The following
example specifies only one collection to
search:
PKLIST(*.COLLA.*)
Requirement: When you specify the
DEFER(PREPARE) bind option with DRDA
access, the package that contains the
statements whose preparation you want to
defer must be the first qualifying entry in
the package search sequence that DB2 uses.
For example, assume that the package list
for a plan contains two entries:
PKLIST(LOCB.COLLA.*, LOCB.COLLB.*)
If the intended package is in collection
COLLB, ensure that DB2 searches that
collection first by executing the following
SQL statement:
SET CURRENT PACKAGESET = 'COLLB';
Alternatively, you can list COLLB first in
the PKLIST bind option:
PKLIST(LOCB.COLLB.*, LOCB.COLLA.*)
For the NODEFER(PREPARE) bind option,
the collections in the package list can be in
any order, but if the package is not found
in the first qualifying PKLIST entry,
significant network overhead might result
from DB2 searching through the list.
The order in which you specify package
collections in a package list can affect the
performance of your application program.
When a local instance of DB2 attempts to
execute an SQL statement at a remote
server, the local DB2 subsystem must
determine which package collection the
SQL statement is in. DB2 must send a
message to the server to request that the
server check each collection ID for the SQL
statement until the statement is found or no
more collection IDs are in the package list.
You can reduce the amount of network
traffic, and thereby improve performance,
by reducing the number of package
collections that each server must search.
As an alternative to specifying the package
collections on the PKLIST bind option, you
can specify the package collection that is
associated with an SQL statement in your
application program. Execute the SET
CURRENT PACKAGESET statement before
you execute an SQL statement to tell DB2
which package collection to search for the
statement.
Chapter 1. Planning for and designing DB2 applications 39
Table 6. Recommended bind option values for applications that access distributed data (continued)
Bind option Recommended value and actions Reason
REOPT Use the following guidelines to decide
which option to choose:
v Use the REOPT(AUTO) option when the
following conditions are true:
You are using the dynamic statement
cache.
You want DB2 to decide if a new
access path is needed.
Your dynamic SQL statements are
executed many times with possibly
different input variables.
Similar input variables tend to be
executed consecutively.
v Use the REOPT(ALWAYS) option on only
packages or plans that contain statements
that perform poorly because of a bad
access path. If you specify
REOPT(ALWAYS) when you bind a plan
that contains statements that use DB2
private protocol access to access remote
data, DB2 prepares those statements
twice.
v Use the REOPT(ONCE) option when the
following conditions are true:
You are using the dynamic statement
cache.
You have plans or packages that
contain dynamic SQL statements that
perform poorly because of access path
selection.
Your dynamic SQL statements are
executed many times with possibly
different input variables.
v Use the REOPT(NONE) option when you
bind a plan or package that contains
statements that use DB2 private protocol
access.
Because of performance costs when DB2
reoptimizes the access path at run time,
minimize reoptimization when possible.
Related concepts
Block fetching result sets (DB2 Performance Monitoring and Tuning Guide)
How DB2 identifies packages at run time on page 888
Related tasks
Fetching a limited number of rows: FETCH FIRST n ROWS ONLY (DB2
Performance Monitoring and Tuning Guide)
Saving storage when manipulating LOBs by using LOB locators on page 677
Related reference
fetch-first-clause (DB2 SQL Reference)
BIND and REBIND options (DB2 Command Reference)
40 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
The effect of the OPTIMIZE FOR n ROWS clause in distributed
applications
You can specify the OPTIMIZE FOR n ROWS clause to improve the performance of
certain queries. For queries that access distributed data, this clause can have a
significant performance impact, because it helps limit the amount of data that is
sent over the network and the number of network transmissions.
When you specify the OPTIMIZE FOR n ROWS clause in your query, the number
of rows that DB2 transmits on each network transmission depends on the
following factors:
v If n rows of the SQL result set fit within a single DRDA query block, a DB2
server can send n rows to any DRDA client. In this case, DB2 sends n rows in
each network transmission until the entire query result set is returned.
v If n rows of the SQL result set exceed a single DRDA query block, the number of
rows that are contained in each network transmission depends on the clients
DRDA software level and configuration. The following conditions apply:
If the client does not support extra query blocks, the DB2 server automatically
reduces the value of n to match the number of rows that fit within a DRDA
query block.
If the client supports extra query blocks, the DRDA client can choose to
accept multiple DRDA query blocks in a single data transmission. DRDA
allows the client to establish an upper limit on the number of DRDA query
blocks in each network transmission.
The number of rows that a DB2 server sends is the smaller of the following
values:
- n rows
- the number of rows that fit within the maximum number of extra DRDA
query blocks that the DB2 server returns to a client in a single network
transmission. (This value is specified in the EXTRA BLOCKS SRV field on
installation panel DSNTIP5 at the DB2 server.)
- the number of rows that fit within the clients extra query block limit,
which is obtained from the DDM MAXBLKEXT parameter that is received
from the client. (When DB2 acts as a DRDA client, the DDM MAXBLKEXT
parameter is set to the value of EXTRA BLOCKS REQ on installation panel
DSNTIP5.)
Depending on the value that you specify for n, the OPTIMIZE FOR n ROWS clause
can improve performance in the following ways:
v If n is less than the number of rows that fit in the DRDA query block,
OPTIMIZE FOR n ROWS can improve performance by preventing the DB2
server from fetching rows that might never be used by the DRDA client
application.
v If n is greater than the number of rows that fit in a DRDA query block,
OPTIMIZE FOR n ROWS lets the DRDA client request multiple blocks of query
data on each network transmission. This use of OPTIMIZE FOR n ROWS can
significantly improve elapsed time for applications that download large amounts
of data.
Although the OPTIMIZE FOR n ROWS clause can improve performance, this same
function can degrade performance if you do not use it properly. The following
examples demonstrate the performance problems that can occur when you do not
use this clause judiciously.
Chapter 1. Planning for and designing DB2 applications 41
In the following figure, the DRDA client opens a cursor and fetches rows from the
cursor. At some point before all rows in the query result set are returned, the
application issues an SQL INSERT statement.
In this case, DB2 uses normal DRDA message blocking, which has the following
advantages over the message blocking that is used for the OPTIMIZE FOR n
ROWS clause:
v If the application issues an SQL statement other than FETCH (for example, an
INSERT statement in this case), the DRDA client can transmit the SQL statement
immediately, because the DRDA connection is not in use after the SQL OPEN.
v The DRDA query block size places an upper limit on the number of rows that
are fetched unnecessarily. If the SQL application closes the cursor before fetching
all the rows in the query result set, the server fetches only the number of rows
that fit in one query block, which is 100 rows of the result set.
In the following figure, the DRDA client opens a cursor and fetches rows from the
cursor by using OPTIMIZE FOR n ROWS clause. Both the DRDA client and the
DB2 server are configured to support multiple DRDA query blocks. At some time
before the end of the query result set, the application issues an SQL INSERT.
Server processes
INSERT statement
DRDA client DB2 server
DECLARE C1 CURSOR
FOR SELECT * FROM T1
FOR FETCH ONLY;
OPEN C1;
FETCH C1 INTO ...;
FETCH C1 INTO ...;
INSERT INTO ...;
SQL cursor is opened
Query block with 100
rows is returned
Figure 1. Message flows without the OPTIMIZE FOR n ROWS clause
42 Application Programming and SQL Guide
Because the query uses the OPTIMIZE FOR n ROWS clause, the DRDA connection
is not available when the SQL INSERT is issued. The connection is still being used
to receive the DRDA query blocks for 1000 rows of data. This situation causes the
following performance problems:
v Application elapsed time can increase if the DRDA client waits for a large query
result set to be transmitted before the DRDA connection can be used for other
SQL statements. In this example, the SQL INSERT statement is delayed because
of a large query result set.
v If the application closes the cursor before fetching all the rows in the SQL result
set, the server might fetch a large number of rows unnecessarily.
Related concepts
Minimizing overhead for retrieving few rows: OPTIMIZE FOR n ROWS (DB2
Performance Monitoring and Tuning Guide)
Related reference
optimize-for-clause (DB2 SQL Reference)
Fast implicit close
When you specify the FETCH FIRST n ROWS ONLY clause in a distributed query,
DB2 might use a fast implicit close to improve performance. Fast implicit close is the
process of DB2 closing a cursor after prefetching thenth row or when no more
rows are to be returned.
DRDA client DB2 server
DECLARE C1 CURSOR
FOR SELECT * FROM T1
OPTIMIZE FOR
1000 ROWS;
OPEN C1;
FETCH C1 INTO ...;
FETCH C1 INTO ...;
.
.
.
INSERT INTO ...;
SQL cursor is opened
Query block with 100
rows is returned
Query block with 100
rows is returned
Query block with 100
rows is returned
Query block with 100
rows is returned
Query block with 100
rows is returned
Query block with 100
rows is returned
Query block with 100
rows is returned
Query block with 100
rows is returned
Query block with 100
rows is returned
Query block with 100
rows is returned
Server processes
INSERT statement
Figure 2. Message flows with the OPTIMIZE FOR 1000 ROWS clause
Chapter 1. Planning for and designing DB2 applications 43
Fast implicit close can improve query performance, because it saves an additional
network transmission between the client and the server.
DB2 uses fast implicit close when all of the following conditions are true:
v The query uses limited block fetch.
v The query does not retrieve any LOBs.
v The cursor is not a scrollable cursor.
v Either of the following conditions is true:
The cursor is defined with the WITH HOLD option, and the package or plan
that contains the cursor is bound with the KEEPDYNAMIC(YES) option.
The cursor is not defined with the WITH HOLD option.
Related concepts
Block fetching result sets (DB2 Performance Monitoring and Tuning Guide)
44 Application Programming and SQL Guide
Chapter 2. Connecting to DB2 from your application program
Application programs communicate to DB2 through an attachment facility. You
must invoke an attachment facility, either implicitly or explicitly, before your
program can interact with DB2.
You can use the following attachment facilities in a z/OS environment:
CICS attachment facility
Use this facility to access DB2 from CICS application programs.
IMS attachment facility
Use this facility to access DB2 from IMS application programs.
Time Sharing Option (TSO) attachment facility
Use this facility in a TSO or batch environment to communicate to a local
DB2 subsystem. This facility invokes the DSN command processor.
Call attachment facility (CAF)
Use this facility as an alternative to the TSO attachment facility when your
application needs tight control over the session environment.
Resource Recovery Services attachment facility (RRSAF)
Use this facility for stored procedures that run in a WLM-established
address space or as an alternative to the CAF. This facility has more
capabilities than CAF.
For distributed applications, use the distributed data facility (DDF).
Requirement: Ensure that any application that requests DB2 services satisfies the
following environment characteristics, regardless of the attachment facility that you
use:
v The application must be running in TCB mode. SRB mode is not supported.
v An application task cannot have any Enabled Unlocked Task (EUT) functional
recovery routines (FRRs) active when requesting DB2 services. If an EUT FRR is
active, the DB2 functional recovery can fail, and your application can receive
some unpredictable abends.
v Different attachment facilities cannot be active concurrently within the same
address space. Specifically, the following requirements exist:
An application must not use CAF or RRSAF in an CICS or IMS address
space.
An application that runs in an address space that has a CAF connection to
DB2 cannot connect to DB2 by using RRSAF.
An application that runs in an address space that has an RRSAF connection to
DB2 cannot connect to DB2 by using CAF.
An application cannot invoke the z/OS AXSET macro after executing the CAF
CONNECT call and before executing the CAF DISCONNECT call.
v One attachment facility cannot start another. For example, your CAF or RRSAF
application cannot use DSN, and a DSN RUN subcommand cannot call your
CAF or RRSAF application.
Copyright IBM Corp. 1983, 2008 45
v The language interface modules for CAF and RRSAF, DSNALI and DSNRLI, are
shipped with the linkage attributes AMODE(31) and RMODE(ANY). If your
applications load CAF or RRSAF below the 16-MB line, you must link-edit
DSNALI or DSNRLI again.
Related concepts
DB2 attachment facilities (Introduction to DB2 for z/OS)
Distributed data facility (Introduction to DB2 for z/OS)
Invoking the call attachment facility
Invoke the call attachment facility (CAF) when you want your application program
to establish and control its own connection to DB2. Applications that use CAF can
explicitly control the state of their connections to DB2 by using connection
functions that CAF supplies.
Before you can invoke CAF, perform the following actions:
v Ensure that the CAF language interface (DSNALI) is available.
v Ensure that your application satisfies the requirements for programs that access
CAF.
v Ensure that your application satisfies the general environment characteristics for
connecting to DB2.
v Ensure that you are familiar with the following z/OS concepts and facilities:
The CALL macro and standard module linkage conventions
Program addressing and residency options (AMODE and RMODE)
Creating and controlling tasks; multitasking
Functional recovery facilities such as ESTAE, ESTAI, and FRRs
Asynchronous events and TSO attention exits (STAX)
Synchronization techniques such as WAIT/POST.
Applications that use CAF can be written in assembler language, C, COBOL,
Fortran, and PL/I. When choosing a language to code your application in, consider
the following restrictions:
v If you need to use z/OS macros (ATTACH, WAIT, POST, and so on), use a
programming language that supports them or embed them in modules that are
written in assembler language.
v The CAF TRANSLATE function is not available in Fortran. To use this function,
code it in a routine that is written in another language, and then call that routine
from Fortran.
Recommendations: For IMS and DSN applications, consider the following
recommendations:
v For IMS batch applications, do not use CAF. Instead use the DB2 DL/I batch
support. Although it is possible for IMS batch applications to access DB2
databases through CAF, that method does not coordinate the commitment of
work between the IMS and DB2 systems.
v For DSN applications, do not use CAF unless you provide an application
controller to manage the DSN application and replace any needed DSN
functions. You might also have to change the application to communicate
connection failures to the controller correctly. Running DSN applications with
CAF is not advantageous, and the loss of DSN services can affect how well your
program runs.
To invoke CAF:
46 Application Programming and SQL Guide
Perform one of the following actions:
v Explicitly invoke CAF by including in your program CALL DSNALI statements
with the appropriate options.
The first option is a CAF connection function, which describes the action that
you want CAF to take. The effect of any function depends in part on what
functions the program has already run.
Requirement: For C and PL/I applications, you must also include in your
program the compiler directives that are listed in the following table, because
DSNALI is an assembler language program.
Table 7. Compiler directives to include in C and PL/I applications that contain CALL DSNALI
statements
Language Compiler directive to include
C #pragma linkage(dsnali, OS)
C++ extern "OS" {
int DSNALI(
char * functn,
...); }
PL/I DCL DSNALI ENTRY OPTIONS(ASM,INTER,RETCODE;
v Implicitly invoke CAF by including SQL statements or IFI calls in your program
just as you would in any program. The CAF facility establishes the connections
to DB2 with the default values for the subsystem name and plan name.
Restriction: If your program can make its first SQL call from different modules
with different DBRMs, you cannot use a default plan name and thus, you cannot
implicitly invoke CAF. Instead, you must explicitly invoke CAF by using the
OPEN function.
Requirement: If your application includes both SQL and IFI calls, you must
issue at least one SQL call before you issue any IFI calls. This action ensures that
your application uses the correct plan.
Although doing so is not recommended, you can run existing DSN applications
with CAF by allowing them to make implicit connections to DB2. For DB2 to
make an implicit connection successfully, the plan name for the application must
be the same as the member name of the database request module (DBRM) that
DB2 produced when you precompiled the source program that contains the first
SQL call. You must also substitute the DSNALI language interface module for
the TSO language interface module, DSNELI.
If you do not specify the return code and reason code parameters in your CAF
calls or you invoked CAF implicitly, CAF puts a return code in register 15 and a
reason code in register 0.
To determine if an implicit connection was successful, the application program
should examine the return and reason codes immediately after the first executable
SQL statement in the application program by performing one of the following
actions:
v Examining registers 0 and 15 directly.
v Examining the SQLCA, and if the SQLCODE is -991, obtain the return and
reason code from the message text. The return code is the first token, and the
reason code is the second token.
If the implicit connection was successful, the application can examine the
SQLCODE for the first, and subsequent, SQL statements.
Chapter 2. Connecting to DB2 from your application program 47
Examples
Example of a CAF configuration: The following figure shows an conceptual
example of invoking and using CAF. The application contains statements to load
DSNALI, DSNHLI2, and DSNWLI2. The application accesses DB2 by using the
CAF Language Interface. It calls DSNALI to handle CAF requests, DSNWLI to
handle IFI calls, and DSNHLI to handle SQL calls.
Sample programs that use CAF: You can find a sample assembler program
(DSN8CA) and a sample COBOL program (DSN8CC) that use the CAF in library
prefix.SDSNSAMP. A PL/I application (DSN8SPM) calls DSN8CA, and a COBOL
application (DSN8SCM) calls DSN8CC.
Related concepts
DB2 sample applications on page 1029
Related reference
Application CAF
Language
Interface
CAF
Mainline
Code
LOAD DSNALI
LOAD DSNHLI2
LOAD DSNWLI2
Load
CALL DSNALI
( CONNECT )
( OPEN )
( CLOSE )
( DISCONNECT )
Call
DSNALI
(Process
connection
requests)
CALL DSNWLI
CALL DSNHLI
(SQL calls)
DSNHLI (dummy
application
entry point)
DSNWLI (dummy
application
entry point)
CALL DSNHLI2
(Transfer calls
to real CAF SQL
entry point)
CALL DSNWLI2
(Transfer calls
to real CAF
IFI)
DSNWLI
DSNHLI2
(Process
SQL stmts)
DB2
(IFI calls)
Figure 3. Sample call attachment facility configuration
48 Application Programming and SQL Guide
CAF connection functions on page 58
Call attachment facility
An attachment facility enables programs to communicate with DB2. The call
attachment facility (CAF) provides such a connection for programs that run in
z/OS batch, TSO foreground, and TSO background and need tight control over the
session environment.
A program that uses CAF can perform the following actions:
v Access DB2 from z/OS address spaces where TSO, IMS, or CICS do not exist.
v Access DB2 from multiple z/OS tasks in an address space.
v Access the DB2 IFI.
v Run when DB2 is down.
Restriction: The application cannot run SQL when DB2 is down.
v Run with or without the TSO terminal monitor program (TMP).
v Run without being a subtask of the DSN command processor or of any DB2
code.
v Run above or below the 16-MB line. (The CAF code resides below the line.)
v Establish an explicit connection to DB2, through a CALL interface, with control
over the exact state of the connection.
v Establish an implicit connection to DB2, by using SQL statements or IFI calls
without first calling CAF, with a default plan name and subsystem identifier.
v Verify that the application is using the correct release of DB2.
v Supply event control blocks (ECBs), for DB2 to post, that signal startup or
termination.
v Intercept return codes, reason codes, and abend codes from DB2 and translate
them into messages as desired.
Any task in an address space can establish a connection to DB2 through CAF. Only
one connection can exist for each task control block (TCB). A DB2 service request
that is issued by a program that is running under a given task is associated with
that tasks connection to DB2. The service request operates independently of any
DB2 activity under any other task.
Each connected task can run a plan. Multiple tasks in a single address space can
specify the same plan, but each instance of a plan runs independently from the
others. A task can terminate its plan and run a different plan without fully
breaking its connection to DB2.
CAF does not generate task structures.
When you design your application, consider that using multiple simultaneous
connections can increase the possibility of deadlocks and DB2 resource contention.
A tracing facility provides diagnostic messages that aid in debugging programs
and diagnosing errors in the CAF code. In particular, attempts to use CAF
incorrectly cause error messages in the trace stream.
Restriction: CAF does not provide attention processing exits or functional recovery
routines. You can provide whatever attention handling and functional recovery
Chapter 2. Connecting to DB2 from your application program 49
your application needs, but you must use ESTAE/ESTAI type recovery routines
and not Enabled Unlocked Task (EUT) FRR routines.
Properties of CAF connections
CAF enables programs to communicate with DB2. A CAF connection joins any task
in an address space to DB2.
The connection that CAF makes with DB2 has the basic properties that are listed in
the following table.
Table 8. Properties of CAF connections
Property Value Comments
Connection name DB2CALL You can use the DISPLAY
THREAD command to list
CAF applications that have
the connection name
DB2CALL.
Connection type BATCH BATCH connections use a
single phase commit process
that is coordinated by DB2.
Application programs can
also control when statements
are committed by using the
SQL COMMIT and
ROLLBACK statements.
Authorization IDs Authorization IDs that are
associated with the address
space
DB2 establishes authorization
IDs for each tasks connection
when it processes that
connection. For the BATCH
connection type, DB2 creates
a list of authorization IDs
based on the authorization ID
that is associated with the
address space. This list is the
same for every task. A
location can provide a DB2
connection authorization exit
routine to change the list of
IDs.
Scope CAF processes connections as
if each task is entirely
isolated. When a task
requests a function, the CAF
passes the functions to DB2
and is unaware of the
connection status of other
tasks in the address space.
However, the application
program and the DB2
subsystem are aware of the
connection status of multiple
tasks in an address space.
none
If a connected task terminates normally before the CLOSE function deallocates the
plan, DB2 commits any database changes that the thread made since the last
commit point. If a connected task abends before the CLOSE function deallocates
the plan, DB2 rolls back any database changes since the last commit point. In
50 Application Programming and SQL Guide
either case, DB2 deallocates the plan, if necessary, and terminates the tasks
connection before it allows the task to terminate.
If DB2 abnormally terminates while an application is running, the application is
rolled back to the last commit point. If DB2 terminates while processing a commit
request, DB2 either commits or rolls back any changes at the next restart. The
action taken depends on the state of the commit request when DB2 terminates.
Related concepts
Connection routines and sign-on routines (DB2 Administration Guide)
Attention exit routines for CAF
An attention exit routine enables you to regain control from DB2 during
long-running or erroneous requests. CAF has no attention exit routines, but you
can provide your own if necessary.
An attention exit routine works by detaching the TCB that is currently waiting on
an SQL or IFI request to complete. After the TCB is detached, DB2 detects the
resulting abend and performs termination processing for that task. The termination
processing includes any necessary rollback of transactions.
You can provide your own attention exit routines. However, your routine might
not get control if you request attention while DB2 code is running, because DB2
uses enabled unlocked task (EUT) functional recovery routines (FRRs).
Recovery routines for CAF
You can use abend recovery routines and functional recovery routines (FRRs) to
handle unexpected errors. An abend recovery routine controls what happens when
an abend occurs while DB2 has control. A functional recovery routine can obtain
information about and recover from program errors.
The CAF has no abend recovery routines, but you can provide your own. Any
abend recovery routines that you provide must use tracking indicators to
determine if an abend occurred during DB2 processing. If an abend occurs while
DB2 has control, the recovery routine can take one of the following actions:
v Allow task termination to complete. Do not retry the program. DB2 detects task
termination and terminates the thread with the ABRT parameter. You lose all
database changes back to the last sync point or commit point.
This action is the only action that you can take for abends that are caused by the
CANCEL command or by DETACH. You cannot use additional SQL statements.
If you attempt to execute another SQL statement from the application program
or its recovery routine, you receive a return code of +256 and a reason code of
X00F30083.
v In an ESTAE routine, issue a CLOSE function call with the ABRT parameter
followed by a DISCONNECT function call. The ESTAE exit routine can retry so
that you do not need to reinstate the application task.
FRRs must comply with the following requirements and restrictions:
v You can use only enabled unlocked task (EUT) FRRs in your routines that call
DB2. The standard z/OS functional recovery routines (FRRs) apply to only code
that runs in service request block (SRB) mode, and DB2 does not support calls
from SRB mode routines.
v Do not have an EUT FRR active when using CAF, processing SQL requests, or
calling IFI. With z/OS, if you have an active EUT FRR, all DB2 requests fail,
including the initial CONNECT or OPEN request. The requests fail because DB2
Chapter 2. Connecting to DB2 from your application program 51
always creates an ARR-type ESTAE, and z/OS does not allow the creation of
ARR-type ESTAEs when an FRR is active.
v An EUT FRR cannot retry failing DB2 requests. An EUT FRR retry bypasses
ESTAE routines from DB2. The next DB2 request of any type, including a
DISCONNECT request, fails with a return code of +256 and a reason code of
X00F30050.
Making the CAF language interface (DSNALI) available
Before you can invoke the call attachment facility (CAF), you must first make
DSNALI available.
Part of CAF is a DB2 load module, DSNALI, which is also known as the CAF
language interface. DSNALI has the alias names DSNHLI2 and DSNWLI2. The
module has five entry points: DSNALI, DSNHLI, DSNHLI2, DSNWLI, and
DSNWLI2. These entry points serve the following functions:
v Entry point DSNALI handles explicit DB2 connection service requests.
v DSNHLI and DSNHLI2 handle SQL calls. Use DSNHLI if your application
program link-edits DSNALI. Use DSNHLI2 if your application program loads
DSNALI.
v DSNWLI and DSNWLI2 handle IFI calls. Use DSNWLI if your application
program link-edits DSNALI. Use DSNWLI2 if your application program loads
DSNALI.
To make DSNALI available:
1. Decide which of the following two methods you want to use to make DSNALI
available:
v Explicitly issuing LOAD requests when your program runs.
By explicitly loading the DSNALI module, you beneficially isolate the
maintenance of your application from future IBM maintenance to the
language interface. If the language interface changes, the change will
probably not affect your load module.
v Including the DSNALI module in your load module when you link-edit your
program.
If you do not need explicit calls to DSNALI for CAF functions, link-editing
DSNALI into your load module has some advantages. When you include
DSNALI during the link-edit, you do not need to code a dummy DSNHLI
entry point in your program or specify the precompiler option ATTACH.
Module DSNALI contains an entry point for DSNHLI, which is identical to
DSNHLI2, and an entry point DSNWLI, which is identical to DSNWLI2.
A disadvantage to link-editing DSNALI into your load module is that any
IBM maintenance to DSNALI requires a new link-edit of your load module.
2. Depending on the method that you chose in step 1, perform one of the
following actions:
v If you want to explicitly issue LOAD requests when your program runs:
In your program, issue z/OS LOAD service requests for entry points
DSNALI and DSNHLI2. If you use IFI services, you must also load
DSNWLI2. The entry point addresses that LOAD returns are saved for later
use with the CALL macro. Indicate to DB2 which entry point to use in one of
the following two ways:
Specify the precompiler option ATTACH(CAF).
This option causes DB2 to generate calls that specify entry point
DSNHLI2.
52 Application Programming and SQL Guide
Restriction: You cannot use this option if your application is written in
Fortran.
Code a dummy entry point named DSNHLI within your load module.
If you do not specify the precompiler option ATTACH, the DB2
precompiler generates calls to entry point DSNHLI for each SQL request.
The precompiler does not know about and is independent of the different
DB2 attachment facilities. When the calls generated by the DB2
precompiler pass control to DSNHLI, your code that corresponds to the
dummy entry point must preserve the option list that was passed in R1
and specify the same option list when it calls DSNHLI2.
v If you want to include the DSNALI module in your load module when
you link-edit your program:
Include DSNALI in your load module during a link-edit step. The module
must be in a load module library, which is included either in the SYSLIB
concatenation or another INCLUDE library that is defined in the linkage
editor JCL. Because all language interface modules contain an entry point
declaration for DSNHLI, the linkage editor JCL must contain an INCLUDE
linkage editor control statement for DSNALI; for example, INCLUDE
DB2LIB(DSNALI). By coding these options, you avoid inadvertently picking up
the wrong language interface module.
Related concepts
Examples of invoking CAF on page 71
Requirements for programs that use CAF
The call attachment facility (CAF) enables programs to communicate with DB2.
Before you invoke CAF in your program, ensure that your program satisfies any
requirements for using CAF.
When you write programs that use CAF, ensure that they meet the following
requirements:
v The program accounts for the size of the CAF code. The CAF code requires
about 16 KB of virtual storage per address space and an additional 10 KB for
each TCB that uses CAF.
v If your local environment intercepts and replaces the z/OS LOAD SVC that CAF
uses, you must ensure that your version of LOAD manages the load list element
(LLE) and contents directory entry (CDE) chains like the standard z/OS LOAD
macro. CAF uses z/OS SVC LOAD to load two modules as part of the
initialization after your first service request. Both modules are loaded into
fetch-protected storage that has the job-step protection key.
v If you use CAF from IMS batch, you must write data to only one system in any
one unit of work. If you write to both systems within the same unit, a system
failure can leave the two databases inconsistent with no possibility of automatic
recovery. To end a unit of work in DB2, execute the SQL COMMIT statement. To
end a unit of work in IMS, issue the SYNCPOINT command.
You can prepare application programs to run in CAF similar to how you prepare
applications to run in other environments, such as CICS, IMS, and TSO. You can
prepare a CAF application either in the batch environment or by using the DB2
program preparation process. You can use the program preparation system either
through DB2I or through the DSNH CLIST.
Related tasks
Chapter 11, Preparing an application to run on DB2 for z/OS, on page 851
Chapter 2. Connecting to DB2 from your application program 53
How CAF modifies the content of registers
If you do not specify the return code and reason code parameters in your CAF
function calls or you invoke CAF implicitly, CAF puts a return code in register 15
and a reason code in register 0. The contents of registers 2 through 14 are
preserved across calls.
The following table lists the standard calling conventions for registers R1, R13, R14,
and R15.
Table 9. Standard usage of registers R1, R13, R14, and R15
Register Usage
R1 CALL DSNALI parameter list pointer
R13 Address of callers save area
R14 Callers return address
R15 CAF entry point address
Your CAF program should respect these register conventions.
CAF also supports high-level languages that cannot examine the contents of
individual registers.
Related concepts
CALL DSNALI statement parameter list on page 55
Implicit connections to CAF
If the CAF language interface (DSNALI) is available and you do not explicitly
specify CALL DSNALI statements in your application, CAF initiates implicit
CONNECT and OPEN requests to DB2. These requests are subject to the same DB2
return codes and reason codes as explicitly specified requests.
Implicit connections use the following defaults:
Subsystem name
The default name that is specified in the module DSNHDECP. CAF uses
the installation default DSNHDECP, unless your own DSNHDECP module
is in a library in a STEPLIB statement of a JOBLIB concatenation or in the
link list. In a data sharing group, the default subsystem name is the group
attachment name.
Be certain that you know what the default name is and that it names the
specific DB2 subsystem you want to use.
Plan name
The member name of the database request module (DBRM) that DB2
produced when you precompiled the source program that contains the first
SQL call.
Different types of implicit connections exist. The simplest is for an application to
call neither the CONNECT nor OPEN functions. You can also use the CONNECT
function only or the OPEN function only. Each of these calls implicitly connects
your application to DB2. To terminate an implicit connection, you must use the
proper calls.
Related concepts
Summary of CAF behavior on page 57
54 Application Programming and SQL Guide
CALL DSNALI statement parameter list
The CALL DSNALI statement explicitly invokes CAF. When you include CALL
DSNALI statements in your program, you must specify all parameters that come
before the return code parameter.
For CALL DSNALI statements, use a standard z/OS CALL parameter list. Register
1 points to a list of fullword addresses that point to the actual parameters. The last
address must contain a 1 in the high-order bit.
In CALL DSNALI statements, you cannot omit any of parameters that come before
the return code parameter by coding zeros or blanks. No defaults exist for those
parameters for explicit connection requests. Defaults are provided for only implicit
connections. All parameters starting with the return code parameter are optional.
When you want to use the default value for a parameter but specify subsequent
parameters, code the CALL DSNALI statement as follows:
v For all languages except assembler language, code zero for that parameter in the
CALL DSNALI statement. For example, suppose that you are coding a
CONNECT call in a COBOL program, and you want to specify all parameters
except the return code parameter. You can write a statement similar to the
following statement:
CALL 'DSNALI' USING FUNCTN SSID TECB SECB RIBPTR
BY CONTENT ZERO BY REFERENCE REASCODE SRDURA EIBPTR.
v For assembler language, code a comma for that parameter in the CALL DSNALI
statement. For example, to specify all optional parameters except the return code
parameter write a statement similar to the following statement:
CALL DSNALI,(FUNCTN,SSID,TERMECB,STARTECB,RIBPTR,,REASCODE,SRDURA,EIBPTR,
GROUPOVERRIDE)
The following figure shows a sample parameter list structure for the CONNECT
function.
Chapter 2. Connecting to DB2 from your application program 55
The preceding figure illustrates how you can omit parameters for the CALL
DSNALI statement to control the return code and reason code fields after a
CONNECT call. You can terminate the parameter list at any of the following
points. These termination points apply to all CALL DSNALI statement parameter
lists.
1. Terminates the parameter list without specifying the parameters retcode,
reascodeand srdura and places the return code in register 15 and the reason code
in register 0.
Terminating the parameter list at this point ensures compatibility with CAF
programs that require a return code in register 15 and a reason code in register
0.
2. Terminates the parameter list after the parameter retcode and places the return
code in the parameter list and the reason code in register 0.
Terminating the parameter list at this point enables the application program to
take action, based on the return code, without further examination of the
associated reason code.
3. Terminates the parameter list after the parameter reascode and places the return
code and the reason code in the parameter list.
Terminating the parameter list at this point provides support to high-level
languages that are unable to examine the contents of individual registers.
Figure 4. The parameter list for a CONNECT call
56 Application Programming and SQL Guide
If you code your CAF application in assembler language, you can specify the
reason code parameter and omit the return code parameter.
4. Terminates the parameter list after the parameter srdura.
If you code your CAF application in assembler language, you can specify this
parameter and omit the retcode and reascode parameters.
5. Terminates the parameter list after the parameter eibptr.
If you code your CAF application in assembler language, you can specify this
parameter and omit the retcode, reascode, or srdura parameters.
6. Terminates the parameter list after the parameter groupoverride.
If you code your CAF application in assembler language, you can specify this
parameter and omit the retcode, reascode,srdura, or eibptr parameters.
Even if you specify that the return code be placed in the parameter list, it is also
placed in register 15 to accommodate high-level languages that support special
return code processing.
Related concepts
How CAF modifies the content of registers on page 54
Summary of CAF behavior
The effect of any CAF function depends in part on what functions the program has
already run. You should plan the CAF function calls that your program makes to
avoid any errors and major structural problems in your application.
The following table summarizes CAF behavior after various inputs from
application programs. The top row lists the possible CAF functions that programs
can call. The first column lists the tasks most recent history of connection requests.
For example, the value CONNECT followed by OPEN in the first column means
that the task issued CONNECT and then OPEN with no other CAF calls in
between. The intersection of a row and column shows the effect of the next call if
it follows the corresponding connection history. For example, if the call is OPEN
and the connection history is CONNECT, the effect is OPEN; the OPEN function is
performed. If the call is SQL and the connection history is empty (meaning that the
SQL call is the first CAF function the program), the effect is that implicit
CONNECT and OPEN functions are performed, followed by the SQL function.
Table 10. Effects of CAF calls, as dependent on connection history
Previous
function
Next function
CONNECT OPEN SQL CLOSE DISCONNECT TRANSLATE
Empty: first call CONNECT OPEN CONNECT,
OPEN, followed
by the SQL or
IFI call
Error 203
1
Error 204
1
Error 205
1
CONNECT Error 201
1
OPEN OPEN, followed
by the SQL or
IFI call
Error 203
1
DISCONNECT TRANSLATE
CONNECT
followed by
OPEN
Error 201
1
Error 202
1
The SQL or IFI
call
CLOSE
2
DISCONNECT TRANSLATE
CONNECT
followed by SQL
or IFI call
Error 201
1
Error 202
1
The SQL or IFI
call
CLOSE
2
DISCONNECT TRANSLATE
Chapter 2. Connecting to DB2 from your application program 57
Table 10. Effects of CAF calls, as dependent on connection history (continued)
Previous
function
Next function
CONNECT OPEN SQL CLOSE DISCONNECT TRANSLATE
OPEN Error 201
1
Error 202
1
The SQL or IFI
call
CLOSE
2
Error 204
1
TRANSLATE
SQL or IFI call Error 201
1
Error 202
1
The SQL or IFI
call
CLOSE
2
Error 204
1
TRANSLATE
3
Notes:
1. An error is shown in this table as Error nnn. The corresponding reason code is
X00C10nnn. The message number is DSNAnnnI or DSNAnnnE.
2. The task and address space connections remain active. If the CLOSE call fails
because DB2 was down, the CAF control blocks are reset, the function produces
return code 4 and reason code X00C10824, and CAF is ready for more
connection requests when DB2 is up.
3. A TRANSLATE request is accepted, but in this case it is redundant. CAF
automatically issues a TRANSLATE request when an SQL or IFI request fails.
Related reference
CAF return codes and reason codes on page 69
CAF connection functions
A CAF connection function specifies the action that you want CAF to take. You
specify these functions when you invoke CAF through CALL DSNALI statements.
You can specify the following CAF functions in a CALL DSNALI statement:
CONNECT
Establishes the task (TCB) as a user of the named DB2 subsystem. When
the first task within an address space issues a connection request, the
address space is also initialized as a user of DB2.
OPEN Allocates a DB2 plan. You must allocate a plan before DB2 can process SQL
statements. If you did not request the CONNECT function, the OPEN
function implicitly establishes the task, and optionally the address space, as
a user of DB2.
CLOSE
Commits or abnormally terminates any database changes and deallocates
the plan. If the OPEN function implicitly requests the CONNECT function,
the CLOSE function removes the task, and possibly the address space, as a
user of DB2.
DISCONNECT
Removes the task as a user of DB2 and, if this task is the last or only task
in the address space with a DB2 connection, terminates the address space
connection to DB2.
TRANSLATE
Returns an SQL code and printable text that describe a DB2 hexadecimal
error reason code. This information is returned to the SQLCA.
Restriction: You cannot call the TRANSLATE function from the Fortran
language.
58 Application Programming and SQL Guide
Recommendation: Because the effect of any CAF function depends on what
functions the program has already run, carefully plan the calls that your program
makes to these CAF connection functions. Read about the summary of CAF
behavior and make these function calls accordingly.
Related concepts
Summary of CAF behavior on page 57
CALL DSNALI statement parameter list on page 55
CONNECT function for CAF
The CAF CONNECT function initializes a connection to DB2. This function is
different than the SQL CONNECT statement that accesses a remote location within
DB2.
The CONNECT function establishes the callers task as a user of DB2 services. If
no other task in the address space currently holds a connection with the specified
subsystem, the CONNECT function also initializes the address space for
communication to the DB2 address spaces. The CONNECT function establishes the
address spaces cross memory authorization to DB2 and builds address space
control blocks. You can issue a CONNECT request from any or all tasks in the
address space, but the address space level is initialized only once when the first
task connects.
Using the CONNECT function is optional. If you do not call the CONNECT
function, the first request from a task, either an OPEN request or an SQL or IFI
call, causes CAF to issue an implicit CONNECT request. If a task is connected
implicitly, the connection to DB2 is terminated either when you call the CLOSE
function or when the task terminates.
Call the CONNECT function in all of the following situations:
v You need to specify a particular subsystem name (ssnm) other than the default
subsystem name.
v You need the value of the CURRENT DEGREE special register to last as long as
the connection (srdura).
v You need to monitor the DB2 startup ECB (startecb), the DB2 termination ECB
(termecb), or the DB2 release level.
v You plan to have multiple tasks in the address space open and close plans or a
single task in the address space open and close plans more than once.
Establishing task and address space level connections involves significant
overhead. Using the CONNECT function to establish a task connection explicitly
minimizes this overhead by ensuring that the connection to DB2 remains after
the CLOSE function deallocates a plan. In this case, the connection terminates
only when you use the DISCONNECT function or when the task terminates.
The CONNECT function also enables the caller to learn the following items:
v That the operator has issued a STOP DB2 command. When this event occurs,
DB2 posts the termination ECB, termecb. Your application can either wait on or
just look at the ECB.
v That DB2 is abnormally terminating. When this event occurs happens, DB2 posts
the termination ECB, termecb.
v That DB2 is available again after a connection attempt that failed because DB2
was down. Your application can either wait or look at the startup ECB, startecb.
DB2 ignores this ECB if it was active at the time of the CONNECT request, or if
the CONNECT request was to a group attachment name.
Chapter 2. Connecting to DB2 from your application program 59
v The current release level of DB2. To find this information, access the RIBREL
field in the release information block (RIB).
Restriction: Do not issue CONNECT requests from a TCB that already has an
active DB2 connection.
Recommendation: Do not mix explicit CONNECT and OPEN requests with
implicitly established connections in the same address space. Either explicitly
specify which DB2 subsystem you want to use or allow all requests to use the
default subsystem.
The following diagram shows the syntax for the CONNECT function.
DSNALI CONNECT function
CALL DSNALI ( function, ssnm, termecb, startecb, ribptr

,retcode
,reascode
,srdura
,eibptr
,groupoverride
)
Parameters point to the following areas:
function
A 12-byte area that contains CONNECT followed by five blanks.
ssnm
A 4-byte DB2 subsystem name or group attachment name (if used in a data
sharing group) to which the connection is made.
If you specify the group attachment name, the program connects to the DB2 on
the z/OS system on which the program is running. When you specify a group
attachment name and a startup ECB, DB2 ignores the startup ECB. If you need
to use a startup ECB, specify a subsystem name, rather than a group
attachment name. That subsystem name must be different than the group
attachment name.
If ssnm is less than four characters long, pad it on the right with blanks to a
length of four characters.
termecb
The applications event control block (ECB) for DB2 termination. DB2 posts this
ECB when the operator enters the STOP DB2 command or when DB2 is
abnormally terminating. The ECB indicates the type of termination by a POST
code, as shown in the following table:
Table 11. POST codes and related termination types
POST code Termination type
8 QUIESCE
12 FORCE
16 ABTERM
60 Application Programming and SQL Guide
Before you check termecb in your CAF application program, first check the
return code and reason code from the CONNECT call to ensure that the call
completed successfully.
startecb
The applications startup ECB. If DB2 has not yet started when the application
issues the call, DB2 posts the ECB when it successfully completes its startup
processing. DB2 posts at most one startup ECB per address space. The ECB is
the one associated with the most recent CONNECT call from that address
space. Your application program must examine any nonzero CAF and DB2
reason codes before issuing a WAIT on this ECB.
If ssnm is a group attachment name, the first DB2 subsystem that starts on the
local z/OS system and matches the specified group attachment name posts the
ECB.
ribptr
A 4-byte area in which CAF places the address of the release information block
(RIB) after the call. You can determine what release level of DB2 you are
currently running by examining the RIBREL field. You can determine the
modification level within the release level by examining the RIBCNUMB and
RIBCINFO fields. If the value in the RIBCNUMB field is greater than zero,
check the RIBCINFO field for modification levels.
If the RIB is not available (for example, if you name a subsystem that does not
exist), DB2 sets the 4-byte area to zeros.
The area to which ribptr points is below the 16-MB line.
Your program does not have to use the release information block, but it cannot
omit the ribptr parameter.
Macro DSNDRIB maps the release information block (RIB). It can be found in
prefix.SDSNMACS(DSNDRIB).
retcode
A 4-byte area in which CAF places the return code.
This field is optional. If you do not specify retcode, CAF places the return code
in register 15 and the reason code in register 0.
reascode
A 4-byte area in which CAF places a reason code.
This field is optional. If you do not specify reascode, CAF places the reason
code in register 0. If you specify reascode, you must also specify retcode.
srdura
A 10-byte area that contains the string SRDURA(CD). This field is optional. If
you specify srdura, the value in the CURRENT DEGREE special register stays
in effect from the time of the CONNECT call until the time of the
DISCONNECT call. If you do not specify srdura, the value in the CURRENT
DEGREE special register stays in effect from the time of the OPEN call until
the time of the CLOSE call. If you specify this parameter in any language
except assembler, you must also specify retcode and reascode. In assembler
language, you can omit these parameters by specifying commas as
placeholders.
eibptr
A 4-byte area in which CAF puts the address of the environment information
block (EIB). The EIB contains information that you can use if you are
connecting to a DB2 subsystem that is part of a data sharing group. For
Chapter 2. Connecting to DB2 from your application program 61
example, you can determine the name of the data sharing group, the member
to which you are connecting, and whether the subsystem is in new-function
mode. If the DB2 subsystem that you connect to is not part of a data sharing
group, the fields in the EIB that are related to data sharing are blank. If the EIB
is not available (for example, if you name a subsystem that does not exist),
DB2 sets the 4-byte area to zeros.
The area to which eibptr points is below the 16-MB line.
You can omit this parameter when you make a CONNECT call.
If you specify this parameter in any language except assembler, you must also
specify retcode, reascode, and srdura. In assembler language, you can omit
retcode, reascode, and srdura by specifying commas as placeholders.
Macro DSNDEIB maps the EIB. It can be found in
prefix.SDSNMACS(DSNDEIB).
groupoverride
An 8-byte area that the application provides. This parameter is optional. If you
do not want group attach to be attempted, specify NOGROUP. This string
indicates that the subsystem name that is specified by ssnm is to be used as a
DB2 subsystem name, even if ssnm matches a group attachment name. If
groupoverride is not provided, ssnm is used as the group attachment name if it
matches a group attachment name.
If you specify this parameter in any language except assembler, you must also
specify retcode, reascode, srdura, and eibptr. In assembler language, you can omit
retcode, reascode, srdura, and eibptr by specifying commas as placeholders.
Recommendation: Avoid using the groupoverride parameter when possible,
because it limits the ability to do dynamic workload routing in a Parallel
Sysplex

. However, you should use this parameter in a data sharing


environment when you want to connect to a specific member of a data sharing
group, and the subsystem name of that member is the same as the group
attachment name.
Example of CAF CONNECT function calls
The following table shows a CONNECT call in each language.
Table 12. Examples of CAF CONNECT function calls
Language Call example
Assembler CALL
DSNALI,(FUNCTN,SSID,TERMECB,STARTECB,RIBPTR,RETCODE,REASCODE,SRDURA,
EIBPTR, GRPOVER)
C
1
fnret=dsnali(&functn[0],&ssid[0], &tecb, &secb,&ribptr,&retcode, &reascode, &srdura[0],
&eibptr, &grpover[0]);
COBOL CALL 'DSNALI' USING FUNCTN SSID TERMECB STARTECB RIBPTR RETCODE REASCODE SRDURA
EIBPTR GRPOVER.
Fortran CALL
DSNALI(FUNCTN,SSID,TERMECB,STARTECB,RIBPTR,RETCODE,REASCODE,SRDURA,
EIBPTR,GRPOVER)
PL/I
1
CALL
DSNALI(FUNCTN,SSID,TERMECB,STARTECB,RIBPTR,RETCODE,REASCODE,SRDURA,
EIBPTR,GRPOVER)
Note:
62 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
v For C and PL/I applications, you must include the appropriate compiler
directives, because DSNALI is an assembler language program. These compiler
directives are described in the instructions for invoking CAF.
Related tasks
Invoking the call attachment facility on page 46
OPEN function for CAF
The OPEN function allocates DB2 resources that are needed to run the specified
plan or issue IFI requests. If the requesting task does not already have a connection
to the named DB2 subsystem, the OPEN function establishes it.
Using the OPEN function is optional. If you do not call the OPEN function, the
actions that the OPEN function perform occur implicitly on the first SQL or IFI call
from the task.
Restriction: Do not use the OPEN function if the task already has a plan allocated.
The following diagram shows the syntax for the OPEN function.
DSNALI OPEN function
CALL DSNALI ( function, ssnm, plan

, retcode
, reascode
, groupoverride
)
Parameters point to the following areas:
function
A 12-byte area that contains the word OPEN followed by eight blanks.
ssnm
A 4-byte DB2 subsystem name or group attachment name (if used in a data
sharing group). The OPEN function allocates the specified plan to this DB2
subsystem. Also, if the requesting task does not already have a connection to
the named DB2 subsystem, the OPEN function establishes it.
You must specify the ssnm parameter, even if the requesting task also issues a
CONNECT call. If a task issues a CONNECT call followed by an OPEN call,
the subsystem names for both calls must be the same.
If ssnm is less than four characters long, pad it on the right with blanks to a
length of four characters.
plan
An 8-byte DB2 plan name.
retcode
A 4-byte area in which CAF places the return code.
This field is optional. If you do not specify retcode,CAF places the return code
in register 15 and the reason code in register 0.
Chapter 2. Connecting to DB2 from your application program 63
reascode
A 4-byte area in which CAF places a reason code.
This field is optional. If you do not specify reascode, CAF places the reason
code in register 0. If you specify reascode, you must also specify retcode.
groupoverride
An 8-byte area that the application provides. This field is optional. If you do
not want group attach to be attempted, specify NOGROUP. This string
indicates that the subsystem name that is specified by ssnm is to be used as a
DB2 subsystem name, even if ssnm matches a group attachment name. If you
do not specify groupoverride, ssnm is used as the group attachment name if it
matches a group attachment name. If you specify this parameter in any
language except assembler, you must also specify retcode and reascode. In
assembler language, you can omit these parameters by specifying commas as
placeholders.
Recommendation: Avoid using the groupoverride parameter when possible,
because it limits the ability to do dynamic workload routing in a Parallel
Sysplex. However, you should use this parameter in a data sharing
environment when you want to connect to a specific member of a data sharing
group, and the subsystem name of that member is the same as the group
attachment name.
Examples of CAF OPEN calls
The following table shows an OPEN call in each language.
Table 13. Examples of CAF OPEN calls
Language Call example
Assembler CALL DSNALI,(FUNCTN,SSID,PLANNAME, RETCODE,REASCODE,GRPOVER)
C
1
fnret=dsnali(&functn[0],&ssid[0], &planname[0],&retcode, &reascode,&grpover[0]);
COBOL CALL 'DSNALI' USING FUNCTN SSID PLANNAME RETCODE REASCODE GRPOVER.
Fortran CALL DSNALI(FUNCTN,SSID,PLANNAME, RETCODE,REASCODE,GRPOVER)
PL/I
1
CALL DSNALI(FUNCTN,SSID,PLANNAME, RETCODE,REASCODE,GRPOVER);
Note:
v For C and PL/I applications, you must include the appropriate compiler
directives, because DSNALI is an assembler language program. These compiler
directives are described in the instructions for invoking CAF.
Related concepts
Implicit connections to CAF on page 54
Related tasks
Invoking the call attachment facility on page 46
CLOSE function for CAF
The CAF CLOSE function deallocates the plan that was created either explicitly by
a call to the OPEN function or implicitly at the first SQL call. Optionally, the
CLOSE function also disconnects the task, and possibly the address space, from
DB2.
If you did not issue an explicit CONNECT call for the task, the CLOSE function
deletes the tasks connection to DB2. If no other task in the address space has an
64 Application Programming and SQL Guide
|
active connection to DB2, DB2 also deletes the control block structures that were
created for the address space and removes the cross memory authorization.
Using the CLOSE function is optional. Consider the following rules and
recommendations about when to use and not use the CLOSE function:
v Do not use the CLOSE function when your current task does not have a plan
allocated.
v If you want to use a new plan, you must issue an explicit CLOSE call, followed
by an OPEN call with the new plan name.
v When shutting down your application you can improve the performance of this
shut down by explicitly calling the CLOSE function before the task terminates. If
you omit the CLOSE call, DB2 performs an implicit CLOSE. In this case, DB2
performs the same actions when your task terminates, by using the SYNC
parameter if termination is normal and the ABRT parameter if termination is
abnormal.
v If DB2 terminates, issue an explicit CLOSE call for any task that did not issue a
CONNECT call. This action enables CAF to reset its control blocks to allow for
future connections. This CLOSE call returns the reset accomplished return code
(+004) and reason code X00C10824. If you omit the CLOSE call in this case,
when DB2 is back on line, the tasks next connection request fails. You get either
the message YOUR TCB DOES NOT HAVE A CONNECTION, with X00F30018
in register 0, or the CAF error message DSNA201I or DSNA202I, depending on
what your application tried to do. The task must then issue a CLOSE call before
it can reconnect to DB2.
v A task that issued an explicit CONNECT call should issue a DISCONNECT call
instead of a CLOSE call. This action causes CAF to reset its control blocks when
DB2 terminates.
The following diagram shows the syntax for the CLOSE function.
DSNALI CLOSE function
CALL DSNALI ( function, termop )
, retcode
, reascode

Parameters point to the following areas:


function
A 12-byte area that contains the word CLOSE followed by seven blanks.
termop
A 4-byte terminate option, with one of the following values:
SYNC Specifies that DB2 is to commit any modified data.
ABRT Specifies that DB2 is to roll back data to the previous commit point.
retcode
A 4-byte area in which CAF is to place the return code.
This field is optional. If you do not specify retcode, CAF places the return code
in register 15 and the reason code in register 0.
Chapter 2. Connecting to DB2 from your application program 65
reascode
A 4-byte area in which CAF places a reason code.
This field is optional. If you do not specify reascode, CAF places the reason
code in register 0. If you specify reascode, you must also specify retcode.
Examples of CAF CLOSE calls
The following table shows a CLOSE call in each language.
Table 14. Examples of CAF CLOSE calls
Language Call example
Assembler CALL DSNALI,(FUNCTN,TERMOP,RETCODE, REASCODE)
C
1
fnret=dsnali(&functn[0], &termop[0], &retcode,&reascode);
COBOL CALL 'DSNALI' USING FUNCTN TERMOP RETCODE REASCODE.
Fortran CALL DSNALI(FUNCTN,TERMOP, RETCODE,REASCODE)
PL/I
1
CALL DSNALI(FUNCTN,TERMOP, RETCODE,REASCODE);
Note:
v For C and PL/I applications, you must include the appropriate compiler
directives, because DSNALI is an assembler language program. These compiler
directives are described in the instructions for invoking CAF.
Related tasks
Invoking the call attachment facility on page 46
DISCONNECT function for CAF
The CAF DISCONNECT function terminates a connection to DB2.
DISCONNECT removes the calling tasks connection to DB2. If no other task in the
address space has an active connection to DB2, DB2 also deletes the control block
structures that were created for the address space and removes the cross memory
authorization.
If an OPEN call is in effect, which means that a plan is allocated, when the
DISCONNECT call is issued, CAF issues an implicit CLOSE with the SYNC
parameter.
Using the DISCONNECT function is optional. Consider the following rules and
recommendations about when to use and not use the DISCONNECT function:
v Only those tasks that explicitly issued a CONNECT call can issue a
DISCONNECT call. If a CONNECT call was not used, a DISCONNECT call
causes an error.
v When shutting down your application you can improve the performance of this
shut down by explicitly calling the DISCONNECT function before the task
terminates. If you omit the DISCONNECT call, DB2 performs an implicit
DISCONNECT. In this case, DB2 performs the same actions when your task
terminates.
v If DB2 terminates, any task that issued a CONNECT call must issue a
DISCONNECT call to reset the CAF control blocks. The DISCONNECT function
returns the reset accomplished return codes and reason codes (+004 and
X00C10824). This action ensures that future connection requests from the task
work when DB2 is back on line.
66 Application Programming and SQL Guide
v A task that did not explicitly issue a CONNECT call must issue a CLOSE call
instead of a DISCONNECT call. This action resets the CAF control blocks when
DB2 terminates.
The following diagram shows the syntax for the DISCONNECT function.
DSNALI DISCONNECT function
CALL DSNALI ( function )
, retcode
, reascode

The single parameter points to the following area:


function
A 12-byte area that contains the word DISCONNECT followed by two blanks.
retcode
A 4-byte area in which CAF places the return code.
This field is optional. If you do not specify retcode, CAF places the return code
in register 15 and the reason code in register 0.
reascode
A 4-byte area in which CAF places a reason code.
This field is optional. If you do not specify reascode, CAF places the reason
code in register 0. If you specify reascode, you must also specify retcode.
Examples of CAF DISCONNECT calls
The following table shows a DISCONNECT call in each language.
Table 15. Examples of CAF DISCONNECT calls
Language Call example
Assembler CALL DSNALI(,FUNCTN,RETCODE,REASCODE)
C
1
fnret=dsnali(&functn[0], &retcode, &reascode);
COBOL CALL 'DSNALI' USING FUNCTN RETCODE REASCODE.
Fortran CALL DSNALI(FUNCTN,RETCODE,REASCODE)
PL/I
1
CALL DSNALI(FUNCTN,RETCODE,REASCODE);
Note:
v For C and PL/I applications, you must include the appropriate compiler
directives, because DSNALI is an assembler language program. These compiler
directives are described in the instructions for invoking CAF.
Related tasks
Invoking the call attachment facility on page 46
Chapter 2. Connecting to DB2 from your application program 67
TRANSLATE function for CAF
The TRANSLATE function converts a DB2 hexadecimal error reason code from a
failed OPEN request into an SQL error code and printable error message text. DB2
places the information into the SQLCODE and SQLSTATE host variables or related
fields of the callers SQLCA.
The DB2 error reason code that is converted is read from register 0. The
TRANSLATE function does not change the contents of registers 0 and 15, unless
the TRANSLATE request fails; in that case, register 0 is set to XC10205 and
register 15 is set to 200.
Consider the following rules and recommendations about when to use and not use
the TRANSLATE function:
v You cannot call the TRANSLATE function from the Fortran language.
v The TRANSLATE function is useful only if you used an explicit CONNECT call
before an OPEN request that fails. For errors that occur during SQL or IFI
requests, the TRANSLATE function performs automatically.
v The TRANSLATE function can translate those codes that begin with X00F3, but
it does not translate CAF reason codes that begin with X00C1.
If you receive error reason code X00F30040 (resource unavailable) after an OPEN
request, the TRANSLATE function returns the name of the unavailable database
object in the last 44 characters of the SQLERRM field.
If the TRANSLATE function does not recognize the error reason code, it returns
SQLCODE -924 (SQLSTATE 58006) and places a printable copy of the original
DB2 function code and the return and error reason codes in the SQLERRM field.
The following diagram shows the syntax for the TRANSLATE function.
DSNALI TRANSLATE function
CALL DSNALI ( function, sqlca )
, retcode
, reascode

Parameters point to the following areas:


function
A 12-byte area the contains the word TRANSLATE followed by three blanks.
sqlca
The programs SQL communication area (SQLCA).
retcode
A 4-byte area in which CAF places the return code.
This field is optional. If you do not specify retcode, CAF places the return code
in register 15 and the reason code in register 0.
reascode
A 4-byte area in which CAF places a reason code.
68 Application Programming and SQL Guide
This field is optional. If you do not specify reascode, CAF places the reason
code in register 0. If you specify reascode, you must also specify retcode.
Examples of CAF TRANSLATE calls
The following table shows a TRANSLATE call in each language.
Table 16. Examples of CAF TRANSLATE calls
Language Call example
Assembler CALL DSNALI,(FUNCTN,SQLCA,RETCODE, REASCODE)
C
1
fnret=dsnali(&functn[0], &sqlca, &retcode, &reascode);
COBOL CALL 'DSNALI' USING FUNCTN SQLCA RETCODE REASCODE.
PL/I
1
CALL DSNALI(FUNCTN,SQLCA,RETCODE, REASCODE);
Note:
v For C and PL/I applications, you must include the appropriate compiler
directives, because DSNALI is an assembler language program. These compiler
directives are described in the instructions for invoking CAF.
Related tasks
Invoking the call attachment facility on page 46
Turning on a CAF trace
CAF does not capture any diagnostic trace messages unless you tell it to by
turning on a trace.
To turn on a CAF trace:
Allocate a DSNTRACE data set either dynamically or by including a DSNTRACE
DD statement in your JCL. CAF writes diagnostic trace messages to that data set.
The trace message numbers contain the last three digits of the reason codes.
Related concepts
Examples of invoking CAF on page 71
CAF return codes and reason codes
CAF provides the return codes and reason codes either to the corresponding
parameters that are specified in a CAF function call or, if you choose not to use
those parameters, to registers 15 and 0.
When the reason code begins with X00F3 except for X00F30006, you can use the
CAF TRANSLATE function to obtain error message text that can be printed and
displayed. These reason codes are issued by the subsystem support for allied
memories, a part of the DB2 subsystem support subcomponent that services all
DB2 connection and work requests.
For SQL calls, CAF returns standard SQL codes in the SQLCA. CAF returns IFI
return codes and reason codes in the instrumentation facility communication area
(IFCA).
The following table lists the CAF return codes and reason codes.
Chapter 2. Connecting to DB2 from your application program 69
Table 17. CAF return codes and reason codes
Return code Reason code Explanation
0 X00000000 Successful completion.
4 X00C10824 CAF reset complete. CAF is ready to make a new connection.
8 X00C10831 Release level mismatch between DB2 and the CAF code.
200
1
X00C10201 Received a second CONNECT request from the same TCB. The first
CONNECT request could have been implicit or explicit.
200
1
X00C10202 Received a second OPEN request from the same TCB. The first
OPEN request could have been implicit or explicit.
200
1
X00C10203 CLOSE request issued when no active OPEN request exists.
200
1
X00C10204 DISCONNECT request issued when no active CONNECT request
exists, or the AXSET macro was issued between the CONNECT
request and the DISCONNECT request.
200
1
X00C10205 TRANSLATE request issued when no connection to DB2 exists.
200
1
X00C10206 Incorrect number of parameters was specified or the end-of-list bit
was off.
200
1
X00C10207 Unrecognized function parameter.
200
1
X00C10208 Received requests to access two different DB2 subsystems from the
same TCB.
204
2
CAF system error. Probable error in the attach or DB2.
Notes:
1. A CAF error probably caused by errors in the parameter lists from the application programs. CAF errors do not
change the current state of your connection to DB2; you can continue processing with a corrected request.
2. System errors cause abends. If tracing is on, a descriptive message is written to the DSNTRACE data set just
before the abend.
Sample CAF scenarios
One or more tasks can use CAF to connect to DB2. This connection can be made
either implicitly or explicitly. For explicit connections, a task calls one or more of
the CAF connection functions.
A single task with implicit connections
The simplest connection scenario is a single task that makes calls to DB2 without
using explicit CALL DSNALI statements. The task implicitly connects to the
default subsystem name and uses the default plan name.
When the task terminates, the following events occur:
v If termination was normal, any database changes are committed.
v If termination was abnormal, any database changes are rolled back.
v The active plan and all database resources are deallocated.
v The task and address space connections to DB2 are terminated.
A single task with explicit connections
The following example pseudocode illustrates a more complex scenario with a
single task.
70 Application Programming and SQL Guide
CONNECT
OPEN allocate a plan
SQL or IFI call

CLOSE deallocate the current plan


OPEN allocate a new plan
SQL or IFI call

CLOSE
DISCONNECT
A task can have a connection to only one DB2 subsystem at any point in time. A
CAF error occurs if the subsystem name in the OPEN call does not match the
subsystem name in the CONNECT call. To switch to a different subsystem, the
application must first disconnect from the current subsystem and then issue a
connect request with a new subsystem name.
Multiple tasks
In the following scenario, multiple tasks within the address space use DB2 services.
Each task must explicitly specify the same subsystem name on either the
CONNECT function request or the OPEN function request. Task 1 makes no SQL
or IFI calls. Its purpose is to monitor the DB2 termination and startup ECBs and to
check the DB2 release level.
TASK 1 TASK 2 TASK 3 TASK n
CONNECT
OPEN OPEN OPEN
SQL SQL SQL
... ... ...
CLOSE CLOSE CLOSE
OPEN OPEN OPEN
SQL SQL SQL
... ... ...
CLOSE CLOSE CLOSE
DISCONNECT
Examples of invoking CAF
The call attachment facility (CAF) enables programs to communicate with DB2. If
you explicitly invoke CAF in your program, you can use the CAF connection
functions to control the state of the connection.
Example JCL for invoking CAF
The following sample JCL shows how to use CAF in a batch (non-TSO)
environment. The DSNTRACE statement in this example is optional.
//jobname JOB z/OS_jobcard_information
//CAFJCL EXEC PGM=CAF_application_program
//STEPLIB DD DSN=application_load_library
// DD DSN=DB2_load_library
.
.
.
//SYSPRINT DD SYSOUT=*
//DSNTRACE DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
Chapter 2. Connecting to DB2 from your application program 71
Example of assembler code that invokes CAF
The following examples show parts of a sample assembler program that uses CAF.
They demonstrate the basic techniques for making CAF calls, but do not show the
code and z/OS macros needed to support those calls. For example, many
applications need a two-task structure so that attention-handling routines can
detach connected subtasks to regain control from DB2. This structure is not shown
in the following code examples. Also, these code examples assume the existence of
a WRITE macro. Wherever this macro is included in the example, substitute code
of your own. You must decide what you want your application to do in those
situations; you probably do not want to write the error messages shown.
Example of loading and deleting the CAF language interface: The following code
segment shows how an application can load entry points DSNALI and DSNHLI2
for the CAF language interface. Storing the entry points in variables LIALI and
LISQL ensures that the application has to load the entry points only once. When
the module is done with DB2, you should delete the entries.
****************************** GET LANGUAGE INTERFACE ENTRY ADDRESSES
LOAD EP=DSNALI Load the CAF service request EP
ST R0,LIALI Save this for CAF service requests
LOAD EP=DSNHLI2 Load the CAF SQL call Entry Point
ST R0,LISQL Save this for SQL calls
* .
* . Insert connection service requests and SQL calls here
* .
DELETE EP=DSNALI Correctly maintain use count
DELETE EP=DSNHLI2 Correctly maintain use count
Example of connecting to DB2 with CAF: The following example code shows
how to issue explicit requests for certain actions, such as CONNECT, OPEN,
CLOSE, DISCONNECT, and TRANSLATE, and uses the CHEKCODE subroutine to
check the return reason codes from CAF.
****************************** CONNECT ********************************
L R15,LIALI Get the Language Interface address
MVC FUNCTN,CONNECT Get the function to call
CALL (15),(FUNCTN,SSID,TECB,SECB,RIBPTR),VL,MF=(E,CAFCALL)
BAL R14,CHEKCODE Check the return and reason codes
CLC CONTROL,CONTINUE Is everything still OK
BNE EXIT If CONTROL not 'CONTINUE', stop loop
USING R8,RIB Prepare to access the RIB
L R8,RIBPTR Access RIB to get DB2 release level
WRITE 'The current DB2 release level is' RIBREL
****************************** OPEN ***********************************
L R15,LIALI Get the Language Interface address
MVC FUNCTN,OPEN Get the function to call
CALL (15),(FUNCTN,SSID,PLAN),VL,MF=(E,CAFCALL)
BAL R14,CHEKCODE Check the return and reason codes
****************************** SQL ************************************
* Insert your SQL calls here. The DB2 Precompiler
* generates calls to entry point DSNHLI. You should
* specify the precompiler option ATTACH(CAF), or code
* a dummy entry point named DSNHLI to intercept
* all SQL calls. A dummy DSNHLI is shown below.
****************************** CLOSE **********************************
CLC CONTROL,CONTINUE Is everything still OK?
BNE EXIT If CONTROL not 'CONTINUE', shut down
MVC TRMOP,ABRT Assume termination with ABRT parameter
L R4,SQLCODE Put the SQLCODE into a register
C R4,CODE0 Examine the SQLCODE
BZ SYNCTERM If zero, then CLOSE with SYNC parameter
72 Application Programming and SQL Guide
C R4,CODE100 See if SQLCODE was 100
BNE DISC If not 100, CLOSE with ABRT parameter
SYNCTERM MVC TRMOP,SYNC Good code, terminate with SYNC parameter
DISC DS 0H Now build the CAF parmlist
L R15,LIALI Get the Language Interface address
MVC FUNCTN,CLOSE Get the function to call
CALL (15),(FUNCTN,TRMOP),VL,MF=(E,CAFCALL)
BAL R14,CHEKCODE Check the return and reason codes
****************************** DISCONNECT *****************************
CLC CONTROL,CONTINUE Is everything still OK
BNE EXIT If CONTROL not 'CONTINUE', stop loop
L R15,LIALI Get the Language Interface address
MVC FUNCTN,DISCON Get the function to call
CALL (15),(FUNCTN),VL,MF=(E,CAFCALL)
BAL R14,CHEKCODE Check the return and reason codes
This example code does not show a task that waits on the DB2 termination ECB. If
you want such a task, you can code it by using the z/OS WAIT macro to monitor
the ECB. You probably want this task to detach the sample code if the termination
ECB is posted. That task can also wait on the DB2 startup ECB. This sample waits
on the startup ECB at its own task level.
This example code assumes that the variables in the following table are already set:
Table 18. Variables that preceding example assembler code assumes are set
Variable Usage
LIALI The entry point that handles DB2 connection
service requests.
LISQL The entry point that handles SQL calls.
SSID The DB2 subsystem identifier.
TECB The address of the DB2 termination ECB.
SECB The address of the DB2 startup ECB.
RIBPTR A fullword that CAF sets to contain the RIB
address.
PLAN The plan name to use in the OPEN call.
CONTROL This variable is used to shut down
processing because of unsatisfactory return
or reason codes. The CHECKCODE
subroutine sets this value.
CAFCALL List-form parameter area for the CALL
macro.
Example of checking return codes and reason codes when using CAF: The
following example code illustrates a way to check the return codes and the DB2
termination ECB after each connection service request and SQL call. The routine
sets the variable CONTROL to control further processing within the module.
***********************************************************************
* CHEKCODE PSEUDOCODE *
***********************************************************************
*IF TECB is POSTed with the ABTERM or FORCE codes
* THEN
* CONTROL = 'SHUTDOWN'
* WRITE 'DB2 found FORCE or ABTERM, shutting down'
* ELSE /* Termination ECB was not POSTed */
* SELECT (RETCODE) /* Look at the return code */
* WHEN (0) ; /* Do nothing; everything is OK */
Chapter 2. Connecting to DB2 from your application program 73
* WHEN (4) ; /* Warning */
* SELECT (REASCODE) /* Look at the reason code */
* WHEN ('00C10824'X) /* Ready for another CAF call */
* CONTROL = 'RESTART' /* Start over, from the top */
* OTHERWISE
* WRITE 'Found unexpected R0 when R15 was 4'
* CONTROL = 'SHUTDOWN'
* END INNER-SELECT
* WHEN (8,12) /* Connection failure */
* SELECT (REASCODE) /* Look at the reason code */
* WHEN ('00C10831'X) /* DB2 / CAF release level mismatch*/
* WRITE 'Found a mismatch between DB2 and CAF release levels'
* WHEN ('00F30002'X, /* These mean that DB2 is down but */
* '00F30012'X) /* will POST SECB when up again */
* DO
* WRITE 'DB2 is unavailable. I'll tell you when it's up.'
* WAIT SECB /* Wait for DB2 to come up */
* WRITE 'DB2 is now available.'
* END
* /**********************************************************/
* /* Insert tests for other DB2 connection failures here. */
* /* CAF Externals Specification lists other codes you can */
* /* receive. Handle them in whatever way is appropriate */
* /* for your application. */
* /**********************************************************/
* OTHERWISE /* Found a code we're not ready for*/
* WRITE 'Warning: DB2 connection failure. Cause unknown'
* CALL DSNALI ('TRANSLATE',SQLCA) /* Fill in SQLCA */
* WRITE SQLCODE and SQLERRM
* END INNER-SELECT
* WHEN (200)
* WRITE 'CAF found user error. See DSNTRACE dataset'
* WHEN (204)
* WRITE 'CAF system error. See DSNTRACE data set'
* OTHERWISE
* CONTROL = 'SHUTDOWN'
* WRITE 'Got an unrecognized return code'
* END MAIN SELECT
* IF (RETCODE > 4) THEN /* Was there a connection problem?*/
* CONTROL = 'SHUTDOWN'
* END CHEKCODE
***********************************************************************
* Subroutine CHEKCODE checks return codes from DB2 and Call Attach.
* When CHEKCODE receives control, R13 should point to the caller's
* save area.
***********************************************************************
CHEKCODE DS 0H
STM R14,R12,12(R13) Prolog
ST R15,RETCODE Save the return code
ST R0,REASCODE Save the reason code
LA R15,SAVEAREA Get save area address
ST R13,4(,R15) Chain the save areas
ST R15,8(,R13) Chain the save areas
LR R13,R15 Put save area address in R13
* ********************* HUNT FOR FORCE OR ABTERM ***************
TM TECB,POSTBIT See if TECB was POSTed
BZ DOCHECKS Branch if TECB was not POSTed
CLC TECBCODE(3),QUIESCE Is this "STOP DB2 MODE=FORCE"
BE DOCHECKS If not QUIESCE, was FORCE or ABTERM
MVC CONTROL,SHUTDOWN Shutdown
WRITE 'Found found FORCE or ABTERM, shutting down'
B ENDCCODE Go to the end of CHEKCODE
DOCHECKS DS 0H Examine RETCODE and REASCODE
* ********************* HUNT FOR 0 *****************************
CLC RETCODE,ZERO Was it a zero?
BE ENDCCODE Nothing to do in CHEKCODE for zero
* ********************* HUNT FOR 4 *****************************
74 Application Programming and SQL Guide
CLC RETCODE,FOUR Was it a 4?
BNE HUNT8 If not a 4, hunt eights
CLC REASCODE,C10831 Was it a release level mismatch?
BNE HUNT824 Branch if not an 831
WRITE 'Found a mismatch between DB2 and CAF release levels'
B ENDCCODE We are done. Go to end of CHEKCODE
HUNT824 DS 0H Now look for 'CAF reset' reason code
CLC REASCODE,C10824 Was it 4? Are we ready to restart?
BNE UNRECOG If not 824, got unknown code
WRITE 'CAF is now ready for more input'
MVC CONTROL,RESTART Indicate that we should re-CONNECT
B ENDCCODE We are done. Go to end of CHEKCODE
UNRECOG DS 0H
WRITE 'Got RETCODE = 4 and an unrecognized reason code'
MVC CONTROL,SHUTDOWN Shutdown, serious problem
B ENDCCODE We are done. Go to end of CHEKCODE
* ********************* HUNT FOR 8 *****************************
HUNT8 DS 0H
CLC RETCODE,EIGHT Hunt return code of 8
BE GOT8OR12
CLC RETCODE,TWELVE Hunt return code of 12
BNE HUNT200
GOT8OR12 DS 0H Found return code of 8 or 12
WRITE 'Found RETCODE of 8 or 12'
CLC REASCODE,F30002 Hunt for X'00F30002'
BE DB2DOWN
CLC REASCODE,F30012 Hunt for X'00F30012'
BE DB2DOWN
WRITE 'DB2 connection failure with an unrecognized REASCODE'
CLC SQLCODE,ZERO See if we need TRANSLATE
BNE A4TRANS If not blank, skip TRANSLATE
* ********************* TRANSLATE unrecognized RETCODEs ********
WRITE 'SQLCODE 0 but R15 not, so TRANSLATE to get SQLCODE'
L R15,LIALI Get the Language Interface address
CALL (15),(TRANSLAT,SQLCA),VL,MF=(E,CAFCALL)
C R0,C10205 Did the TRANSLATE work?
BNE A4TRANS If not C10205, SQLERRM now filled in
WRITE 'Not able to TRANSLATE the connection failure'
B ENDCCODE Go to end of CHEKCODE
A4TRANS DS 0H SQLERRM must be filled in to get here
* Note: your code should probably remove the X'FF'
* separators and format the SQLERRM feedback area.
* Alternatively, use DB2 Sample Application DSNTIAR
* to format a message.
WRITE 'SQLERRM is:' SQLERRM
B ENDCCODE We are done. Go to end of CHEKCODE
DB2DOWN DS 0H Hunt return code of 200
WRITE 'DB2 is down and I will tell you when it comes up'
WAIT ECB=SECB Wait for DB2 to come up
WRITE 'DB2 is now available'
MVC CONTROL,RESTART Indicate that we should re-CONNECT
B ENDCCODE
* ********************* HUNT FOR 200 ***************************
HUNT200 DS 0H Hunt return code of 200
CLC RETCODE,NUM200 Hunt 200
BNE HUNT204
WRITE 'CAF found user error, see DSNTRACE data set'
B ENDCCODE We are done. Go to end of CHEKCODE
* ********************* HUNT FOR 204 ***************************
HUNT204 DS 0H Hunt return code of 204
CLC RETCODE,NUM204 Hunt 204
BNE WASSAT If not 204, got strange code
WRITE 'CAF found system error, see DSNTRACE data set'
B ENDCCODE We are done. Go to end of CHEKCODE
* ********************* UNRECOGNIZED RETCODE *******************
WASSAT DS 0H
WRITE 'Got an unrecognized RETCODE'
Chapter 2. Connecting to DB2 from your application program 75
MVC CONTROL,SHUTDOWN Shutdown
BE ENDCCODE We are done. Go to end of CHEKCODE
ENDCCODE DS 0H Should we shut down?
L R4,RETCODE Get a copy of the RETCODE
C R4,FOUR Have a look at the RETCODE
BNH BYEBYE If RETCODE <= 4 then leave CHEKCODE
MVC CONTROL,SHUTDOWN Shutdown
BYEBYE DS 0H Wrap up and leave CHEKCODE
L R13,4(,R13) Point to caller's save area
RETURN (14,12) Return to the caller
Example of invoking CAF when you do not specify the precompiler option
ATTACH(CAF): Each of the four DB2 attachment facilities contains an entry point
named DSNHLI. When you use CAF but do not specify the precompiler option
ATTACH(CAF), SQL statements result in BALR instructions to DSNHLI in your
program. To find the correct DSNHLI entry point without including DSNALI in
your load module, code a subroutine with entry point DSNHLI that passes control
to entry point DSNHLI2 in the DSNALI module. DSNHLI2 is unique to DSNALI
and is at the same location in DSNALI as DSNHLI. DSNALI uses 31-bit
addressing. If the application that calls this intermediate subroutine uses 24-bit
addressing, this subroutine should account for the difference.
In the following example, LISQL is addressable because the calling CSECT used
the same register 12 as CSECT DSNHLI. Your application must also establish
addressability to LISQL.
***********************************************************************
* Subroutine DSNHLI intercepts calls to LI EP=DSNHLI
***********************************************************************
DS 0D
DSNHLI CSECT Begin CSECT
STM R14,R12,12(R13) Prologue
LA R15,SAVEHLI Get save area address
ST R13,4(,R15) Chain the save areas
ST R15,8(,R13) Chain the save areas
LR R13,R15 Put save area address in R13
L R15,LISQL Get the address of real DSNHLI
BASSM R14,R15 Branch to DSNALI to do an SQL call
* DSNALI is in 31-bit mode, so use
* BASSM to assure that the addressing
* mode is preserved.
L R13,4(,R13) Restore R13 (caller's save area addr)
L R14,12(,R13) Restore R14 (return address)
RETURN (1,12) Restore R1-12, NOT R0 and R15 (codes)
Example of variable declarations when using CAF: The following example code
shows declarations for some of the variables that were used in the previous
subroutines.
****************************** VARIABLES ******************************
SECB DS F DB2 Startup ECB
TECB DS F DB2 Termination ECB
LIALI DS F DSNALI Entry Point address
LISQL DS F DSNHLI2 Entry Point address
SSID DS CL4 DB2 Subsystem ID. CONNECT parameter
PLAN DS CL8 DB2 Plan name. OPEN parameter
TRMOP DS CL4 CLOSE termination option (SYNC|ABRT)
FUNCTN DS CL12 CAF function to be called
RIBPTR DS F DB2 puts Release Info Block addr here
RETCODE DS F Chekcode saves R15 here
REASCODE DS F Chekcode saves R0 here
CONTROL DS CL8 GO, SHUTDOWN, or RESTART
SAVEAREA DS 18F Save area for CHEKCODE
****************************** CONSTANTS ******************************
SHUTDOWN DC CL8'SHUTDOWN' CONTROL value: Shutdown execution
76 Application Programming and SQL Guide
RESTART DC CL8'RESTART ' CONTROL value: Restart execution
CONTINUE DC CL8'CONTINUE' CONTROL value: Everything OK, cont
CODE0 DC F'0' SQLCODE of 0
CODE100 DC F'100' SQLCODE of 100
QUIESCE DC XL3'000008' TECB postcode: STOP DB2 MODE=QUIESCE
CONNECT DC CL12'CONNECT ' Name of a CAF service. Must be CL12!
OPEN DC CL12'OPEN ' Name of a CAF service. Must be CL12!
CLOSE DC CL12'CLOSE ' Name of a CAF service. Must be CL12!
DISCON DC CL12'DISCONNECT ' Name of a CAF service. Must be CL12!
TRANSLAT DC CL12'TRANSLATE ' Name of a CAF service. Must be CL12!
SYNC DC CL4'SYNC' Termination option (COMMIT)
ABRT DC CL4'ABRT' Termination option (ROLLBACK)
****************************** RETURN CODES (R15) FROM CALL ATTACH ****
ZERO DC F'0' 0
FOUR DC F'4' 4
EIGHT DC F'8' 8
TWELVE DC F'12' 12 (Call Attach return code in R15)
NUM200 DC F'200' 200 (User error)
NUM204 DC F'204' 204 (Call Attach system error)
****************************** REASON CODES (R00) FROM CALL ATTACH ****
C10205 DC XL4'00C10205' Call attach could not TRANSLATE
C10831 DC XL4'00C10831' Call attach found a release mismatch
C10824 DC XL4'00C10824' Call attach ready for more input
F30002 DC XL4'00F30002' DB2 subsystem not up
F30011 DC XL4'00F30011' DB2 subsystem not up
F30012 DC XL4'00F30012' DB2 subsystem not up
F30025 DC XL4'00F30025' DB2 is stopping (REASCODE)
*
* Insert more codes here as necessary for your application
*
****************************** SQLCA and RIB **************************
EXEC SQL INCLUDE SQLCA
DSNDRIB Get the DB2 Release Information Block
****************************** CALL macro parm list *******************
CAFCALL CALL ,(*,*,*,*,*,*,*,*,*),VL,MF=L
Invoking the Resource Recovery Services attachment facility
The Resource Recovery Services attachment facility (RRSAF) enables your program
to communicate with DB2. Invoke RRSAF as an alternative to invoking CAF or
when using stored procedures that run in a WLM-established address space.
RRSAF has more capabilities than CAF.
Before you invoke RRSAF, perform the following actions:
v Ensure that the RRSAF language interface load module, DSNRLI, is available.
v Ensure that your application satisfies the requirements for programs that access
RRSAF.
v Ensure that your application satisfies the general environment characteristics for
connecting to DB2.
v Ensure that you are familiar with the following z/OS concepts and facilities:
The CALL macro and standard module linkage conventions
Program addressing and residency options (AMODE and RMODE)
Creating and controlling tasks; multitasking
Functional recovery facilities such as ESTAE, ESTAI, and FRRs
Synchronization techniques such as WAIT/POST
z/OS RRS functions, such as SRRCMIT and SRRBACK
Applications that use RRSAF can be written in assembler language, C, COBOL,
Fortran, and PL/I. When choosing a language to code your application in, consider
the following restrictions:
Chapter 2. Connecting to DB2 from your application program 77
v If you use z/OS macros (ATTACH, WAIT, POST, and so on), choose a
programming language that supports them.
v The RRSAF TRANSLATE function is not available in Fortran. To use this
function, code it in a routine that is written in another language, and then call
that routine from Fortran.
To invoke RRSAF:
1. Perform one of the following actions:
v Explicitly invoke RRSAF by including in your program CALL DSNRLI
statements with the appropriate options.
The first option is an RRSAF connection function, which describes the action
that you want RRSAF to take. The effect of any function depends in part on
what functions the program has already performed.
To code RRSAF functions in C, COBOL, Fortran, or PL/I, follow the
individual languages rules for making calls to assembler language routines.
Specify the return code and reason code parameters in the parameter list for
each RRSAF call.
Requirement: For C, C++, and PL/I applications, you must also include in
your program the compiler directives that are listed in the following table,
because DSNRLI is an assembler language program.
Table 19. Compiler directives to include in C, C++, and PL/I applications that contain CALL
DSNRLI statements
Language Compiler directive to include
C #pragma linkage(dsnrli, OS)
C++ extern "OS" {
int DSNRLI(
char * functn,
...); }
PL/I DCL DSNRLI ENTRY OPTIONS(ASM,INTER,RETCODE);
v Implicitly invoke RRSAF by including SQL statements or IFI calls in your
program just as you would in any program. The RRSAF facility establishes
the connection to DB2 with the default values for the subsystem name, plan
name and authorization ID.
Restriction: If your program can make its first SQL call from different
modules with different DBRMs, you cannot use a default plan name and
thus, you cannot implicitly invoke RRSAF. Instead, you must explicitly
invoke RRSAF by calling the CREATE THREAD function.
Requirement: If your application includes both SQL and IFI calls, you must
issue at least one SQL call before you issue any IFI calls. This action ensures
that your application uses the correct plan.
2. If you implicitly invoked RRSAF, determine if the implicit connection was
successful by examining the return code and reason code immediately after the
first executable SQL statement within the application program. Your program
can check these codes by performing one of the following actions:
v Examine registers 0 and 15 directly.
v Examine the SQLCA, and if the SQLCODE is -981, obtain the return and
reason code from the message text. The return code is the first token, and the
reason code is the second token.
78 Application Programming and SQL Guide
If the implicit connection is successful, the application can examine the
SQLCODE for the first, and subsequent, SQL statements.
Example of an RRSAF configuration
The following figure shows an conceptual example of invoking and using RRSAF.
Resource Recovery Services attachment facility
An attachment facility enables programs to communicate with DB2. The Resource
Recovery Services attachment facility (RRSAF) provides such a connection for
programs that run in z/OS batch, TSO foreground, and TSO background. The
RRSAF is an alternative to CAF and has more functionality.
Figure 5. Sample RRSAF configuration
Chapter 2. Connecting to DB2 from your application program 79
An application program using RRSAF can perform the following actions:
v Use DB2 to process SQL statements, commands, or instrumentation facility
interface (IFI) calls.
v Coordinate DB2 updates with updates made by all other resource managers that
also use z/OS RRS in an z/OS system.
v Use the z/OS System Authorization Facility and an external security product,
such as RACF, to sign on to DB2 with the authorization ID of an end user.
v Sign on to DB2 using a new authorization ID and an existing connection and
plan.
v Access DB2 from multiple z/OS tasks in an address space.
v Switch a DB2 thread among z/OS tasks within a single address space.
v Access the DB2 IFI.
v Run with or without the TSO terminal monitor program (TMP).
v Run without being a subtask of the DSN command processor (or of any DB2
code).
v Run above or below the 16-MB line.
v Establish an explicit connection to DB2, through a call interface, with control
over the exact state of the connection.
v Establish an implicit connection to DB2 (with a default subsystem identifier and
a default plan name) by using SQL statements or IFI calls without first calling
RRSAF.
v Supply event control blocks (ECBs), for DB2 to post, that signal start-up or
termination.
v Intercept return codes, reason codes, and abend codes from DB2 and translate
them into messages as desired.
RRSAF uses z/OS Transaction Management and Recoverable Resource Manager
Services (z/OS RRS).
Any task in an address space can establish a connection to DB2 through RRSAF.
Each task control block (TCB) can have only one connection to DB2. A DB2 service
request that is issued by a program that runs under a given task is associated with
that tasks connection to DB2. The service request operates independently of any
DB2 activity under any other task.
Each connected task can run a plan. Tasks within a single address space can
specify the same plan, but each instance of a plan runs independently from the
others. A task can terminate its plan and run a different plan without completely
breaking its connection to DB2.
RRSAF does not generate task structures.
When you design your application, consider that using multiple simultaneous
connections can increase the possibility of deadlocks and DB2 resource contention.
Restriction: RRSAF does not provide attention processing exits or functional
recovery routines. You can provide whatever attention handling and functional
recovery your application needs, but you must use ESTAE/ESTAI type recovery
routines only.
80 Application Programming and SQL Guide
A tracing facility provides diagnostic messages that help you debug programs and
diagnose errors in the RRSAF code. The trace information is available only in a
SYSABEND or SYSUDUMP dump.
To commit work in RRSAF applications, use the CPIC SRRCMIT function or the
DB2 COMMIT statement. To roll back work, use the CPIC SRRBACK function or
the DB2 ROLLBACK statement.
Use the following guidelines to decide whether to use the DB2 statements or the
CPIC functions for commit and rollback operations:
v Use DB2 COMMIT and ROLLBACK statements when all of the following
conditions are true:
The only recoverable resource that is accessed by your application is DB2 data
that is managed by a single DB2 instance.
DB2 COMMIT and ROLLBACK statements fail if your RRSAF application
accesses recoverable resources other than DB2 data that is managed by a
single DB2 instance.
The address space from which syncpoint processing is initiated is the same as
the address space that is connected to DB2.
v If your application accesses other recoverable resources, or syncpoint processing
and DB2 access are initiated from different address spaces, use SRRCMIT and
SRRBACK.
Related reference
COMMIT (DB2 SQL Reference)
ROLLBACK (DB2 SQL Reference)
Related information
z/OS Internet Library at ibm.com
Properties of RRSAF connections
RRSAF enables programs to communicate with DB2 to process SQL statements,
commands, or IFI calls. An RRSAF connection joins any task in an address space to
DB2.
Restriction: Do not mix RRSAF connections with other connection types in a
single address space. The first connection that is made from an address space to
DB2 determines the type of connection allowed.
The connection that RRSAF makes with DB2 has the basic properties that are listed
in the following table.
Table 20. Properties of RRSAF connections
Property Value Comments
Connection name RRSAF You can use the DISPLAY
THREAD command to list
RRSAF applications that have
the connection name RRSAF.
Connection type RRSAF None.
Chapter 2. Connecting to DB2 from your application program 81
Table 20. Properties of RRSAF connections (continued)
Property Value Comments
Authorization ID Authorization IDs that are
associated with each DB2
connection
A connection must have a
primary ID and can have one
or more secondary IDs. Those
identifiers are used for the
following purposes:
v Validating access to DB2
v Checking privileges on
DB2 objects
v Assigning ownership of
DB2 objects
v Identifying the user of a
connection for audit,
performance, and
accounting traces.
RRSAF relies on the z/OS
System Authorization Facility
(SAF) and a security product,
such as RACF, to verify and
authorize the authorization
IDs. An application that
connects to DB2 through
RRSAF must pass those
identifiers to SAF for
verification and authorization
checking. RRSAF retrieves
the identifiers from SAF.
A location can provide an
authorization exit routine for
a DB2 connection to change
the authorization IDs and to
indicate whether the
connection is allowed. The
actual values that are
assigned to the primary and
secondary authorization IDs
can differ from the values
that are provided by a
SIGNON or AUTH SIGNON
request. A sites DB2 signon
exit routine can access the
primary and secondary
authorization IDs and can
modify the IDs to satisfy the
sites security requirements.
The exit routine can also
indicate whether the signon
request should be accepted.
82 Application Programming and SQL Guide
Table 20. Properties of RRSAF connections (continued)
Property Value Comments
Scope RRSAF processes connections
as if each task is entirely
isolated. When a task
requests a function, RRSAF
passes the function to DB2,
regardless of the connection
status of other tasks in the
address space. However, the
application program and the
DB2 subsystem have access
to the connection status of
multiple tasks in an address
space.
None.
If an application that is connected to DB2 through RRSAF terminates normally
before the TERMINATE THREAD or TERMINATE IDENTIFY functions deallocate
the plan, RRS commits any changes made after the last commit point. If the
application terminates abnormally before the TERMINATE THREAD or
TERMINATE IDENTIFY functions deallocate the plan, z/OS RRS rolls back any
changes made after the last commit point. In either case, DB2 deallocates the plan,
if necessary, and terminates the applications connection.
If DB2 abends while an application is running, DB2 rolls back changes to the last
commit point. If DB2 terminates while processing a commit request, DB2 either
commits or rolls back any changes at the next restart. The action taken depends on
the state of the commit request when DB2 terminates.
Making the RRSAF language interface (DSNRLI) available
Before you can invoke the Resource Recovery Services attachment facility (RRSAF),
you must first make available the RRSAF language interface load module,
DSNRLI.
Part of RRSAF is a DB2 load module, DSNRLI, which is also known as the RRSAF
language interface module. DSNRLI has the alias names DSNHLIR and DSNWLIR.
The module has five entry points: DSNRLI, DSNHLI, DSNHLIR, DSNWLI, and
DSNWLIR. These entry points serve the following functions:
v Entry point DSNRLI handles explicit DB2 connection service requests.
v DSNHLI and DSNHLIR handle SQL calls. Use DSNHLI if your application
program link-edits RRSAF. Use DSNHLIR if your application program loads
RRSAF.
v DSNWLI and DSNWLIR handle IFI calls. Use DSNWLI if your application
program link-edits RRSAF. Use DSNWLIR if your application program loads
RRSAF.
To make DSNRLI available:
1. Decide which of the following two methods you want to use to make DSNRLI
available:
v Explicitly issuing LOAD requests when your program runs.
Chapter 2. Connecting to DB2 from your application program 83
By explicitly loading the DSNRLI module, you can isolate the maintenance of
your application from future IBM maintenance to the language interface. If
the language interface changes, the change will probably not affect your load
module.
v Including the DSNRLI module in your load module when you link-edit your
program.
A disadvantage of link-editing DSNRLI into your load module is that if IBM
makes a change to DSNRLI, you must link-edit your program again.
2. Depending on the method that you chose in step 1, perform one of the
following actions:
v If you want to explicitly issue LOAD requests when your program runs:
In your program, issue z/OS LOAD service requests for entry points
DSNRLI and DSNHLIR. If you use IFI services, you must also load
DSNWLIR. Save the entry point address that LOAD returns and use it in the
CALL macro.
Indicate to DB2 which entry point to use in one of the following two ways:
Specify the precompiler option ATTACH(RRSAF).
This option causes DB2 to generate calls that specify entry point
DSNHLIR.
Restriction: You cannot use this option if your application is written in
Fortran.
Code a dummy entry point named DSNHLI within your load module.
If you do not specify the precompiler option ATTACH, the DB2
precompiler generates calls to entry point DSNHLI for each SQL request.
The precompiler does not know about and is independent of the different
DB2 attachment facilities. When the calls that are generated by the DB2
precompiler pass control to DSNHLI, your code that corresponds to the
dummy entry point must preserve the option list that is passed in register
1 and call DSNHLIR with the same option list.
v If you want to include the DSNRLI module in your load module when
you link-edit your program:
Include DSNRLI in your load module during a link-edit step. For example,
you can use a linkage editor control statement that is similar to the following
statement in your JCL:
INCLUDE DB2LIB(DSNRLI).
By coding this statement, you avoid inadvertently picking up the wrong
language interface module.
When you include the DSNRLI module during the link-edit, do not include a
dummy DSNHLI entry point in your program or specify the precompiler
option ATTACH. Module DSNRLI contains an entry point for DSNHLI,
which is identical to DSNHLIR, and an entry point for DSNWLI, which is
identical to DSNWLIR.
Related concepts
Program examples for RRSAF on page 121
Requirements for programs that use RRSAF
The Resource Recovery Services attachment facility (RRSAF) enables programs to
communicate with DB2. Before you invoke RRSAF in your program, ensure that
your program satisfies any requirements for using RRSAF.
84 Application Programming and SQL Guide
When you write programs that use RRSAF, ensure that they meet the following
requirements:
v The program accounts for the size of the RRSAF code. The RRSAF code requires
about 10 KB of virtual storage per address space and an additional 10 KB for
each TCB that uses RRSAF.
v If your local environment intercepts and replaces the z/OS LOAD SVC that
RRSAF uses, you must ensure that your version of LOAD manages the load list
element (LLE) and contents directory entry (CDE) chains like the standard z/OS
LOAD macro. RRSAF uses z/OS SVC LOAD to load a module as part of the
initialization after your first service request. The module is loaded into
fetch-protected storage that has the job-step protection key.
You can prepare application programs to run in RRSAF similar to how you prepare
applications to run in other environments, such as CICS, IMS, and TSO. You can
prepare an RRSAF application either in the batch environment or by using the DB2
program preparation process. You can use the program preparation system either
through DB2I or through the DSNH CLIST.
Related tasks
Chapter 11, Preparing an application to run on DB2 for z/OS, on page 851
How RRSAF modifies the content of registers
If you do not specify the return code and reason code parameters in your RRSAF
function calls or you invoke RRSAF implicitly, RRSAF puts a return code in
register 15 and a reason code in register 0. RRSAF preserves the contents of
registers 2 through 14.
If you specify the return code and reason code parameters, RRSAF places the
return code in register 15 and in the return code parameter to accommodate
high-level languages that support special return code processing.
The following table summarizes the register conventions for RRSAF calls.
Table 21. Register conventions for RRSAF calls
Register Usage
R1 Parameter list pointer
R13 Address of callers save area
R14 Callers return address
R15 RRSAF entry point address
Implicit connections to RRSAF
RRSAF establishes an implicit connection to DB2 if the RRSAF language interface
load module (DSNRLI) is available, you do not explicitly specify the IDENTIFY
function in a CALL DSNRLI statement in your program, and the application
includes SQL statements or IFI calls.
An implicit connection causes RRSAF to initiate implicit IDENTIFY and CREATE
THREAD requests to DB2. These requests are subject to the same DB2 return codes
and reason codes as explicitly specified requests.
Implicit connections use the following defaults:
Chapter 2. Connecting to DB2 from your application program 85
Subsystem name
The default name that is specified in the module DSNHDECP. RRSAF uses
the installation default DSNHDECP, unless your own DSNHDECP module
is in a library in a STEPLIB statement of the JOBLIB concatenation or in
the link list. In a data sharing group, the default subsystem name is the
group attachment name.
Be certain that you know what the default name is and that it names the
specific DB2 subsystem that you want to use.
Plan name
The member name of the database request module (DBRM) that DB2
produced when you precompiled the source program that contains the first
SQL call.
Authorization ID
The 7-byte user ID that is associated with the address space, unless an
authorized function has built an Accessor Environment Element (ACEE)
for the address space. If an authorized function has built an ACEE, DB2
passes the 8-byte user ID from the ACEE.
For an implicit connection request, your application should not explicitly specify
either the IDENTIFY function or the CREATE THREAD function. Your application
can execute other explicit RRSAF calls after the implicit connection is made. An
implicit connection does not perform any SIGNON processing. Your application
can execute the SIGNON function at any point of consistency. To terminate an
implicit connection, you must use the proper function calls.
For implicit connection requests, register 15 contains the return code, and register 0
contains the reason code. The return code and reason code are also in the message
text for SQLCODE -981.
Related concepts
Summary of RRSAF behavior on page 87
CALL DSNRLI statement parameter list
The CALL DSNRLI statement explicitly invokes RRSAF. When you include CALL
DSNRLI statements in your program, you must specify all parameters that come
before the return code parameter.
In CALL DSNRLI statements, you cannot omit any of parameters that come before
the return code parameter by coding zeros or blanks. No defaults exist for those
parameters for explicit connection requests. Defaults are provided for only implicit
connections. All parameters starting with the return code parameter are optional.
When you want to use the default value for a parameter but specify subsequent
parameters, code the CALL DSNRLI statement as follows:
v For C-language, when you code CALL DSNRLI statements in C, you need to
specify the address of every parameter, using the address of operator (&), and
not the parameter itself. For example, to pass the pklistptr parameter on the
CREATE THREAD specify the address of the 4-byte pointer to the structure
(&pklistptr):
fnret=dsnrli(&crthrdfn[0], &plan[0], &collid[0], &reuse[0],
&retcode, &reascode, &pklistptr);
v For all languages except assembler language, code zero for that parameter in the
CALL DSNRLI statement. For example, suppose that you are coding an
86 Application Programming and SQL Guide
|
|
|
|
|
|
|
IDENTIFY call in a COBOL program, and you want to specify all parameters
except the return code parameter. You can write a statement similar to the
following statement:
CALL 'DSNRLI' USING IDFYFN SSNM RIBPTR EIBPTR TERMECB STARTECB
BY CONTENT ZERO BY REFERENCE REASCODE.
v For assembler language, code a comma for that parameter in the CALL DSNRLI
statement. For example, suppose that you are coding an IDENTIFY call, and you
want to specify all parameters except the return code parameter. You can write a
statement similar to the following statement:
CALL DSNRLI,(IDFYFN,SSNM,RIBPTR,EIBPTR,TERMECB,STARTECB,,REASCODE)
For assembler programs that invoke RRSAF, use a standard parameter list for an
z/OS CALL. Register 1 must contain the address of a list of pointers to the
parameters. Each pointer is a 4-byte address. The last address must contain the
value 1 in the high-order bit.
Summary of RRSAF behavior
The effect of any RRSAF function depends in part on what functions the program
has already run. You should plan the RRSAF function calls that your program
makes to avoid any errors and major structural problems in your application.
The following tables summarize RRSAF behavior after various inputs from
application programs. The contents of each table cell indicate the result of calling
the function in the first column for that row followed by the function in the
current column heading. For example, if you issue TERMINATE THREAD and
then IDENTIFY, RRSAF returns reason code X00C12201. Use these tables to
understand the order in which your application must issue RRSAF calls, SQL
statements, and IFI requests.
The RRSAF FIND_DB2_SYSTEMS function is omitted from these tables, because it
does not affect the operation of any of the other functions
The following table summarizes RRSAF behavior when the next call is to the
IDENTIFY function, the SWITCH TO function, the SIGNON function, or the
CREATE THREAD function.
Table 22. Effect of call order when next call is IDENTIFY, SWITCH TO, SIGNON, or CREATE THREAD
Previous function
Next function
IDENTIFY SWITCH TO
SIGNON, AUTH SIGNON,
or CONTEXT SIGNON CREATE THREAD
Empty: first call IDENTIFY X00C12205
1
X00C12204
1
X00C12204
1
IDENTIFY X00F30049
1
Switch to ssnm Signon
2
X00C12217
1
SWITCH TO IDENTIFY Switch to ssnm Signon
2
CREATE THREAD
SIGNON, AUTH SIGNON,
or CONTEXT SIGNON
X00F30049
1
Switch to ssnm Signon
2
CREATE THREAD
CREATE THREAD X00F30049
1
Switch to ssnm Signon
2
X00C12202
1
TERMINATE THREAD X00C12201
1
Switch to ssnm Signon
2
CREATE THREAD
IFI X00F30049
1
Switch to ssnm Signon
2
X00C12202
1
SQL X00F30049
1
Switch to ssnm X00F30092
13
X00C12202
1
SRRCMIT or SRRBACK X00F30049
1
Switch to ssnm Signon
2
X00C12202
1
Chapter 2. Connecting to DB2 from your application program 87
|
|
Table 22. Effect of call order when next call is IDENTIFY, SWITCH TO, SIGNON, or CREATE THREAD (continued)
Previous function
Next function
IDENTIFY SWITCH TO
SIGNON, AUTH SIGNON,
or CONTEXT SIGNON CREATE THREAD
Notes:
1. Errors are identified by the DB2 reason code that RRSAF returns.
2. Signon means either the SIGNON function, the AUTH SIGNON function, or the CONTEXT SIGNON function.
3. The SIGNON, AUTH SIGNON, or CONTEXT SIGNON functions are not allowed if any SQL operations are
requested after the CREATE THREAD function or after the last SRRCMIT or SRRBACK request.
The following table summarizes RRSAF behavior when the next call is an SQL
statement or an IFI call or to the TERMINATE THREAD function, the TERMINATE
IDENTIFY function, or the TRANSLATE function.
Table 23. Effect of call order when next call is SQL or IFI, TERMINATE THREAD, TERMINATE IDENTIFY, or
TRANSLATE
Previous function
Next function
SQL or IFI TERMINATE THREAD TERMINATE IDENTIFY TRANSLATE
Empty: first call SQL or IFI call
4
X00C12204
1
X00C12204
1
X00C12204
1
IDENTIFY SQL or IFI call
4
X00C12203
1
TERMINATE IDENTIFY TRANSLATE
SWITCH TO SQL or IFI call
4
TERMINATE THREAD TERMINATE IDENTIFY TRANSLATE
SIGNON, AUTH SIGNON,
or CONTEXT SIGNON
SQL or IFI call
4
TERMINATE THREAD TERMINATE IDENTIFY TRANSLATE
CREATE THREAD SQL or IFI call
4
TERMINATE THREAD TERMINATE IDENTIFY TRANSLATE
TERMINATE THREAD SQL or IFI call
4
X00C12203
1
TERMINATE IDENTIFY TRANSLATE
IFI SQL or IFI call
4
TERMINATE THREAD TERMINATE IDENTIFY TRANSLATE
SQL SQL or IFI call
4
X00F30093
12
X00F30093
13
TRANSLATE
SRRCMIT or SRRBACK SQL or IFI call
4
TERMINATE THREAD TERMINATE IDENTIFY TRANSLATE
Notes:
1. Errors are identified by the DB2 reason code that RRSAF returns.
2. TERMINATE THREAD is not allowed if any SQL operations are requested after the CREATE THREAD function
or after the last SRRCMIT or SRRBACK request.
3. TERMINATE IDENTIFY is not allowed if any SQL operations are requested after the CREATE THREAD function
or after the last SRRCMIT or SRRBACK request.
4. If you are using an implicit connection to RRSAF and issue SQL or IFI calls, RRSAF issues implicit IDENTIFY and
CREATE THREAD requests. If you continue with explicit RRSAF statements, you must follow the standard order
of explicit RRSAF calls. Implicitly connecting to RRSAF does not cause an implicit SIGNON request. Therefore,
you might need to issue an explicit SIGNON request to satisfy the standard order requirement. For example, an
SQL statement followed by an explicit TERMINATE THREAD request results in an error. You must issue an
explicit SIGNON request before issuing the TERMINATE THREAD request.
Related concepts
XC1...... codes (DB2 Codes)
XF3...... codes (DB2 Codes)
RRSAF connection functions
An RRSAF connection function specifies the action that you want RRSAF to take.
You specify these functions when you invoke RRSAF through CALL DSNRLI
statements.
88 Application Programming and SQL Guide
|
|
|
Related concepts
Summary of RRSAF behavior on page 87
CALL DSNRLI statement parameter list on page 86
IDENTIFY function for RRSAF
The RRSAF IDENTIFY function initializes a connection to DB2.
The IDENTIFY function establishes the callers task as a user of DB2 services. If no
other task in the address space currently is connected to the specified subsystem,
the IDENTIFY function also initializes the address space to communicate with the
DB2 address spaces. The IDENTIFY function establishes the cross-memory
authorization of the address space to DB2 and builds address space control blocks.
The following diagram shows the syntax for the IDENTIFY function.
DSNRLI IDENTIFY function
CALL DSNRLI ( function , ssnm , ribptr , eibptr , termecb ,
startecb

, retcode
, reascode
, groupoverride
, decpptr
)
Parameters point to the following areas:
function
An 18-byte area that contains IDENTIFY followed by 10 blanks.
ssnm
A 4-byte DB2 subsystem name or group attachment name (if used in a data
sharing group) to which the connection is made. If ssnm is less than four
characters long, pad it on the right with blanks to a length of four characters.
ribptr
A 4-byte area in which RRSAF places the address of the release information
block (RIB) after the call. You can use the RIB to determine the release level of
the DB2 subsystem to which the application is connected. You can determine
the modification level within the release level by examining the RIBCNUMB
and RIBCINFO fields. If the value in the RIBCNUMB field is greater than zero,
check the RIBCINFO field for modification levels.
If the RIB is not available (for example, if ssnm names a subsystem that does
not exist), DB2 sets the 4-byte area to zeros.
The area to which ribptr points is below the 16-MB line.
This parameter is required. However, the application does not need to refer to
the returned information.
eibptr
A 4-byte area in which RRSAF places the address of the environment
information block (EIB) after the call. The EIB contains environment
Chapter 2. Connecting to DB2 from your application program 89
||
information, such as the data sharing group, the name of the DB2 member to
which the IDENTIFY request was issued, and whether the subsystem is in
new-function mode. If the DB2 subsystem is not in a data sharing group,
RRSAF sets the data sharing group and member names to blanks. If the EIB is
not available (for example, if ssnm names a subsystem that does not exist),
RRSAF sets the 4-byte area to zeros.
The area to which eibptr points is above the 16-MB line.
This parameter is required. However, the application does not need to refer to
the returned information.
termecb
The address of the applications event control block (ECB) that is used for DB2
termination. DB2 posts this ECB when the system operator enters the STOP
DB2 command or when DB2 is terminating abnormally. Specify a value of 0 if
you do not want to use a termination ECB.
RRSAF puts a POST code in the ECB to indicate the type of termination as
shown in the following table.
Table 24. Post codes for types of DB2 termination
POST code Termination type
8 QUIESCE
12 FORCE
16 ABTERM
startecb
The address of the applications startup ECB. If DB2 has not started when the
application issues the IDENTIFY call, DB2 posts the ECB when DB2 has
started. Enter a value of zero if you do not want to use a startup ECB. DB2
posts no more than one startup ECB per address space. The ECB that is posted
is associated with the most recent IDENTIFY call from that address space. The
application program must examine any nonzero RRSAF or DB2 reason codes
before issuing a WAIT request on this ECB.
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places a reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify reascode, you must also specify retcode or its default. You can
specify a default for retcode by specifying a comma or zero, depending on the
language.
groupoverride
An 8-byte area that the application provides. This parameter is optional. If you
do not want group attach to be attempted, specify NOGROUP. This string
indicates that the subsystem name that is specified by ssnm is to be used as a
DB2 subsystem name, even if ssnm matches a group attachment name. If
groupoverride is not provided, ssnm is used as the group attachment name if it
matches a group attachment name.
90 Application Programming and SQL Guide
|
|
|
|
|
|
If you specify this parameter in any language except assembler, you must also
specify the retcode and reascode parameters. In assembler language, you can
omit the retcode and reascode parameters by specifying commas as
place-holders.
Recommendation: Avoid using the groupoverride parameter when possible,
because it limits the ability to do dynamic workload routing in a Parallel
Sysplex. However, you should use this parameter in a data sharing
environment when you want to connect to a specific member of a data sharing
group, and the subsystem name of that member is the same as the group
attachment name.
decpptr
A 4-byte area in which RRSAF is to put the address of the DSNHDECP control
block that was loaded by subsystem ssnm when that subsystem was started.
This 4-byte area is a 31-bit pointer. If ssnm is not found, the 4-byte area is set to
0.
The area to which decpptr points is above the 16-MB line.
If you specify this parameter in any language except assembler, you must also
specify the retcode, reascode, and groupoverride parameters. In assembler
language, you can omit the retcode, reascode, and groupoverride parameters by
specifying commas as placeholders.
Example of RRSAF IDENTIFY function calls
The following table shows an IDENTIFY call in each language.
Table 25. Examples of RRSAF IDENTIFY calls
Language Call example
Assembler CALL DSNRLI,(IDFYFN,SSNM,RIBPTR,EIBPTR,TERMECB,STARTECB, RETCODE,REASCODE,GRPOVER,DECPPTR)
C
1
fnret=dsnrli(&idfyfn[0],&ssnm[0], &ribptr, &eibptr, &termecb, &startecb, &retcode,
&reascode,&grpover[0],&decpptr);
COBOL CALL 'DSNRLI' USING IDFYFN SSNM RIBTPR EIBPTR TERMECB STARTECB RETCODE REASCODE GRPOVER
DECPPTR.
Fortran CALL DSNRLI(IDFYFN,SSNM,RIBPTR,EIBPTR,TERMECB,STARTECB, RETCODE,REASCODE,GRPOVER,DECPPTR)
PL/I
1
CALL DSNRLI(IDFYFN,SSNM,RIBPTR,EIBPTR,TERMECB,STARTECB, RETCODE,REASCODE,GRPOVER,DECPPTR);
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Internal processing for the IDENTIFY function
When you call the IDENTIFY function, DB2 performs the following steps:
1. DB2 determines whether the user address space is authorized to connect to
DB2. DB2 invokes the z/OS SAF and passes a primary authorization ID to SAF.
That authorization ID is the 7-byte user ID that is associated with the address
space, unless an authorized function has built an ACEE for the address space.
If an authorized function has built an ACEE, DB2 passes the 8-byte user ID
from the ACEE. SAF calls an external security product, such as RACF, to
determine if the task is authorized to use the following items:
v The DB2 resource class (CLASS=DSNR)
Chapter 2. Connecting to DB2 from your application program 91
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
v The DB2 subsystem (SUBSYS=ssnm)
v Connection type RRSAF
2. If that check is successful, DB2 calls the DB2 connection exit routine to perform
additional verification and possibly change the authorization ID.
3. DB2 searches for a matching trusted context in the system cache and then the
catalog based on the following criteria:
v The primary authorization ID matches a trusted context SYSTEM AUTHID.
v The job or started task name matches the JOBNAME attribute that is defined
for the identified trusted context.
If a trusted context is defined, DB2 checks if SECURITY LABEL is defined in
the trusted context. If SECURITY LABEL is defined, DB2 verifies the SECURITY
LABEL with RACF by using the RACROUTE VERIFY request. This security
label is used to verify multi-level security for SYSTEM AUTHID.If a matching
trusted context is defined, DB2 establishes the connection as trusted. Otherwise,
the connection is established without any additional privileges.
4. DB2 then sets the connection name to RRSAF and the connection type to
RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
SWITCH TO function for RRSAF
The RRSAF SWITCH TO function directs RRSAF, SQL, or IFI requests to a
specified DB2 subsystem. Use the SWITCH TO function to establish connections to
multiple DB2 subsystems from a single task.
The SWITCH TO function is useful only after a successful IDENTIFY call. If you
have established a connection with one DB2 subsystem, you must issue a SWITCH
TO call before you make an IDENTIFY call to another DB2 subsystem. Otherwise,
DB2 returns return code X200 and reason code X00C12201.
The first time that you make a SWITCH TO call to a new DB2 subsystem, DB2
returns return code 4 and reason code X00C12205 as a warning to indicate that
the current task has not yet been identified to the new DB2 subsystem.
The following diagram shows the syntax for the SWITCH TO function.
DSNRLI SWITCH TO function
CALL DSNRLI ( function,ssnm

, retcode
, reascode
, groupoverride
)
Parameters point to the following areas:
function
An 18-byte area that contains SWITCH TO followed by nine blanks.
92 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ssnm
A 4-byte DB2 subsystem name or group attachment name (if used in a data
sharing group) to which the connection is made. If ssnm is less than four
characters long, pad it on the right with blanks to a length of four characters.
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify this parameter, you must also specify retcode.
groupoverride
An 8-byte area that the application provides. This parameter is optional. If you
do not want group attach to be attempted, specify NOGROUP. This string
indicates that the subsystem name that is specified by ssnm is to be used as a
DB2 subsystem name, even if ssnm matches a group attachment name. If
groupoverride is not provided, ssnm is used as the group attachment name if it
matches a group attachment name.
If you specify this parameter in any language except assembler, you must also
specify the retcode and reascode parameters. In assembler language, you can
omit the retcode and reascode parameters by specifying commas as
place-holders.
Recommendation: Avoid using the groupoverride parameter when possible,
because it limits the ability to do dynamic workload routing in a Parallel
Sysplex. However, you should use this parameter in a data sharing
environment when you want to connect to a specific member of a data sharing
group, and the subsystem name of that member is the same as the group
attachment name.
Examples
Examples of RRSAF SWITCH TO calls: The following table shows a SWITCH TO
call in each language.
Table 26. Examples of RRSAF SWITCH TO calls
Language Call example
Assembler CALL DSNRLI,(SWITCHFN,SSNM,RETCODE,REASCODE,GRPOVER)
C
1
fnret=dsnrli(&switchfn[0], &ssnm[0], &retcode, &reascode,&grpover[0]);
COBOL CALL 'DSNRLI' USING SWITCHFN RETCODE REASCODE GRPOVER.
Fortran CALL DSNRLI(SWITCHFN,RETCODE,REASCODE,GRPOVER)
PL/I
1
CALL DSNRLI(SWITCHFN,RETCODE,REASCODE,GRPOVER);
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Chapter 2. Connecting to DB2 from your application program 93
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Example of using the SWITCH TO function to interact with multiple DB2
subsystems: The following example shows how you can use the SWITCH TO
function to interact with three DB2 subsystems.
RRSAF calls for subsystem db21:
IDENTIFY
SIGNON
CREATE THREAD
Execute SQL on subsystem db21
SWITCH TO db22
IF retcode = 4 AND reascode = '00C12205'X THEN
DO;
RRSAF calls on subsystem db22:
IDENTIFY
SIGNON
CREATE THREAD
END;
Execute SQL on subsystem db22
SWITCH TO db23
IF retcode = 4 AND reascode = '00C12205'X THEN
DO;
RRSAF calls on subsystem db23:
IDENTIFY
SIGNON
CREATE THREAD
END;
Execute SQL on subsystem 23
SWITCH TO db21
Execute SQL on subsystem 21
SWITCH TO db22
Execute SQL on subsystem 22
SWITCH TO db21
Execute SQL on subsystem 21
SRRCMIT (to commit the UR)
SWITCH TO db23
Execute SQL on subsystem 23
SWITCH TO db22
Execute SQL on subsystem 22
SWITCH TO db21
Execute SQL on subsystem 21
SRRCMIT (to commit the UR)
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
SIGNON function for RRSAF
The RRSAF SIGNON function establishes a primary authorization ID and,
optionally, one or more secondary authorization IDs for a connection.
Requirement: Your program does not need to be an authorized program to issue
the SIGNON call. For that reason, before you issue the SIGNON call, you must
issue the RACF external security interface macro RACROUTE REQUEST=VERIFY
to perform the following actions:
v Define and populate an ACEE to identify the user of the program.
v Associate the ACEE with the users TCB.
v Verify that the user is defined to RACF and authorized to use the application.
Generally, you issue a SIGNON call after an IDENTIFY call and before a CREATE
THREAD call. You can also issue a SIGNON call if the application is at a point of
consistency, and one of the following conditions is true:
v The value of reuse in the CREATE THREAD call was RESET.
v The value of reuse in the CREATE THREAD call was INITIAL, no held cursors
are open, the package or plan is bound with KEEPDYNAMIC(NO), and all
94 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
special registers are at their initial state. If open held cursors exist or the package
or plan is bound with KEEPDYNAMIC(YES), you can issue a SIGNON call only
if the primary authorization ID has not changed.
After you issue a SIGNON call, subsequent SQL statements return an error
(SQLCODE -900) if the both of following conditions are true:
v The connection was established as trusted when it was initialized.
v The primary authorization ID that was used when you issued the SIGNON call
is not allowed to use the trusted connection.
If a trusted context is defined, DB2 checks if SECURITY LABEL is defined in the
trusted context. If SECURITY LABEL is defined, DB2 verifies the security label
with RACF by using the RACROUTE VERIFY request. This security label is used
to verify multi-level security for SYSTEM AUTHID.
The following diagram shows the syntax for the SIGNON function.
DSNRLI SIGNON function
CALL DSNRLI ( function, correlation-id, accounting-token, accounting-interval

,retcode
,reascode
,user
,appl
,ws
,xid
,accounting-string
)
Parameters point to the following areas:
function
An 18-byte area that contains SIGNON followed by twelve blanks.
correlation-id
A 12-byte area in which you can put a DB2 correlation ID. The correlation ID is
displayed in DB2 accounting and statistics trace records. You can use the
correlation ID to correlate work units. This token appears in the output from
the DISPLAY THREAD command. If you do not want to specify a correlation
ID, fill the 12-byte area with blanks.
accounting-token
A 22-byte area in which you can put a value for a DB2 accounting token. This
value is displayed in DB2 accounting and statistics trace records in the
QWHCTOKEN field, which is mapped by DSNDQWHC DSECT. Setting the
value of the accounting token sets the value of the CURRENT
CLIENT_ACCTNG special register. If accounting-token is less than 22 characters
long, you must pad it on the right with blanks to a length of 22 characters. If
you do not want to specify an accounting token, fill the 22-byte area with
blanks.
Alternatively, you change the value of the DB2 accounting token with RRSAF
functions AUTH SIGNON, CONTEXT SIGNON or SET_CLIENT_ID. You can
retrieve the DB2 accounting token with the CURRENT CLIENT_ACCTNG
special register only if the DDF accounting string is not set.
Chapter 2. Connecting to DB2 from your application program 95
|
|
|
|
|
|
|
|
|
accounting-interval
A 6-byte area that specifies when DB2 writes an accounting record.
If you specify COMMIT in that area, DB2 writes an accounting record each
time that the application issues SRRCMIT without open held cursors. If the
accounting interval is COMMIT and an SRRCMIT is issued while a held cursor
is open, the accounting interval spans that commit and ends at the next valid
accounting interval end point (such as the next SRRCMIT that is issued
without open held cursors, application termination, or SIGNON with a new
authorization ID).
If you specify any other value, DB2 writes an accounting record when the
application terminates or when you call the SIGNON function with a new
authorization ID.
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify this parameter, you must also specify retcode.
user
A 16-byte area that contains the user ID of the client end user. You can use this
parameter to provide the identity of the client end user for accounting and
monitoring purposes. DB2 displays this user ID in the output from the
DISPLAY THREAD command and in DB2 accounting and statistics trace
records. Setting the user ID sets the value of the CURRENT CLIENT_USERID
special register. If user is less than 16 characters long, you must pad it on the
right with blanks to a length of 16 characters.
This parameter is optional. If you specify user, you must also specify retcode
and reascode. If you do not specify user, no user ID is associated with the
connection.
appl
A 32-byte area that contains the application or transaction name of the end
users application. You can use this parameter to provide the identity of the
client end user for accounting and monitoring purposes. DB2 displays the
application name in the output from the DISPLAY THREAD command and in
DB2 accounting and statistics trace records. Setting the application name sets
the value of the CURRENT CLIENT_APPLNAME special register. If appl is less
than 32 characters long, you must pad it on the right with blanks to a length of
32 characters.
This parameter is optional. If you specify appl, you must also specify retcode,
reascode, and user. If you do not specify appl, no application or transaction is
associated with the connection.
ws An 18-byte area that contains the workstation name of the client end user. You
can use this parameter to provide the identity of the client end user for
accounting and monitoring purposes. DB2 displays the workstation name in
the output from the DISPLAY THREAD command and in DB2 accounting and
statistics trace records. Setting the workstation name sets the value of the
96 Application Programming and SQL Guide
|
|
|
|
|
|
|
CURRENT CLIENT_WRKSTNNAME special register. If ws is less than 18
characters long, you must pad it on the right with blanks to a length of 18
characters.
This field is optional. If you specify ws, you must also specify retcode, reascode,
user, and appl. If you do not specify ws, no workstation name is associated with
the connection.
xid
A 4-byte area that indicates whether the thread is part of a global transaction.
A DB2 thread that is part of a global transaction can share locks with other
DB2 threads that are part of the same global transaction and can access and
modify the same data. A global transaction exists until one of the threads that
is part of the global transaction is committed or rolled back.
You can specify one of the following values for xid:
0 Indicates that the thread is not part of a global transaction. The value 0
must be specified as a binary integer.
1 Indicates that the thread is part of a global transaction and that DB2
should retrieve the global transaction ID from RRS. If a global
transaction ID already exists for the task, the thread becomes part of
the associated global transaction. Otherwise, RRS generates a new
global transaction ID. The value 1 must be specified as a binary
integer. Alternatively, if you want DB2 to return the generated global
transaction ID to the caller, specify an address instead of 1.
address The 4-byte address of an area in which you enter a global transaction
ID for the thread. If the global transaction ID already exists, the thread
becomes part of the associated global transaction. Otherwise, RRS
creates a new global transaction with the ID that you specify.
Alternatively, if you want DB2 to generate and return a global
transaction ID, pass the address of a null global transaction ID by
setting the format ID field of the global transaction ID to binary -1
(FFFFFFFX). DB2 then replaces the contents of the area with the
generated transaction ID. The area at the specified address must be in
writable storage and have a length of at least 140 bytes to
accommodate the largest possible transaction ID value.
The following table shows the format of a global transaction ID.
Table 27. Format of a user-created global transaction ID
Field description Length in bytes Data type
Format ID 4 Integer
Global transaction ID length
(1 - 64)
4 Integer
Branch qualifier length (1 -
64)
4 Integer
Global transaction ID 1 to 64 Character
Branch qualifier 1 to 64 Character
accounting-string
A one-byte length field and a 255-byte area in which you can put a value for a
DB2 accounting string. This value is placed in the DDF accounting trace
records in the QMDASQLI field, which is mapped by DSNDQMDA DSECT. If
Chapter 2. Connecting to DB2 from your application program 97
accounting-string is less than 255 characters, you must pad it on the right with
zeros to a length of 255 bytes. The entire 256 bytes is mapped by DSNDQMDA
DSECT.
This parameter is optional. If you specify accounting-string, you must also
specify retcode, reascode, user, appl and xid. If you do not specify
accounting-string, no accounting string is associated with the connection.
You can also change the value of the accounting string with RRSAF functions
AUTH SIGNON, CONTEXT SIGNON, or SET_CLIENT_ID.
You can retrieve the DDF suffix portion of the accounting string with the
CURRENT CLIENT_ACCTNG special register. The suffix portion of
accounting-string can contain a maximum of 200 characters. The QMDASFLN
field contains the accounting suffix length, and the QMDASUFX field contains
the accounting suffix value. If the DDF accounting string is set, you cannot
query the accounting token with the CURRENT CLIENT_ACCTNG special
register.
Example of RRSAF SIGNON calls
The following table shows a SIGNON call in each language.
Table 28. Examples of RRSAF SIGNON calls
Language Call example
assembler CALL DSNRLI,(SGNONFN,CORRID,ACCTTKN,ACCTINT, RETCODE,REASCODE,USERID,APPLNAME,WSNAME,XIDPTR)
C
1
fnret=dsnrli(&sgnonfn[0], &corrid[0], &accttkn[0], &acctint[0], &retcode, &reascode,
&userid[0], &applname[0], &wsname[0], &xidptr);
COBOL CALL 'DSNRLI' USING SGNONFN CORRID ACCTTKN ACCTINT RETCODE REASCODE USERID APPLNAME WSNAME
XIDPTR.
Fortran CALL DSNRLI(SGNONFN,CORRID,ACCTTKN,ACCTINT, RETCODE,REASCODE,USERID,APPLNAME,WSNAME,XIDPTR)
PL/I
1
CALL DSNRLI(SGNONFN,CORRID,ACCTTKN,ACCTINT, RETCODE,REASCODE,USERID,APPLNAME,WSNAME,XIDPTR);
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
Related information
z/OS Internet Library at ibm.com
AUTH SIGNON function for RRSAF
The RRSAF AUTH SIGNON function enables an APF-authorized program to pass
to DB2 either a primary authorization ID and, optionally, one or more secondary
authorization IDs, or an ACEE that is used for authorization checking. These IDs
are then associated with the connection.
Generally, you issue an AUTH SIGNON call after an IDENTIFY call and before a
CREATE THREAD call. You can also issue an AUTH SIGNON call if the
application is at a point of consistency, and one of the following conditions is true:
v The value of reuse in the CREATE THREAD call was RESET.
98 Application Programming and SQL Guide
v The value of reuse in the CREATE THREAD call was INITIAL, no held cursors
are open, the package or plan is bound with KEEPDYNAMIC(NO), and all
special registers are at their initial state. If open held cursors exist or the package
or plan is bound with KEEPDYNAMIC(YES), a SIGNON call is permitted only if
the primary authorization ID has not changed.
The following diagram shows the syntax for the AUTH SIGNON function.
DSNRLI AUTH SIGNON function
CALL DSNRLI ( function, correlation-id, accounting-token,
accounting-interval, primary-authid, ACEE-address, secondary-authid

,retcode
,reascode
,user
,appl
,ws
,xid
,accounting-string
)
Parameters point to the following areas:
function
An 18-byte area that contains AUTH SIGNON followed by seven blanks.
correlation-id
A 12-byte area in which you can put a DB2 correlation ID. The correlation ID is
displayed in DB2 accounting and statistics trace records. You can use the
correlation ID to correlate work units. This token appears in output from the
DISPLAY THREAD command. If you do not want to specify a correlation ID,
fill the 12-byte area with blanks.
accounting-token
A 22-byte area in which you can put a value for a DB2 accounting token. This
value is displayed in DB2 accounting and statistics trace records in the
QWHCTOKEN field, which is mapped by DSNDQWHC DSECT. Setting the
value of the accounting token sets the value of the CURRENT
CLIENT_ACCTNG special register. If accounting-token is less than 22 characters
long, you must pad it on the right with blanks to a length of 22 characters. If
you do not want to specify an accounting token, fill the 22-byte area with
blanks.
You can also change the value of the DB2 accounting token with RRSAF
functions SIGNON, CONTEXT SIGNON or SET_CLIENT_ID. You can retrieve
the DB2 accounting token with the CURRENT CLIENT_ACCTNG special
register only if the DDF accounting string is not set.
accounting-interval
A 6-byte area with that specifies when DB2 writes an accounting record.
If you specify COMMIT in that area, DB2 writes an accounting record each
time that the application issues SRRCMIT without open held cursors. If the
accounting interval is COMMIT and an SRRCMIT is issued while a held cursor
is open, the accounting interval spans that commit and ends at the next valid
Chapter 2. Connecting to DB2 from your application program 99
|
|
|
|
accounting interval end point (such as the next SRRCMIT that is issued
without open held cursors, application termination, or SIGNON with a new
authorization ID).
If you specify any other value, DB2 writes an accounting record when the
application terminates or when you call the SIGNON function with a new
authorization ID.
primary-authid
An 8-byte area in which you can put a primary authorization ID. If you are not
passing the authorization ID to DB2 explicitly, put X00 or a blank in the first
byte of the area.
ACEE-address
The 4-byte address of an ACEE that you pass to DB2. If you do not want to
provide an ACEE, specify 0 in this field.
secondary-authid
An 8-byte area in which you can put a secondary authorization ID. If you do
not pass the authorization ID to DB2 explicitly, put X00 or a blank in the first
byte of the area. If you enter a secondary authorization ID, you must also enter
a primary authorization ID.
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify reascoder, you must also specify retcode.
user
A 16-byte area that contains the user ID of the client end user. You can use this
parameter to provide the identity of the client end user for accounting and
monitoring purposes. DB2 displays this user ID in the output from the
DISPLAY THREAD command and in DB2 accounting and statistics trace
records. Setting the user ID sets the value of the CURRENT CLIENT_USERID
special register. If user is less than 16 characters long, you must pad it on the
right with blanks to a length of 16 characters.
This parameter is optional. If you specify user, you must also specify retcode
and reascode. If you do not specify this parameter, no user ID is associated with
the connection.
appl
A 32-byte area that contains the application or transaction name of the end
users application. You can use this parameter to provide the identity of the
client end user for accounting and monitoring purposes. DB2 displays the
application name in the output from the DISPLAY THREAD command and in
DB2 accounting and statistics trace records. Setting the application name sets
the value of the CURRENT CLIENT_APPLNAME special register. If appl is less
than 32 characters long, you must pad it on the right with blanks to a length of
32 characters.
100 Application Programming and SQL Guide
|
|
|
This parameter is optional. If you specify appl, you must also specify retcode,
reascode, and user. If you do not specify this parameter, no application or
transaction is associated with the connection.
ws An 18-byte area that contains the workstation name of the client end user. You
can use this parameter to provide the identity of the client end user for
accounting and monitoring purposes. DB2 displays the workstation name in
the output from the DISPLAY THREAD command and in DB2 accounting and
statistics trace records. Setting the workstation name sets the value of the
CURRENT CLIENT_WRKSTNNAME special register. If ws is less than 18
characters long, you must pad it on the right with blanks to a length of 18
characters.
This parameter is optional. If you specify ws, you must also specify retcode,
reascode, user, and appl. If you do not specify this parameter, no workstation
name is associated with the connection.
You can also change the value of the workstation name with RRSAF functions
SIGNON, CONTEXT SIGNON or SET_CLIENT_ID. You can retrieve the
workstation name with the CURRENT CLIENT_WRKSTNNAME special
register.
xid
A 4-byte area that indicates whether the thread is part of a global transaction.
A DB2 thread that is part of a global transaction can share locks with other
DB2 threads that are part of the same global transaction and can access and
modify the same data. A global transaction exists until one of the threads that
is part of the global transaction is committed or rolled back.
You can specify one of the following values for xid:
0 Indicates that the thread is not part of a global transaction. The value 0
must be specified as a binary integer.
1 Indicates that the thread is part of a global transaction and that DB2
should retrieve the global transaction ID from RRS. If a global
transaction ID already exists for the task, the thread becomes part of
the associated global transaction. Otherwise, RRS generates a new
global transaction ID. The value 1 must be specified as a binary
integer. Alternatively, if you want DB2 to return the generated global
transaction ID to the caller, specify an address instead of 1.
address The 4-byte address of an area into which you enter a global transaction
ID for the thread. If the global transaction ID already exists, the thread
becomes part of the associated global transaction. Otherwise, RRS
creates a new global transaction with the ID that you specify.
Alternatively, if you want DB2 to generate and return a global
transaction ID, pass the address of a null global transaction ID by
setting the format ID field of the global transaction ID to binary -1
(FFFFFFFX). DB2 then replaces the contents of the area with the
generated transaction ID. The area at the specified address must be in
writable storage and have a length of at least 140 bytes to
accommodate the largest possible transaction ID value.
The format of a global transaction ID is shown in the description of the
RRSAF SIGNON function.
accounting-string
A one-byte length field and a 255-byte area in which you can put a value for a
DB2 accounting string. This value is placed in the DDF accounting trace
Chapter 2. Connecting to DB2 from your application program 101
records in the QMDASQLI field, which is mapped by DSNDQMDA DSECT. If
accounting-string is less than 255 characters, you must pad it on the right with
zeros to a length of 255 bytes. The entire 256 bytes is mapped by DSNDQMDA
DSECT.
This parameter is optional. If you specify this accounting-string, you must also
specify retcode, reascode, user, appl and xid. If you do not specify this parameter,
no accounting string is associated with the connection.
You can also change the value of the accounting string with RRSAF functions
AUTH SIGNON, CONTEXT SIGNON, or SET_CLIENT_ID.
You can retrieve the DDF suffix portion of the accounting string with the
CURRENT CLIENT_ACCTNG special register. The suffix portion of
accounting-string can contain a maximum of 200 characters. The QMDASFLN
field contains the accounting suffix length, and the QMDASUFX field contains
the accounting suffix value. If the DDF accounting string is set, you cannot
query the accounting token with the CURRENT CLIENT_ACCTNG special
register.
Example of RRSAF AUTH SIGNON calls
The following table shows a AUTH SIGNON call in each language.
Table 29. Examples of RRSAF AUTH SIGNON calls
Language Call example
Assembler CALL DSNRLI,(ASGNONFN,CORRID,ACCTTKN,ACCTINT,PAUTHID,ACEEPTR, SAUTHID,RETCODE,REASCODE,
USERID,APPLNAME,WSNAME,XIDPTR)
C
1
fnret=dsnrli(&asgnonfn[0], &corrid[0], &accttkn[0], &acctint[0], &pauthid[0], &aceeptr,
&sauthid[0], &retcode, &reascode, &userid[0], &applname[0], &wsname[0], &xidptr);
COBOL CALL 'DSNRLI' USING ASGNONFN CORRID ACCTTKN ACCTINT PAUTHID ACEEPTR SAUTHID RETCODE REASCODE
USERID APPLNAME WSNAME XIDPTR.
Fortran CALL DSNRLI(ASGNONFN,CORRID,ACCTTKN,ACCTINT,PAUTHID,ACEEPTR, SAUTHID,RETCODE,REASCODE,USERID,
APPLNAME,WSNAME,XIDPTR)
PL/I
1
CALL DSNRLI(ASGNONFN,CORRID,ACCTTKN,ACCTINT,PAUTHID,ACEEPTR, SAUTHID,RETCODE,REASCODE,USERID,
APPLNAME,WSNAME,XIDPTR);
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
Related reference
SIGNON function for RRSAF on page 94
CONTEXT SIGNON function for RRSAF
The RRSAF CONTEXT SIGNON function establishes a primary authorization ID
and one or more secondary authorization IDs for a connection.
Requirement: Before you invoke CONTEXT SIGNON, you must have called the
RRS context services function Set Context Data (CTXSDTA) to store a primary
authorization ID and optionally, the address of an ACEE in the context data whose
context key you supply as input to CONTEXT SIGNON.
102 Application Programming and SQL Guide
The CONTEXT SIGNON function uses the context key to retrieve the primary
authorization ID from data that is associated with the current RRS context. DB2
uses the RRS context services function Retrieve Context Data (CTXRDTA) to
retrieve context data that contains the authorization ID and ACEE address. The
context data must have the following format:
Version number
A 4-byte area that contains the version number of the context data. Set this
area to 1.
Server product name
An 8-byte area that contains the name of the server product that set the
context data.
ALET A 4-byte area that can contain an ALET value. DB2 does not reference this
area.
ACEE address
A 4-byte area that contains an ACEE address or 0 if an ACEE is not
provided. DB2 requires that the ACEE is in the home address space of the
task.
If you pass an ACEE address, the CONTEXT SIGNON function uses the
value in ACEEGRPN as the secondary authorization ID if the length of the
group name (ACEEGRPL) is not 0.
primary-authid
An 8-byte area that contains the primary authorization ID to be used. If the
authorization ID is less than 8 bytes in length, pad it on the right with
blank characters to a length of 8 bytes.
If the new primary authorization ID is not different than the current
primary authorization ID (which was established when the IDENTIFY
function was invoked or at a previous SIGNON invocation), DB2 invokes
only the signon exit. If the value has changed, DB2 establishes a new
primary authorization ID and new SQL authorization ID and then invokes
the signon exit.
Generally, you issue a CONTEXT SIGNON call after an IDENTIFY call and before
a CREATE THREAD call. You can also issue a CONTEXT SIGNON call if the
application is at a point of consistency, and one of the following conditions is true:
v The value of reuse in the CREATE THREAD call was RESET.
v The value of reuse in the CREATE THREAD call was INITIAL, no held cursors
are open, the package or plan is bound with KEEPDYNAMIC(NO), and all
special registers are at their initial state. If open held cursors exist or the package
or plan is bound with KEEPDYNAMIC(YES), a SIGNON call is permitted only if
the primary authorization ID has not changed.
The following diagram shows the syntax for the CONTEXT SIGNON function.
Chapter 2. Connecting to DB2 from your application program 103
DSNRLI CONTEXT SIGNON function
CALL DSNRLI ( function, correlation-id, accounting-token, accounting-interval, context-key

,retcode
,reascode
,user
,appl
,ws
,xid
,accounting-string
)
Parameters point to the following areas:
function
An 18-byte area that contains CONTEXT SIGNON followed by four blanks.
correlation-id
A 12-byte area in which you can put a DB2 correlation ID. The correlation ID is
displayed in DB2 accounting and statistics trace records. You can use the
correlation ID to correlate work units. This token appears in output from the
DISPLAY THREAD command. If you do not want to specify a correlation ID,
fill the 12-byte area with blanks.
accounting-token
A 22-byte area in which you can put a value for a DB2 accounting token. This
value is displayed in DB2 accounting and statistics trace records in the
QWHCTOKEN field, which is mapped by DSNDQWHC DSECT. Setting the
value of the accounting token sets the value of the CURRENT
CLIENT_ACCTNG special register. If accounting-token is less than 22 characters
long, you must pad it on the right with blanks to a length of 22 characters. If
you do not want to specify an accounting token, fill the 22-byte area with
blanks.
You can also change the value of the DB2 accounting token with RRSAF
functions SIGNON, AUTH SIGNON, or SET_CLIENT_ID. You can retrieve the
DB2 accounting token with the CURRENT CLIENT_ACCTNG special register
only if the DDF accounting string is not set.
accounting-interval
A 6-byte area that specifies when DB2 writes an accounting record.
If you specify COMMIT in that area, DB2 writes an accounting record each
time that the application issues SRRCMIT without open held cursors. If the
accounting interval is COMMIT and an SRRCMIT is issued while a held cursor
is open, the accounting interval spans that commit and ends at the next valid
accounting interval end point (such as the next SRRCMIT that is issued
without open held cursors, application termination, or SIGNON with a new
authorization ID).
If you specify any other value, DB2 writes an accounting record when the
application terminates or when you call the SIGNON function with a new
authorization ID.
context-key
A 32-byte area in which you put the context key that you specified when you
called the RRS Set Context Data (CTXSDTA) service to save the primary
authorization ID and an optional ACEE address.
104 Application Programming and SQL Guide
|
|
|
|
|
|
|
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify reascode, you must also specify retcode.
user
A 16-byte area that contains the user ID of the client end user. You can use this
parameter to provide the identity of the client end user for accounting and
monitoring purposes. DB2 displays this user ID in the output from the
DISPLAY THREAD command and in DB2 accounting and statistics trace
records. Setting the user ID sets the value of the CURRENT CLIENT_USERID
special register. If user is less than 16 characters long, you must pad it on the
right with blanks to a length of 16 characters.
This parameter is optional. If you specify user, you must also specify retcode
and reascode. If you do not specify user, no user ID is associated with the
connection.
appl
A 32-byte area that contains the application or transaction name of the end
users application. You can use this parameter to provide the identity of the
client end user for accounting and monitoring purposes. DB2 displays the
application name in the output from the DISPLAY THREAD command and in
DB2 accounting and statistics trace records. Setting the application name sets
the value of the CURRENT CLIENT_APPLNAME special register. If appl is less
than 32 characters long, you must pad it on the right with blanks to a length of
32 characters.
This parameter is optional. If you specify appl, you must also specify retcode,
reascode, and user. If you do not specify appl, no application or transaction is
associated with the connection.
ws An 18-byte area that contains the workstation name of the client end user. You
can use this parameter to provide the identity of the client end user for
accounting and monitoring purposes. DB2 displays the workstation name in
the output from the DISPLAY THREAD command and in DB2 accounting and
statistics trace records. Setting the workstation name sets the value of the
CURRENT CLIENT_WRKSTNNAME special register. If ws is less than 18
characters long, you must pad it on the right with blanks to a length of 18
characters.
This parameter is optional. If you specify ws, you must also specify retcode,
reascode, user, and appl. If you do not specify ws, no workstation name is
associated with the connection.
You can also change the value of the workstation name with the RRSAF
functions SIGNON, AUTH SIGNON, or SET_CLIENT_ID. You can retrieve the
workstation name with the CLIENT_WRKSTNNAME special register.
xid
A 4-byte area that indicates whether the thread is part of a global transaction.
A DB2 thread that is part of a global transaction can share locks with other
DB2 threads that are part of the same global transaction and can access and
Chapter 2. Connecting to DB2 from your application program 105
modify the same data. A global transaction exists until one of the threads that
is part of the global transaction is committed or rolled back.
You can specify one of the following values for xid:
0 Indicates that the thread is not part of a global transaction. The value 0
must be specified as a binary integer.
1 Indicates that the thread is part of a global transaction and that DB2
should retrieve the global transaction ID from RRS. If a global
transaction ID already exists for the task, the thread becomes part of
the associated global transaction. Otherwise, RRS generates a new
global transaction ID. The value 1 must be specified as a binary
integer. Alternatively, if you want DB2 to return the generated global
transaction ID to the caller, specify an address instead of 1.
address The 4-byte address of an area into which you enter a global transaction
ID for the thread. If the global transaction ID already exists, the thread
becomes part of the associated global transaction. Otherwise, RRS
creates a new global transaction with the ID that you specify.
Alternatively, if you want DB2 to generate and return a global
transaction ID, pass the address of a null global transaction ID by
setting the format ID field of the global transaction ID to binary -1
(FFFFFFFX). DB2 then replaces the contents of the area with the
generated transaction ID. The area at the specified address must be in
writable storage and have a length of at least 140 bytes to
accommodate the largest possible transaction ID value.
The format of a global transaction ID is shown in the description of the
RRSAF SIGNON function.
accounting-string
A one-byte length field and a 255-byte area in which you can put a value for a
DB2 accounting string. This value is placed in the DDF accounting trace
records in the QMDASQLI field, which is mapped by DSNDQMDA DSECT. If
accounting-string is less than 255 characters, you must pad it on the right with
zeros to a length of 255 bytes. The entire 256 bytes is mapped by DSNDQMDA
DSECT.
This parameter is optional. If you specify this accounting-string, you must also
specify retcode, reascode, user, appl and xid. If you do not specify this parameter,
no accounting string is associated with the connection.
You can also change the value of the accounting string with RRSAF functions
AUTH SIGNON, CONTEXT SIGNON, or SET_CLIENT_ID.
You can retrieve the DDF suffix portion of the accounting string with the
CURRENT CLIENT_ACCTNG special register. The suffix portion of
accounting-string can contain a maximum of 200 characters. The QMDASFLN
field contains the accounting suffix length, and the QMDASUFX field contains
the accounting suffix value. If the DDF accounting string is set, you cannot
query the accounting token with the CURRENT CLIENT_ACCTNG special
register.
Example of RRSAF CONTEXT SIGNON calls
The following table shows a CONTEXT SIGNON call in each language.
106 Application Programming and SQL Guide
Table 30. Examples of RRSAF CONTEXT SIGNON calls
Language Call example
Assembler CALL DSNRLI,(CSGNONFN,CORRID,ACCTTKN,ACCTINT,CTXTKEY, RETCODE,REASCODE,USERID,APPLNAME,
WSNAME,XIDPTR)
C
1
fnret=dsnrli(&csgnonfn[0], &corrid[0], &accttkn[0], &acctint[0], &ctxtkey[0], &retcode,
&reascode, &userid[0], &applname[0], &wsname[0], &xidptr);
COBOL CALL 'DSNRLI' USING CSGNONFN CORRID ACCTTKN ACCTINT CTXTKEY RETCODE REASCODE USERID APPLNAME
WSNAME XIDPTR.
Fortran CALL DSNRLI(CSGNONFN,CORRID,ACCTTKN,ACCTINT,CTXTKEY, RETCODE,REASCODE, USERID,APPLNAME,
WSNAME,XIDPTR)
PL/I
1
CALL DSNRLI(CSGNONFN,CORRID,ACCTTKN,ACCTINT,CTXTKEY, RETCODE,REASCODE,USERID,APPLNAME,
WSNAME,XIDPTR);
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
Related reference
SIGNON function for RRSAF on page 94
SET_ID function for RRSAF
The RRSAF SET_ID function sets a new value for the client program ID that can be
used to identify the end user. The function then passes this information to DB2
when the next SQL request is processed.
The following diagram shows the syntax of the SET_ID function.
DSNRLI SET_ID function
CALL DSNRLI ( function, program-id )
, retcode
, reascode

Parameters point to the following areas:


function
An 18-byte area that contains SET_ID followed by 12 blanks.
program-id
An 80-byte area that contains the caller-provided string to be passed to DB2. If
program-id is less than 80 characters, you must pad it with blanks on the right
to a length of 80 characters.
DB2 places the contents of program-id into IFCID 316 records, along with other
statistics, so that you can identify which program is associated with a
particular SQL statement.
retcode
A 4-byte area in which RRSAF places the return code.
Chapter 2. Connecting to DB2 from your application program 107
This parameter is optional. If you do not specify retcode RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify reascode, you must also specify retcode.
Example of RRSAF SET_ID calls
The following table shows a SET_ID call in each language.
Table 31. Examples of RRSAF SET_ID calls
Language Call example
Assembler CALL DSNRLI,(SETIDFN,PROGID,RETCODE,REASCODE)
C
1
fnret=dsnrli(&setidfn[0], &progid[0], &retcode, &reascode);
COBOL CALL 'DSNRLI' USING SETIDFN PROGID RETCODE REASCODE.
Fortran CALL DSNRLI(SETIDFN,PROGID,RETCODE,REASCODE)
PL/I
1
CALL DSNRLI(SETIDFN,PROGID,RETCODE,REASCODE);
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
SET_CLIENT_ID function for RRSAF
The RRSAF SET_CLIENT_ID function sets new values for the client user ID, the
application program name, the workstation name, the accounting token, and the
DDF client accounting string. The function then passes this information to DB2
when the next SQL request is processed.
These values can be used to identify the end user. The calling program defines the
contents of these parameters. DB2 places the parameter values in the output from
the DISPLAY THREAD command and in DB2 accounting and statistics trace
records.
The following diagram shows the syntax of the SET_CLIENT_ID function.
108 Application Programming and SQL Guide
DSNRLI SET_CLIENT_ID function
CALL DSNRLI ( function, accounting-token, user, appl, ws
)
,retcode
,reascode
,accounting-string

Parameters point to the following areas:


function
An 18-byte area that contains SET_CLIENT_ID followed by 5 blanks.
accounting-token
A 22-byte area in which you can put a value for a DB2 accounting token. This
value is placed in the DB2 accounting and statistics trace records in the
QWHCTOKEN field, which is mapped by DSNDQWHC DSECT. If
accounting-token is less than 22 characters long, you must pad it on the right
with blanks to a length of 22 characters.
You can omit this parameter by specifying a value of 0 in the parameter list.
Alternatively, you can change the value of the DB2 accounting token with the
RRSAF functions SIGNON, AUTH SIGNON, or CONTEXT SIGNON. You can
retrieve the DB2 accounting token with the CURRENT CLIENT_ACCTNG
special register only if the DDF accounting string is not set.
user
A 16-byte area that contains the user ID of the client end user. You can use this
parameter to provide the identity of the client end user for accounting and
monitoring purposes. DB2 places this user ID in the output from the DISPLAY
THREAD command and in DB2 accounting and statistics trace records. If user
is less than 16 characters long, you must pad it on the right with blanks to a
length of 16 characters.
You can omit this parameter by specifying a value of 0 in the parameter list.
You can also change the value of the client user ID with the RRSAF functions
SIGNON, AUTH SIGNON, or CONTEXT SIGNON. You can retrieve the client
user ID with the CLIENT_USERID special register.
appl
An 32-byte area that contains the application or transaction name of the end
users application. You can use this parameter to provide the identity of the
client end user for accounting and monitoring purposes. DB2 places the
application name in the output from the DISPLAY THREAD command and in
DB2 accounting and statistics trace records. If appl is less than 32 characters,
you must pad it on the right with blanks to a length of 32 characters.
You can omit this parameter by specifying a value of 0 in the parameter list.
You can also change the value of the application name with the RRSAF
functions SIGNON, AUTH SIGNON, or CONTEXT SIGNON. You can retrieve
the application name with the CLIENT_APPLNAME special register.
ws An 18-byte area that contains the workstation name of the client end user. You
can use this parameter to provide the identity of the client end user for
accounting and monitoring purposes. DB2 places this workstation name in the
Chapter 2. Connecting to DB2 from your application program 109
output from the DISPLAY THREAD command and in DB2 accounting and
statistics trace records. If ws is less than 18 characters, you must pad it on the
right with blanks to a length of 18 characters.
You can omit this parameter by specifying a value of 0 in the parameter list.
You can also change the value of the workstation name with the RRSAF
functions SIGNON, AUTH SIGNON, or CONTEXT SIGNON. You can retrieve
the workstation name with the CLIENT_WRKSTNNAME special register.
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify reascode, you must also specify retcode.
accounting-string
A one-byte length field and a 255-byte area in which you can put a value for a
DB2 accounting string. This value is placed in the DDF accounting trace
records in the QMDASQLI field, which is mapped by DSNDQMDA DSECT. If
accounting-string is less than 255 characters, you must pad it on the right with
zeros to a length of 255 bytes. The entire 256 bytes is mapped by DSNDQMDA
DSECT.
This parameter is optional. If you specify this accounting-string, you must also
specify retcode, reascode, user, appl and xid. If you do not specify this parameter,
no accounting string is associated with the connection.
You can also change the value of the accounting string with RRSAF functions
AUTH SIGNON, CONTEXT SIGNON, or SET_CLIENT_ID.
You can retrieve the DDF suffix portion of the accounting string with the
CURRENT CLIENT_ACCTNG special register. The suffix portion of
accounting-string can contain a maximum of 200 characters. The QMDASFLN
field contains the accounting suffix length, and the QMDASUFX field contains
the accounting suffix value. If the DDF accounting string is set, you cannot
query the accounting token with the CURRENT CLIENT_ACCTNG special
register.
Example of RRSAF SET_CLIENT_ID calls
The following table shows a SET_CLIENT_ID call in each language.
Table 32. Examples of RRSAF SET_CLIENT_ID calls
Language Call example
Assembler CALL DSNRLI,(SECLIDFN,ACCT,USER,APPL,WS,RETCODE,REASCODE)
C
1
fnret=dsnrli(&seclidfn[0], &acct[0], &user[0], &appl[0], &ws[0], &retcode, &reascode);
COBOL CALL 'DSNRLI' USING SECLIDFN ACCT USER APPL WS RETCODE REASCODE.
Fortran CALL DSNRLI(SECLIDFN,ACCT,USER,APPL,WS,RETCODE,REASCODE)
PL/I
1
CALL DSNRLI(SECLIDFN,ACCT,USER,APPL,WS,RETCODE,REASCODE);
110 Application Programming and SQL Guide
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
CREATE THREAD function for RRSAF
The RRSAF CREATE THREAD function allocates the DB2 resources that are
required for an application to issue SQL or IFI requests. This function must
complete before the application can execute SQL statements or IFI requests.
The following diagram shows the syntax of the CREATE THREAD function.
DSNRLI CREATE THREAD function
CALL DSNRLI ( function, plan, collection, reuse

, retcode
, reascode
, pklistptr
)
Parameters point to the following areas:
function
An 18-byte area that contains CREATE THREAD followed by five blanks.
plan
An 8-byte DB2 plan name. RRSAF allocates the named plan.
If you provide a collection name instead of a plan name, specify the question
mark character (?) in the first byte of this field. DB2 then allocates a special
plan named ?RRSAF and uses the value that you specify for collection . When
DB2 allocates a plan named ?RRSAF, DB2 checks authorization to execute the
package in the same way as it checks authorization to execute a package from
a requester other than DB2 for z/OS.
If you do not provide a collection name in the collection field, you must enter a
valid plan name in this field.
collection
An 18-byte area in which you enter a collection name. DB2 uses the collection
names to locate a package that is associated with the first SQL statement in the
program.
When you provide a collection name and put the question mark character (?)
in the plan field, DB2 allocates a plan named ?RRSAF and a package list that
contains the following two entries:
v The specified collection name.
v An entry that contains * for the location, collection name, and package name.
(This entry lets the application access remote locations and access packages
in collections other than the default collection that is specified at create
thread time.)
Chapter 2. Connecting to DB2 from your application program 111
The application can use the SET CURRENT PACKAGESET statement to change
the collection ID that DB2 uses to locate a package.
If you provide a plan name in the plan field, DB2 ignores the value in the
collection field.
reuse
An 8-byte area that controls the action that DB2 takes if a SIGNON call is
issued after a CREATE THREAD call. Specify one of the following values in
this field:
RESET
Releases any held cursors and reinitializes the special registers
INITIAL
Does not allow the SIGNON call
This parameter is required. If the 8-byte area does not contain either RESET or
INITIAL, the default value is INITIAL.
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify reascode, you must also specify retcode.
pklistptr
A 4-byte field that contains a pointer to a user-supplied data area that contains
a list of collection IDs. A collection ID is an SQL identifier of 1 to 128 letters,
digits, or the underscore character that identifies a collection of packages. The
length of the data area is a maximum of 2050 bytes. The data area contains a
2-byte length field, followed by up to 2048 bytes of collection ID entries,
separated by commas.
When you specify pklistptr and the question mark character (?) in the plan field,
DB2 allocates a special plan named ?RRSAF and a package list that contains
the following entries:
v The collection names that you specify in the data area to which pklistptr
points
v An entry that contains * for the location, collection ID, and package name
If you also specify collection, DB2 ignores that value.
Each collection entry must be of the form collection-ID.*, *.collection-ID.*, or *.*.*.
collection-ID and must follow the naming conventions for a collection ID, as
described in the description of the BIND and REBIND options.
DB2 uses the collection names to locate a package that is associated with the
first SQL statement in the program. The entry that contains *.*.* lets the
application access remote locations and access packages in collections other
than the default collection that is specified at create thread time.
The application can use the SET CURRENT PACKAGESET statement to change
the collection ID that DB2 uses to locate a package.
112 Application Programming and SQL Guide
This parameter is optional. If you specify this parameter, you must also specify
retcode and reascode.
If you provide a plan name in the plan field, DB2 ignores the pklistptr value.
Recommendation: Using a package list can have a negative impact on
performance. For better performance, specify a short package list.
Example of RRSAF CREATE THREAD calls
The following table shows a CREATE THREAD call in each language.
Table 33. Examples of RRSAF CREATE THREAD calls
Language Call example
Assembler CALL DSNRLI,(CRTHRDFN,PLAN,COLLID,REUSE,RETCODE,REASCODE,PKLISTPTR)
C
1
fnret=dsnrli(&crthrdfn[0], &plan[0], &collid[0], &reuse[0], &retcode, &reascode, &pklistptr);
COBOL CALL 'DSNRLI' USING CRTHRDFN PLAN COLLID REUSE RETCODE REASCODE PKLSTPTR.
Fortran CALL DSNRLI(CRTHRDFN,PLAN,COLLID,REUSE,RETCODE,REASCODE,PKLSTPTR)
PL/I
1
CALL DSNRLI(CRTHRDFN,PLAN,COLLID,REUSE,RETCODE,REASCODE,PKLSTPTR);
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
Authorizing plan or package access through applications (DB2 Administration
Guide)
Related reference
BIND and REBIND options (DB2 Command Reference)
TERMINATE THREAD function for RRSAF
The RRSAF TERMINATE THREAD function deallocates DB2 resources that are
associated with a plan and were previously allocated for an application by the
CREATE THREAD function. You can then use the CREATE THREAD function to
allocate another plan with the same connection.
If you call the TERMINATE THREAD function and the application is not at a point
of consistency, RRSAF returns reason code X00C12211.
The following diagram shows the syntax of the TERMINATE THREAD function.
DSNRLI TERMINATE THREAD function
CALL DSNRLI ( function, )
, retcode
, reascode

Chapter 2. Connecting to DB2 from your application program 113


Parameters point to the following areas:
function
An 18-byte area the contains TERMINATE THREAD followed by two blanks.
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify reascode, you must also specify retcode.
Example of RRSAF TERMINATE THREAD calls
The following table shows a TERMINATE THREAD call in each language.
Table 34. Examples of RRSAF TERMINATE THREAD calls
Language Call example
Assembler CALL DSNRLI,(TRMTHDFN,RETCODE,REASCODE)
C
1
fnret=dsnrli(&trmthdfn[0], &retcode, &reascode);
COBOL CALL 'DSNRLI' USING TRMTHDFN RETCODE REASCODE.
Fortran CALL DSNRLI(TRMTHDFN,RETCODE,REASCODE)
PL/I
1
CALL DSNRLI(TRMTHDFN,RETCODE,REASCODE);
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
TERMINATE IDENTIFY function for RRSAF
The RRSAF TERMINATE IDENTIFY function terminates a connection to DB2.
Calling the TERMINATE IDENTIFY function is optional. If you do not call it, DB2
performs the same functions when the task terminates.
If DB2 terminates, the application must issue TERMINATE IDENTIFY to reset the
RRSAF control blocks. This action ensures that future connection requests from the
task are successful when DB2 restarts.
The TERMINATE IDENTIFY function removes the calling tasks connection to DB2.
If no other task in the address space has an active connection to DB2, DB2 also
deletes the control block structures that were created for the address space and
removes the cross-memory authorization.
If the application is not at a point of consistency when you call the TERMINATE
IDENTIFY function, RRSAF returns reason code X00C12211.
114 Application Programming and SQL Guide
If the application allocated a plan, and you call the TERMINATE IDENTIFY
function without first calling the TERMINATE THREAD function, DB2 deallocates
the plan before terminating the connection.
The following diagram shows the syntax of the TERMINATE IDENTIFY function.
DSNRLI TERMINATE IDENTIFY function
CALL DSNRLI ( function )
, retcode
, reascode

Parameters point to the following areas:


function
An 18-byte area that contains TERMINATE IDENTIFY.
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify reascode, you must also specify retcode.
Example of RRSAF TERMINATE IDENTIFY calls
The following table shows a TERMINATE IDENTIFY call in each language.
Table 35. Examples of RRSAF TERMINATE IDENTIFY calls
Language Call example
Assembler CALL DSNRLI,(TMIDFYFN,RETCODE,REASCODE)
C
1
fnret=dsnrli(&tmidfyfn[0], &retcode, &reascode);
COBOL CALL 'DSNRLI' USING TMIDFYFN RETCODE REASCODE.
Fortran CALL DSNRLI(TMIDFYFN,RETCODE,REASCODE)
PL/I
1
CALL DSNRLI(TMIDFYFN,RETCODE,REASCODE);
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
Chapter 2. Connecting to DB2 from your application program 115
TRANSLATE function for RRSAF
The RRSAF TRANSLATE function converts a hexadecimal reason code for a DB2
error into a signed integer SQL code and a printable error message. The SQL code
and message text are placed in the SQLCODE and SQLSTATE host variables or
related fields of the SQLCA.
Consider the following rules and recommendations about when to use and not use
the TRANSLATE function:
v You cannot call the TRANSLATE function from the Fortran language.
v Call the TRANSLATE function only after a successful IDENTIFY operation. For
errors that occur during SQL or IFI requests, the TRANSLATE function performs
automatically.
v The TRANSLATE function translates codes that begin with X00F3, but it does
not translate RRSAF reason codes that begin with X00C1.
If you receive error reason code X00F30040 (resource unavailable) after an OPEN
request, the TRANSLATE function returns the name of the unavailable database
object in the last 44 characters of the SQLERRM field.
If the TRANSLATE function does not recognize the error reason code, it returns
SQLCODE -924 (SQLSTATE 58006) and places a printable copy of the original
DB2 function code and the return and error reason codes in the SQLERRM field.
The contents of registers 0 and 15 do not change, unless TRANSLATE fails. In this
case, register 0 is set to X00C12204, and register 15 is set to 200.
The following diagram shows the syntax of the TRANSLATE function.
DSNRLI TRANSLATE function
CALL DSNRLI ( function, sqlca )
, retcode
, reascode

Parameters point to the following areas:


function
An 18-byte area that contains the word TRANSLATE followed by nine blanks.
sqlca
The programs SQL communication area (SQLCA).
retcode
A 4-byte area in which RRSAF places the return code.
This parameter is optional. If you do not specify retcode, RRSAF places the
return code in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF places the reason code.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
If you specify reascode, you must also specify retcode.
116 Application Programming and SQL Guide
Example of RRSAF TRANSLATE calls
The following table shows a TRANSLATE call in each language.
Table 36. Examples of RRSAF TRANSLATE calls
Language Call example
Assembler CALL DSNRLI,(XLATFN,SQLCA,RETCODE,REASCODE)
C
1
fnret=dsnrli(&connfn[0], &sqlca, &retcode, &reascode);
COBOL CALL 'DSNRLI' USING XLATFN SQLCA RETCODE REASCODE.
PL/I
1
CALL DSNRLI(XLATFN,SQLCA,RETCODE,REASCODE);
Note:
1. For C, C++, and PL/I applications, you must include the appropriate compiler
directives, because DSNRLI is an assembler language program. These compiler
directives are described in the instructions for invoking RRSAF.
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
FIND_DB2_SYSTEMS function for RRSAF
The RRSAF FIND_DB2_SYSTEMS function identifies all active DB2 subsystems on
a z/OS LPAR.
The following diagram shows the syntax of the FIND_DB2_SYSTEMS function.
DSNRLI FIND_DB2_SYSTEMS function
CALL DSNRLI ( function , ssnma , activea , arraysz ,

, retcode
, reascode
)
Parameters point to the following areas:
function
An 18-byte area that contains FIND_DB2_SYSTEMS followed by two blanks.
ssnma
A storage area for an array of 4-byte character strings into which RRSAF places
the names of all the DB2 subsystems (SSIDs) that are defined for the current
LPAR. You must provide the storage area. If the array is larger than the
number of DB2 subsystems, RRSAF returns the value (four blanks) in all
unused array members.
activea
A storage area for an array of 4-byte values into which RRSAF returns an
indication of whether a defined subsystem is active. Each value is represented
as a fixed 31-bit integer. The value 1 means that the subsystem is active. The
value 0 means that the subsystem is not active. The size of this array must be
Chapter 2. Connecting to DB2 from your application program 117
|
|
|
|
|
|
|||||||||||||||||||||||
|
|
|||||||||||||||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
the same as the size of the ssnma array. If the array is larger than the number
of DB2 subsystems, RRSAF returns the value -1 in all unused array members.
The information in the activea array is the information that is available at the
point in time that you requested it and might change at any time.
arraysz
A 4-byte area, represented as a fixed 31-bit integer, that specifies the number of
entries for the ssnma and activea arrays. If the number of array entries is
insufficient to contain all of the subsystems defined on the current LPAR,
RRSAF uses all available entries and returns return code 4.
retcode
A 4-byte area in which RRSAF is to place the return code for this call to the
FIND_DB2_SYSTEMS function.
This parameter is optional. If you do not retcode, RRSAF places the return code
in register 15 and the reason code in register 0.
reascode
A 4-byte area in which RRSAF is to place the reason code for this call to the
FIND_DB2_SYSTEMS function.
This parameter is optional. If you do not specify reascode, RRSAF places the
reason code in register 0.
Example values that the FIND_DB2_SYSTEMS function returns
Assume that two subsystems are defined on the current LPAR. Subsystem DB2A is
active, and subsystem DB2B is stopped. Suppose that you invoke RRSAF with the
function FIND_DB2_SYSTEMS and a value of 3 for arraysz. The ssnma array and
activea array are set to the following values:
Table 37. Example values returned in the ssnma and activeaarrays
Array element number Values in ssnma array Values in activea array
1 DB2A 1
2 DB2B 0
3 (four blanks) -1
Related tasks
Invoking the Resource Recovery Services attachment facility on page 77
RRSAF return codes and reason codes
If you specify return code and reason code parameters in an RRSAF function call,
RRSAF returns the return code and reason code in those parameters. If you do not
specify those parameters or implicitly invoke RRSAF, RRSAF puts the return code
in register 15 and the reason code in register 0.
When the reason code begins with X00F3, except for X00F30006, you can use the
RRSAF TRANSLATE function to obtain error message text that can be printed and
displayed.
For SQL calls, RRSAF returns standard SQL return codes in the SQLCA. RRSAF
returns IFI return codes and reason codes in the instrumentation facility
communication area (IFCA).
118 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|||
|||
|||
|||
|
|
|
The following table lists the RRSAF return codes.
Table 38. RRSAF return codes
Return code Explanation
0 The call completed successfully.
4 Status information is available. See the
reason code for details.
>4 The call failed. See the reason code for
details.
Related reference
TRANSLATE function for RRSAF on page 116
Sample RRSAF scenarios
One or more tasks can use RRSAF to connect to DB2. This connection can be made
either implicitly or explicitly. For explicit connections, a task calls one or more of
the RRSAF connection functions.
A single task
The following example pseudocode illustrates a single task running in an address
space that explicitly connects to DB2 through RRSAF. z/OS RRS controls commit
processing when the task terminates normally.
IDENTIFY
SIGNON
CREATE THREAD
SQL or IFI
.
.
.
TERMINATE IDENTIFY
Multiple tasks
In the following scenario, multiple tasks in an address space explicitly connect to
DB2 through RRSAF. Task 1 executes no SQL statements and makes no IFI calls. Its
purpose is to monitor DB2 termination and startup ECBs and to check the DB2
release level.
TASK 1 TASK 2 TASK 3 TASK n
IDENTIFY IDENTIFY IDENTIFY IDENTIFY
SIGNON SIGNON SIGNON
CREATE THREAD CREATE THREAD CREATE THREAD
SQL SQL SQL
... ... ...
SRRCMIT SRRCMIT SRRCMIT
SQL SQL SQL
... ... ...
SRRCMIT SRRCMIT SRRCMIT
... ... ...
TERMINATE IDENTIFY
Reusing a DB2 thread
The following example pseudocode shows a DB2 thread that is reused by another
user at a point of consistency. When the application calls the SIGNON function for
user B, DB2 reuses the plan that is allocated by the CREATE THREAD function for
user A.
Chapter 2. Connecting to DB2 from your application program 119
IDENTIFY
SIGNON user A
CREATE THREAD
SQL
...
SRRCMIT
SIGNON user B
SQL
...
SRRCMIT
Switching DB2 threads between tasks
The following scenario shows how you can switch the threads for four users (A, B,
C, and D) among two tasks (1 and 2).
Task 1 Task 2
CTXBEGC (create context a) CTXBEGC (create context b)
CTXSWCH(a,0) CTXSWCH(b,0)
IDENTIFY IDENTIFY
SIGNON user A SIGNON user B
CREATE THREAD (Plan A) CREATE THREAD (plan B)
SQL SQL
... ...
CTXSWCH(0,a) CTXSWCH(0,b)
CTXBEGC (create context c) CTXBEGC (create context d)
CTXSWCH(c,0) CTXSWCH(d,0)
IDENTIFY IDENTIFY
SIGNON user C SIGNON user D
CREATE THREAD (plan C) CREATE THREAD (plan D)
SQL SQL
... ...
CTXSWCH(b,c) CTXSWCH(0,d)
SQL (plan B) ...
... CTXSWCH(a,0)
SQL (plan A)
The applications perform the following steps:
v Task 1 creates context a, switches contexts so that context a is active for task 1,
and calls the IDENTIFY function to initialize a connection to a subsystem. A task
must always call the IDENTIFY function before a context switch can occur. After
the IDENTIFY operation is complete, task 1 allocates a thread for user A, and
performs SQL operations.
At the same time, task 2 creates context b, switches contexts so that context b is
active for task 2, calls the IDENTIFY function to initialize a connection to the
subsystem, allocates a thread for user B, and performs SQL operations.
When the SQL operations complete, both tasks perform RRS context switch
operations. Those operations disconnect each DB2 thread from the task under
which it was running.
v Task 1 then creates context c, calls the IDENTIFY function to initialize a
connection to the subsystem, switches contexts so that context c is active for task
1, allocates a thread for user C, and performs SQL operations for user C.
Task 2 does the same operations for user D.
v When the SQL operations for user C complete, task 1 performs a context switch
operation to perform the following actions:
Switch the thread for user C away from task 1.
Switch the thread for user B to task 1.
120 Application Programming and SQL Guide
For a context switch operation to associate a task with a DB2 thread, the DB2
thread must have previously performed an IDENTIFY operation. Therefore,
before the thread for user B can be associated with task 1, task 1 must have
performed an IDENTIFY operation.
v Task 2 performs two context switch operations to perform the following actions:
Disassociate the thread for user D from task 2.
Associate the thread for user A with task 2.
Program examples for RRSAF
The Resource Recovery Services attachment facility (RRSAF) enables programs to
communicate with DB2. You can use RRSAF as an alternative to CAF.
Example JCL for invoking RRSAF
The following sample JCL shows how to use RRSAF in a batch environment. The
DSNRRSAF DD statement starts the RRSAF trace. Use that DD statement only if
you are diagnosing a problem.
//jobname JOB z/OS_jobcard_information
//RRSJCL EXEC PGM=RRS_application_program
//STEPLIB DD DSN=application_load_library
// DD DSN=DB2_load_library
.
.
.
//SYSPRINT DD SYSOUT=*
//DSNRRSAF DD DUMMY
//SYSUDUMP DD SYSOUT=*
Example of loading and deleting the RRSAF language interface
The following code segment shows how an application loads entry points DSNRLI
and DSNHLIR of the RRSAF language interface. Storing the entry points in
variables LIRLI and LISQL ensures that the application loads the entry points only
once. Delete the loaded modules when the application no longer needs to access
DB2.
****************************** GET LANGUAGE INTERFACE ENTRY ADDRESSES
LOAD EP=DSNRLI Load the RRSAF service request EP
ST R0,LIRLI Save this for RRSAF service requests
LOAD EP=DSNHLIR Load the RRSAF SQL call Entry Point
ST R0,LISQL Save this for SQL calls
* .
* . Insert connection service requests and SQL calls here
* .
DELETE EP=DSNRLI Correctly maintain use count
DELETE EP=DSNHLIR Correctly maintain use count
Example of using dummy entry point DSNHLI for RRSAF
Each of the DB2 attachment facilities contains an entry point named DSNHLI.
When you use RRSAF but do not specify the ATTACH(RRSAF) precompiler
option, the precompiler generates BALR instructions to DSNHLI for SQL
statements in your program. To find the correct DSNHLI entry point without
including DSNRLI in your load module, code a subroutine, with entry point
DSNHLI, that passes control to entry point DSNHLIR in the DSNRLI module.
DSNHLIR is unique to DSNRLI and is at the same location as DSNHLI in
DSNRLI. DSNRLI uses 31-bit addressing. If the application that calls this
intermediate subroutine uses 24-bit addressing, the intermediate subroutine must
account for the difference.
Chapter 2. Connecting to DB2 from your application program 121
In the following example, LISQL is addressable because the calling CSECT used
the same register 12 as CSECT DSNHLI. Your application must also establish
addressability to LISQL.
***********************************************************************
* Subroutine DSNHLI intercepts calls to LI EP=DSNHLI
***********************************************************************
DS 0D
DSNHLI CSECT Begin CSECT
STM R14,R12,12(R13) Prologue
LA R15,SAVEHLI Get save area address
ST R13,4(,R15) Chain the save areas
ST R15,8(,R13) Chain the save areas
LR R13,R15 Put save area address in R13
L R15,LISQL Get the address of real DSNHLI
BASSM R14,R15 Branch to DSNRLI to do an SQL call
* DSNRLI is in 31-bit mode, so use
* BASSM to assure that the addressing
* mode is preserved.
L R13,4(,R13) Restore R13 (caller's save area addr)
L R14,12(,R13) Restore R14 (return address)
RETURN (1,12) Restore R1-12, NOT R0 and R15 (codes)
Example of connecting to DB2 with RRSAF
This example uses the variables that are declared in the following code.
****************** VARIABLES SET BY APPLICATION ***********************
LIRLI DS F DSNRLI entry point address
LISQL DS F DSNHLIR entry point address
SSNM DS CL4 DB2 subsystem name for IDENTIFY
CORRID DS CL12 Correlation ID for SIGNON
ACCTTKN DS CL22 Accounting token for SIGNON
ACCTINT DS CL6 Accounting interval for SIGNON
PLAN DS CL8 DB2 plan name for CREATE THREAD
COLLID DS CL18 Collection ID for CREATE THREAD. If
* PLAN contains a plan name, not used.
REUSE DS CL8 Controls SIGNON after CREATE THREAD
CONTROL DS CL8 Action that application takes based
* on return code from RRSAF
****************** VARIABLES SET BY DB2 *******************************
STARTECB DS F DB2 startup ECB
TERMECB DS F DB2 termination ECB
EIBPTR DS F Address of environment info block
RIBPTR DS F Address of release info block
****************************** CONSTANTS ******************************
CONTINUE DC CL8'CONTINUE' CONTROL value: Everything OK
IDFYFN DC CL18'IDENTIFY ' Name of RRSAF service
SGNONFN DC CL18'SIGNON ' Name of RRSAF service
CRTHRDFN DC CL18'CREATE THREAD ' Name of RRSAF service
TRMTHDFN DC CL18'TERMINATE THREAD ' Name of RRSAF service
TMIDFYFN DC CL18'TERMINATE IDENTIFY' Name of RRSAF service
****************************** SQLCA and RIB **************************
EXEC SQL INCLUDE SQLCA
DSNDRIB Map the DB2 Release Information Block
******************* Parameter list for RRSAF calls ********************
RRSAFCLL CALL ,(*,*,*,*,*,*,*,*),VL,MF=L
The following example code shows how to issue requests for the RRSAF functions
IDENTIFY, SIGNON, CREATE THREAD, TERMINATE THREAD, and
TERMINATE IDENTIFY. This example does not show a task that waits on the DB2
termination ECB. You can code such a task and use the z/OS WAIT macro to
monitor the ECB. The task that waits on the termination ECB should detach the
sample code if the termination ECB is posted. That task can also wait on the DB2
startup ECB. This example waits on the startup ECB at its own task level.
122 Application Programming and SQL Guide
***************************** IDENTIFY ********************************
L R15,LIRLI Get the Language Interface address
CALL (15),(IDFYFN,SSNM,RIBPTR,EIBPTR,TERMECB,STARTECB),VL,MF=X
(E,RRSAFCLL)
BAL R14,CHEKCODE Call a routine (not shown) to check
* return and reason codes
CLC CONTROL,CONTINUE Is everything still OK
BNE EXIT If CONTROL not 'CONTINUE', stop loop
USING R8,RIB Prepare to access the RIB
L R8,RIBPTR Access RIB to get DB2 release level
WRITE 'The current DB2 release level is' RIBREL
***************************** SIGNON **********************************
L R15,LIRLI Get the Language Interface address
CALL (15),(SGNONFN,CORRID,ACCTTKN,ACCTINT),VL,MF=(E,RRSAFCLL)
BAL R14,CHEKCODE Check the return and reason codes
*************************** CREATE THREAD *****************************
L R15,LIRLI Get the Language Interface address
CALL (15),(CRTHRDFN,PLAN,COLLID,REUSE),VL,MF=(E,RRSAFCLL)
BAL R14,CHEKCODE Check the return and reason codes
****************************** SQL ************************************
* Insert your SQL calls here. The DB2 Precompiler
* generates calls to entry point DSNHLI. You should
* code a dummy entry point of that name to intercept
* all SQL calls. A dummy DSNHLI is shown in the following
* section.
************************ TERMINATE THREAD *****************************
CLC CONTROL,CONTINUE Is everything still OK?
BNE EXIT If CONTROL not 'CONTINUE', shut down
L R15,LIRLI Get the Language Interface address
CALL (15),(TRMTHDFN),VL,MF=(E,RRSAFCLL)
BAL R14,CHEKCODE Check the return and reason codes
************************ TERMINATE IDENTIFY ***************************
CLC CONTROL,CONTINUE Is everything still OK
BNE EXIT If CONTROL not 'CONTINUE', stop loop
L R15,LIRLI Get the Language Interface address
CALL (15),(TMIDFYFN),VL,MF=(E,RRSAFCLL)
BAL R14,CHEKCODE Check the return and reason codes
Controlling the CICS attachment facility from an application
Use the CICS attachment facility to access DB2 from CICS application programs.
You can start and stop the CICS attachment facility from within an application
program.
To control the CICS attachment facility:
1. To start the CICS attachment facility, perform one of the following actions:
v Include the following statement in your application:
EXEC CICS LINK PROGRAM('DSN2COM0')
v Use the system programming interface SET DB2CONN for the CICS
Transaction Server.
2. To stop the CICS attachment facility, perform one of the following actions:
v Include the following statement in your application:
EXEC CICS LINK PROGRAM('DSN2COM2')
v Use the system programming interface SET DB2CONN for the CICS
Transaction Server.
Related information
CICS Transaction Server Library at ibm.com
Chapter 2. Connecting to DB2 from your application program 123
Detecting whether the CICS attachment facility is operational
Before you execute SQL in a CICS program, you should test if the CICS attachment
facility is available. You do not need to do this test if the CICS attachment facility
is started and you are using standby mode.
When an SQL statement is executed, and the CICS attachment facility is in standby
mode, the attachment issues SQLCODE -923 with a reason code that indicates that
DB2 is not available.
To detect whether the CICS attachment facility is operational:
Use the INQUIRE EXITPROGRAM command for the CICS Transaction Server in
your application.
The following example shows how to use this command. In this example, the
INQUIRE EXITPROGRAM command tests whether the resource manager for SQL,
DSNCSQL, is up and running. CICS returns the results in the EIBRESP field of the
EXEC interface block (EIB) and in the field whose name is the argument of the
CONNECTST parameter (in this case, STST). If the EIBRESP value indicates that
the command completed normally and the STST value indicates that the resource
manager is available, you can then execute SQL statements.
STST DS F
ENTNAME DS CL8
EXITPROG DS CL8
.
.
.
MVC ENTNAME,=CL8'DSNCSQL'
MVC EXITPROG,=CL8'DSN2EXT1'
EXEC CICS INQUIRE EXITPROGRAM(EXITPROG) X
ENTRYNAME(ENTNAME) CONNECTST(STST) NOHANDLE
CLC EIBRESP,DFHRESP(NORMAL)
BNE NOTREADY
CLC STST,DFHVALUE(CONNECTED)
BNE NOTREADY
UPNREADY DS 0H
attach is up
NOTREADY DS 0H
attach isn't up yet
If you use the INQUIRE EXITPROGRAM command to avoid AEY9 abends and the
CICS attachment facility is down, the storm drain effect can occur. The storm drain
effect is a condition that occurs when a system continues to receive work, even
though that system is down.
Related concepts
Storm-drain effect (DB2 Data Sharing: Planning and Administration)
Related reference
-923 (DB2 Codes)
Related information
CICS Transaction Server Library at ibm.com
Improving thread reuse in CICS applications
In general, you want transactions to reuse threads whenever possible, because each
thread creation is associated with a high processor cost.
To improve thread reuse in CICS applications:
124 Application Programming and SQL Guide
Close all cursors that are declared with the WITH HOLD option before each sync
point. DB2 does not automatically close them. A thread for an application that
contains an open cursor cannot be reused. You should close all cursors
immediately after you finish using them.
Related concepts
Held and non-held cursors on page 639
Chapter 2. Connecting to DB2 from your application program 125
126 Application Programming and SQL Guide
Chapter 3. Including DB2 queries in an application program
A query is an SQL statement that returns data from a DB2 database. Your program
can communicate this SQL statement to DB2 in one of several ways. After
processing the statement, DB2 sends back a return code, which your program
should then test to determine the result of the operation.
To include DB2 queries in an application program:
1. Choose one of the following methods for communicating with DB2:
v Static SQL
v Embedded dynamic SQL
v Open Database Connectivity (ODBC)
v JDBC application support
v SQLJ application support
ODBC lets you access data through ODBC function calls in your application.
You execute SQL statements by passing them to DB2 through a ODBC function
call. ODBC eliminates the need for precompiling and binding your application
and increases the portability of your application by using the ODBC interface.
If you are writing your applications in Java

, you can use JDBC application


support to access DB2. JDBC is similar to ODBC but is designed specifically for
use with Java. In addition to using JDBC, you can use SQLJ application support
to access DB2. SQLJ is designed to simplify the coding of DB2 calls for Java
applications.
2. Optional: Declare the tables and views that you use. You can use DCLGEN to
generate these declarations.
3. Define the items that your program can use to check whether an SQL statement
executed successfully. You can either define an SQL communications area
(SQLCA) or declare SQLSTATE and SQLCODE host variables.
4. Define at least one SQL descriptor area (SQLDA).
5. Declare any of the following data items for passing data between DB2 and a
host language:
v host variables
v host variable arrays
v host structures
Ensure that you use the appropriate data types.
6. Code SQL statements to access DB2 data. Ensure that you delimit these
statements properly.
Consider using cursors to select a set of rows and then process the set either
one row at a time or one rowset at a time.
7. Check the execution of the SQL statements.
8. Handle any SQL error codes.
Related concepts
Dynamic SQL on page 267
DCLGEN (declarations generator) on page 129
JDBC application programming (DB2 Application Programming Guide and
Reference for Java)
SQLJ application programming (DB2 Application Programming Guide and
Reference for Java)
Copyright IBM Corp. 1983, 2008 127
Introduction to DB2 ODBC (DB2 ODBC Guide and Reference)
Related tasks
Retrieving a set of rows by using a cursor on page 636
Delimiting an SQL statement on page 255
Declaring table and view definitions
Before your program issues SQL statements that select, insert, update, or delete
data, the program should declare the tables and views that those statements access.
Your program is not required to declare tables or views, but doing so offers the
following advantages:
v Clear documentation in the program
The declaration specifies the structure of the table or view and the data type of
each column. You can refer to the declaration for the column names and data
types in the table or view.
v Assurance that your program uses the correct column names and data types
The DB2 precompiler uses your declarations to make sure that you have used
correct column names and data types in your SQL statements. The DB2
precompiler issues a warning message when the column names and data types
in SQL statements do not correspond to the table and view declarations in your
program.
To declare table and view definitions:
Perform one of the following actions:
v Include an SQL DECLARE TABLE statement in your program. Specify the name
of the table or view and list each column and its data type.
When you declare a table or view that contains a column with a distinct type,
declare that column with the source type of the distinct type rather than with
the distinct type itself. When you declare the column with the source type, DB2
can check embedded SQL statements that reference that column at precompile
time.
In a COBOL program, code the DECLARE TABLE statement in the
WORKING-STORAGE SECTION or LINKAGE SECTION within the DATA
DIVISION.
Example DECLARE statement in a COBOL program: The following DECLARE
TABLE statement in a COBOL program defines the DSN8910.DEPT table:
EXEC SQL
DECLARE DSN8910.DEPT TABLE
(DEPTNO CHAR(3) NOT NULL,
DEPTNAME VARCHAR(36) NOT NULL,
MGRNO CHAR(6) ,
ADMRDEPT CHAR(3) NOT NULL,
LOCATION CHAR(16) )
END-EXEC.
v Use DCLGEN, the declarations generator that is supplied with DB2, to create
these declarations for you and then include them in your program.
Restriction: You can use DCLGEN for only C, COBOL, and PL/I programs.
Related reference
DECLARE TABLE (DB2 SQL Reference)
128 Application Programming and SQL Guide
DCLGEN (declarations generator)
Your program should declare the tables and views that it accesses. DCLGEN, the
declarations generator that is supplied with DB2, produces these DECLARE
statements for C, COBOL, and PL/I programs, so that you do not need to code the
statements yourself. DCLGEN also generates corresponding host variable
structures.
DCLGEN generates a table or view declaration and puts it into a member of a
partitioned data set that you can include in your program. When you use
DCLGEN to generate a table declaration, DB2 gets the relevant information from
the DB2 catalog. The catalog contains information about the table or view
definition and the definition of each column within the table or view. DCLGEN
uses this information to produce an SQL DECLARE TABLE statement for the table
or view and a corresponding PL/I or C structure declaration or COBOL record
description.
Related reference
DCLGEN (DECLARATIONS GENERATOR) (DSN) (DB2 Command
Reference)
Generating table and view declarations by using DCLGEN
Your program should declare the tables and views that it accesses. For C, COBOL,
and PL/I programs you can use DCLGEN to produce these declarations, so that
you do not need to code the statements yourself. DCLGEN also generates
corresponding host variable structures.
Requirements:
v DB2 must be active before you can use DCLGEN.
v You can use DCLGEN for table declarations only if the table or view that you
are declaring already exists.
v If you use DCLGEN, you must use it before you precompile your program.
To generate table and view declarations by using DCLGEN:
1. Invoke DCLGEN by performing one of the following actions:
v To start DCLGEN from ISPF through DB2I: Select the DCLGEN option on
the DB2I Primary Option Menu panel. Then follow the detailed instructions
for generating table and view declarations by using DCLGEN from DB2I.
v To start DCLGEN directly from TSO: Sign on to TSO, issue the TSO
command DSN, and then issue the subcommand DCLGEN.
v To start DCLGEN directly from a CLIST: From a CLIST, running in TSO
foreground or background, issue DSN and then DCLGEN.
v To start DCLGEN with JCL: Supply the required information in JCL and run
DCLGEN in batch. Use the sample jobs DSNTEJ2C and DSNTEJ2P in the
prefix.SDSNSAMP library as models.
Requirement: If you want to start DCLGEN in the foreground and your
table names include DBCS characters, you must provide and display
double-byte characters. If you do not have a terminal that displays DBCS
characters, you can enter DBCS characters by using the hex mode of ISPF
edit.
DCLGEN creates the declarations in the specified data set.
DCLGEN generates a table or column name in the DECLARE statement as a
non-delimited identifier unless at least one of the following conditions is true:
Chapter 3. Including DB2 queries in an application program 129
v The name contains special characters and is not a DBCS string.
v The name is a DBCS string, and you have requested delimited DBCS names.
2. If you use an SQL reserved word as an identifier, edit the DCLGEN output to
add the appropriate SQL delimiters.
3. Make any other necessary edits to the DCLGEN output.
DCLGEN produces output that is intended to meet the needs of most users,
but occasionally, you need to edit the DCLGEN output to work in your specific
case. For example, DCLGEN is unable to determine whether a column that is
defined as NOT NULL also contains the DEFAULT clause, so you must edit the
DCLGEN output to add the DEFAULT clause to the appropriate column
definitions.
Related reference
DCLGEN (DECLARATIONS GENERATOR) (DSN) (DB2 Command
Reference)
DSN (TSO) (DB2 Command Reference)
Reserved words (DB2 SQL Reference)
Generating table and view declarations by using DCLGEN from
DB2I
DCLGEN generates table and view declarations and the corresponding variable
declarations for C, COBOL, and PL/I programs so that you do not have to code
these statements yourself. The easiest way to start DCLGEN is through DB2I.
To generate table and view declarations by using DCLGEN from DB2I:
1. From the DB2I Primary Option Menu panel, select the DCLGEN option. The
following DCLGEN panel is displayed:
2. Fill in the following fields on the DCLGEN panel:
1 SOURCE TABLE NAME
Is the unqualified name of the table, view, or created temporary table
for which you want DCLGEN to produce SQL data declarations. The
table can be stored at your DB2 location or at another DB2 location. To
specify a table name at another DB2 location, enter the table qualifier in
DSNEDP01 DCLGEN SSID: DSN
===>
Enter table name for which declarations are required:
1 SOURCE TABLE NAME ===>
2 TABLE OWNER ..... ===>
3 AT LOCATION ..... ===> (Optional)
Enter destination data set: (Can be sequential or partitioned)
4 DATA SET NAME ... ===>
5 DATA SET PASSWORD ===> (If password protected)
Enter options as desired:
6 ACTION .......... ===> ADD (ADD new or REPLACE old declaration)
7 COLUMN LABEL .... ===> NO (Enter YES for column label)
8 STRUCTURE NAME .. ===> (Optional)
9 FIELD NAME PREFIX ===> (Optional)
10 DELIMIT DBCS .... ===> YES (Enter YES to delimit DBCS identifiers)
11 COLUMN SUFFIX ... ===> NO (Enter YES to append column name)
12 INDICATOR VARS .. ===> NO (Enter YES for indicator variables)
13 ADDITIONAL OPTIONS===> YES (Enter YES to change additional options)
PRESS: ENTER to process END to exit HELP for more information
Figure 6. DCLGEN panel
130 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
the TABLE OWNER field and the location name in the AT LOCATION
field. DCLGEN generates a three-part table name from the SOURCE
TABLE NAME, TABLE OWNER, and AT LOCATION fields. You can
also use an alias for a table name.
To specify a table name that contains special characters or blanks,
enclose the name in apostrophes. If the name contains apostrophes, you
must double each one( ). For example, to specify a table named
DONS TABLE, enter the following text:
'DON''S TABLE'
The underscore is not handled as a special character in DCLGEN. For
example, the table name JUNE_PROFITS does not need to be enclosed
in apostrophes. Because COBOL field names cannot contain
underscores, DCLGEN substitutes hyphens (-) for single-byte
underscores in COBOL field names that are built from the table name.
You do not need to enclose DBCS table names in apostrophes.
If you do not enclose the table name in apostrophes, DB2 converts
lowercase characters to uppercase.
2 TABLE OWNER
Is the schema qualifier of the source table. If you do not specify this
value and the table is a local table, DB2 assumes that the table qualifier
is your TSO logon ID. If the table is at a remote location, you must
specify this value.
3 AT LOCATION
Is the location of a table or view at another DB2 subsystem. The value
of the AT LOCATION field becomes a prefix for the table name on the
SQL DECLARE statement, as follows: location_name, schema_name,
table_name For example, if the location name is PLAINS_GA, the
schema name is CARTER, and the table name is CROP_YIELD_89, the
following table name is included in the SQL DECLARE statement:
PLAINS_GA.CARTER.CROP_YIELD_89
The default is the local location name. This field applies to DB2 private
protocol access only. The location must be another DB2 for z/OS
subsystem.
4 DATA SET NAME
Is the name of the data set that you allocated to contain the
declarations that DCLGEN produces. You must supply a name; no
default exists.
The data set must already exist and be accessible to DCLGEN. The data
set can be either sequential or partitioned. If you do not enclose the
data set name in apostrophes, DCLGEN adds a standard TSO prefix
(user ID) and suffix (language). DCLGEN determines the host language
from the DB2I defaults panel.
For example, for library name LIBNAME(MEMBNAME), the name
becomes userid.libname.language(membname) For library name
LIBNAME, the name becomes userid.libname.language.
If this data set is password protected, you must supply the password in
the DATA SET PASSWORD field.
5 DATA SET PASSWORD
Is the password for the data set that is specified in the DATA SET
Chapter 3. Including DB2 queries in an application program 131
|
|
|
|
NAME field, if the data set is password protected. The password is not
displayed on your terminal, and it is not recognized if you issued it
from a previous session.
6 ACTION
Specifies what DCLGEN is to do with the output when it is sent to a
partitioned data set. (The option is ignored if the data set you specify
in the DATA SET NAME field is sequential.) You can specify one of the
following values:
ADD
Indicates that an old version of the output does not exist and
creates a new member with the specified data set name. ADD is the
default.
REPLACE
Replaces an old version, if it already exists. If the member does not
exist, this option creates a new member.
7 COLUMN LABEL
Specifies whether DCLGEN is to include labels that are declared on any
columns of the table or view as comments in the data declarations.
(The SQL LABEL statement creates column labels to use as
supplements to column names.) You can specify one of the following
values:
YES
Include column labels.
NO
Ignore column labels. NO is the default.
8 STRUCTURE NAME
Is the name of the generated data structure. The name can be up to 31
characters. If the name is not a DBCS string, and the first character is
not alphabetic, enclose the name in apostrophes. If you use special
characters, be careful to avoid name conflicts.
If you leave this field blank, DCLGEN generates a name that contains
the table or view name with a prefix of DCL. If the language is COBOL
or PL/I and the table or view name consists of a DBCS string, the
prefix consists of DBCS characters.
For C, lowercase characters that you enter in this field are not
converted to uppercase.
9 FIELD NAME PREFIX
Specifies a prefix that DCLGEN uses to form field names in the output.
For example, if you choose ABCDE, the field names generated are
ABCDE1, ABCDE2, and so on.
You can specify a field name prefix of up to 28 bytes that can include
special and double-byte characters. If you specify a single-byte or
mixed-string prefix and the first character is not alphabetic, enclose the
prefix in apostrophes. If you use special characters, be careful to avoid
name conflicts.
For COBOL and PL/I, if the name is a DBCS string, DCLGEN
generates DBCS equivalents of the suffix numbers.
For C, lowercase characters that you enter in this field do not converted
to uppercase.
132 Application Programming and SQL Guide
If you leave this field blank, the field names are the same as the
column names in the table or view.
10 DELIMIT DBCS
Specifies whether DCLGEN is to delimit DBCS table names and column
names in the table declaration. You can specify one of the following
values:
YES
Specifies that DCLGEN is to enclose the DBCS table and column
names with SQL delimiters.
NO
Specifies that DCLGEN is not to delimit the DBCS table and
column names.
11 COLUMN SUFFIX
Specifies whether DCLGEN is to form field names by attaching the
column name as a suffix to the value that you specify in FIELD NAME
PREFIX. You can specify one of the following values:
YES
Specifies that DCLGEN is to use the column name as a suffix. For
example, if you specify YES, the field name prefix is NEW, and the
column name is EMPNO, the field name is NEWEMPNO.
If you specify YES, you must also enter a value in FIELD NAME
PREFIX. If you do not enter a field name prefix, DCLGEN issues a
warning message and uses the column names as the field names.
NO
Specifies that DCLGEN is not to use the column name as a suffix.
The default is NO.
12 INDICATOR VARS
Specifies whether DCLGEN is to generate an array of indicator
variables for the host variable structure. You can specify one of the
following values:
YES
Specifies that DCLGEN is to generate an array of indicator
variables for the host variable structure.
If you specify YES, the array name is the table name with a prefix
of I (or DBCS letter <I> if the table name consists solely of
double-byte characters). The form of the data declaration depends
on the language, as shown in the following table. n is the number
of columns in the table.
Table 39. Declarations for indicator variable arrays from DCLGEN
Language Declaration form
C short int Itable-name[n];
COBOL 01 Itable-name PIC S9(4) USAGE COMP
OCCURS n TIMES.
PL/I DCL Itable-name(n) BIN FIXED(15);
For example, suppose that you define the following table:
CREATE TABLE HASNULLS (CHARCOL1 CHAR(1), CHARCOL2 CHAR(1));
Chapter 3. Including DB2 queries in an application program 133
If you request an array of indicator variables for a COBOL
program, DCLGEN might generate the following host variable
declaration:
01 DCLHASNULLS.
10 CHARCOL1 PIC X(1).
10 CHARCOL2 PIC X(1).
01 IHASNULLS PIC S9(4) USAGE COMP OCCURS 2 TIMES.
NO
Specifies that DCLGEN is not to generate an array of indicator
variables. The default is NO.
13 ADDITIONAL OPTIONS
Indicates whether to display the panel for additional DCLGEN options,
including the break point for statement tokens and whether to generate
DECLARE VARIABLE statements for FOR BIT DATA columns. You can
specify YES or NO. The default is YES.
If you specified YES in the ADDITIONAL OPTIONS field, the following
ADDITIONAL DCLGEN OPTIONS panel is displayed:
Otherwise, DCLGEN creates the declarations in the specified data set.
3. If the ADDITIONAL DCLGEN OPTIONS panel is displayed, fill in the
following fields on that panel:
1 RIGHT MARGIN
Specifies the break point for statement tokens that must be wrapped to
one or more subsequent records. You can specify column 72 or column
80.
The default is 72.
2 FOR BIT DATA
Specifies whether DCLGEN is to generate a DECLARE VARIABLE
statement for SQL variables for columns that are declared as FOR BIT
DATA. This statement is required in DB2 applications that meet all of
the following criteria:
v are written in COBOL
v have host variables for FOR BIT DATA columns
v are prepared with the SQLCCSID option of the DB2 coprocessor.
You can specify YES or NO. The default is NO.
If the table or view does not have FOR BIT DATA columns, DCLGEN
does not generate this statement.
DCLGEN creates the declarations in the specified data set.
Related reference
DSNEDP02 ADDITIONAL DCLGEN OPTIONS SSID: DSN
===>
Enter options as desired:
1 RIGHT MARGIN .... ===> 72 (Enter 72 or 80)
2 FOR BIT DATA .... ===> NO (Enter YES to declare SQL variables for
FOR BIT DATA columns)
PRESS: ENTER to process END to exit HELP for more information
Figure 7. ADDITIONAL DCLGEN OPTIONS panel
134 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LABEL (DB2 SQL Reference)
DB2I primary option menu on page 918
Data types that DCLGEN uses for variable declarations
DCLGEN produces declarations for tables and views and the corresponding host
variable structures for C, COBOL, and PL/I programs. DCLGEN derives the
variable names and data types for these declarations based on the source tables in
the database.
The following table lists the C, COBOL, and PL/I data types that DCLGEN uses
for variable declarations based on the corresponding SQL data types that are used
in the source tables. var represents a variable name that DCLGEN provides.
Table 40. Type declarations that DCLGEN generates
SQL data type
1
C COBOL PL/I
SMALLINT short int PIC S9(4) USAGE COMP BIN FIXED(15)
INTEGER long int PIC S9(9) USAGE COMP BIN FIXED(31)
DECIMAL(p,s) or
NUMERIC(p,s)
decimal(p,s)
2
PIC S9(p-s)V9(s) USAGE
COMP-3
DEC FIXED(p,s)
If p>15, the PL/I compiler
must support this precision,
or a warning is generated.
REAL or FLOAT(n) 1 <= n
<= 21
float USAGE COMP-1 BIN FLOAT(n)
DOUBLE PRECISION,
DOUBLE, or FLOAT(n)
double USAGE COMP-2 BIN FLOAT(n)
CHAR(1) char PIC X(1) CHAR(1)
CHAR(n) char var [n+1] PIC X(n) CHAR(n)
VARCHAR(n)
struct
{short int var_len;
char var_data[n];
} var;
10 var.
49 var_LEN PIC 9(4)
USAGE COMP.
49 var_TEXT PIC X(n).
CHAR(n) VAR
CLOB(n)
3
SQL TYPE IS CLOB_LOCATOR USAGE SQL TYPE IS
CLOB-LOCATOR
SQL TYPE IS CLOB_LOCATOR
GRAPHIC(1) sqldbchar PIC G(1) GRAPHIC(1)
GRAPHIC(n)
n > 1
sqldbchar var[n+1];
PIC G(n) USAGE
DISPLAY-1.
4
or
PIC N(n).
4
GRAPHIC(n)
VARGRAPHIC(n)
struct VARGRAPH
{short len;
sqldbchar data[n];
} var;
10 var.
49 var_LEN PIC 9(4)
USAGE COMP.
49 var_TEXT PIC G(n)
USAGE DISPLAY-1.
4
or
10 var.
49 var_LEN PIC 9(4)
USAGE COMP.
49 var_TEXT PIC N(n).
4
GRAPHIC(n) VAR
DBCLOB(n)
3
SQL TYPE IS
DBCLOB_LOCATOR
USAGE SQL TYPE IS
DBCLOB-LOCATOR
SQL TYPE IS
DBCLOB_LOCATOR
BINARY(n) SQL TYPE IS BINARY(n) USAGE SQL TYPE IS
BINARY(n)
SQL TYPE IS BINARY(n)
Chapter 3. Including DB2 queries in an application program 135
|||
|
|
Table 40. Type declarations that DCLGEN generates (continued)
SQL data type
1
C COBOL PL/I
VARBINARY(n) SQL TYPE IS VARBINARY(n) USAGE SQL TYPE IS
VARBINARY(n)
SQL TYPE IS VARBINARY(n)
BLOB(n)
3
SQL TYPE IS BLOB_LOCATOR USAGE SQL TYPE IS
BLOB-LOCATOR
SQL TYPE IS BLOB_LOCATOR
DATE char var[11]
5
PIC X(10)
5
CHAR(10)
5
TIME char var[9]
6
PIC X(8)
6
CHAR(8)
6
TIMESTAMP char var[27] PIC X(26) CHAR(26)
ROWID SQL TYPE IS ROWID USAGE SQL TYPE IS ROWID SQL TYPE IS ROWID
BIGINT long long int PIC S9(18) USAGE COMP FIXED BIN(63)
XML
7
SQL TYPE IS XML AS
CLOB(1M)
SQL TYPE IS XML AS
CLOB(1M)
SQL TYPE IS XML AS
CLOB(1M)
Notes:
1. For a distinct type, DCLGEN generates the host language equivalent of the source data type.
2. If your C compiler does not support the decimal data type, edit your DCLGEN output and replace the decimal
data declarations with declarations of type double.
3. For a BLOB, CLOB, or DBCLOB data type, DCLGEN generates a LOB locator.
4. DCLGEN chooses the format based on the character that you specify as the DBCS symbol on the COBOL Defaults
panel.
5. This declaration is used unless a date installation exit routine exists for formatting dates, in which case the length
is that specified for the LOCAL DATE LENGTH installation option.
6. This declaration is used unless a time installation exit routine exists for formatting times, in which case the length
is that specified for the LOCAL TIME LENGTH installation option.
7. The default setting for XML is 1M; however, you might need to adjust it.
Including declarations from DCLGEN in your program
After you use DCLGEN to produce table, view, and variable declarations for your
C, COBOL, or PL/I program, you should include these declarations in your
program.
Recommendation: To ensure that your program uses a current description of the
table, use DCLGEN to generate the tables declaration and store it as a member in
a library (usually a partitioned data set) just before you precompile the program.
To include declarations from DCLGEN in your program:
Code the following SQL INCLUDE statement in your program:
EXEC SQL
INCLUDE member-name
END-EXEC.
member-name is the name of the data set member where the DCLGEN output is
stored.
Example: Suppose that you used DCLGEN to generate a table declaration and
corresponding COBOL record description for the table DSN8910.EMP, and those
declarations were stored in the data set member DECEMP. (A COBOL record
description is a two-level host structure that corresponds to the columns of a
tables row. ) To include those declarations in your program, include the following
statement in your COBOL program:
136 Application Programming and SQL Guide
|||
|
|
||||
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
EXEC SQL
INCLUDE DECEMP
END-EXEC.
Related reference
INCLUDE (DB2 SQL Reference)
Example: Adding DCLGEN declarations to a library
You can use DCLGEN to generate table and variable declarations for C, COBOL,
and PL/I programs. If you store these declarations in a library, you can later pull
them into your program with a single SQL INCLUDE statement.
This example adds a table declaration and a corresponding host-variable structure
to a library. This example is based on the following scenario:
v The library name is prefix.TEMP.COBOL.
v The member is a new member named VPHONE.
v The table is a local table named DSN8910.VPHONE.
v The host-variable structure is for COBOL.
v The structure receives the default name DCLVPHONE.
Throughout this example, information that you must enter on each panel is in
bold-faced type.
In this scenario, to add a table declaration and a corresponding host variable
structure for DSN8910.VPHONE to the library prefix.TEMP.COBOL, complete the
following steps:
1. Specify COBOL as the host language by completing the following actions:
a. On the ISPF/PDF menu, select option D to display the DB2I DEFAULTS
PANEL l panel.
b. Specify IBMCOB as the application language, as shown in the following figure
and press Enter.
The DB2I DEFAULTS PANEL 2 panel for COBOL is then displayed.
c. Fill in the DB2I DEFAULTS PANEL 2 panel, shown in the following figure,
as needed and press Enter to save the new defaults, if any.
DSNEOP01 DB2I DEFAULTS PANEL 1
COMMAND ===>_
Change defaults as desired:
1 DB2 NAME ............. ===> DSN (Subsystem identifier)
2 DB2 CONNECTION RETRIES ===> 0 (How many retries for DB2 connection)
3 APPLICATION LANGUAGE ===> IBMCOB (ASM, C, CPP, IBMCOB, FORTRAN, PLI)
4 LINES/PAGE OF LISTING ===> 80 (A number from 5 to 999)
5 MESSAGE LEVEL ........ ===> I (Information, Warning, Error, Severe)
6 SQL STRING DELIMITER ===> DEFAULT (DEFAULT, ' or ")
7 DECIMAL POINT ........ ===> . (. or ,)
8 STOP IF RETURN CODE >= ===> 8 (Lowest terminating return code)
9 NUMBER OF ROWS ===> 20 (For ISPF Tables)
10 CHANGE HELP BOOK NAMES?===> NO (YES to change HELP data set names)
11 AS USER ===> (Userid to associate with the trusted
connection)
PRESS: ENTER to process END to cancel HELP for more information
Figure 8. DB2I defaults panelchanging the application language
Chapter 3. Including DB2 queries in an application program 137
The DB2I Primary Option menu is displayed.
2. Generate the table and host structure declarations by completing the following
actions:
a. On the DB2I Primary Option menu, select the DCLGEN option and press
Enter to display the DCLGEN panel.
b. Fill in the fields as shown in the following figure and press Enter.
A successful completion message, such as the one in the following figure, is
displayed at the top of your screen.
DB2 again displays the DCLGEN screen, as shown in the following figure.
DSNEOP02 DB2I DEFAULTS PANEL 2
COMMAND ===>_
Change defaults as desired:
1 DB2I JOB STATEMENT: (Optional if your site has a SUBMIT exit)
===> //ADMF001A JOB (ACCOUNT),'NAME'
===> //*
===> //*
===> //*
COBOL DEFAULTS: (For IBMCOB)
2 COBOL STRING DELIMITER ===> DEFAULT (DEFAULT, ' or ")
3 DBCS SYMBOL FOR DCLGEN ===> G (G/N - Character in PIC clause)
Figure 9. The COBOL defaults panel. Shown only if the field APPLICATION LANGUAGE on the DB2I DEFAULTS
PANEL l panel is IBMCOB.
DSNEDP01 DCLGEN SSID: DSN
===>
Enter table name for which declarations are required:
1 SOURCE TABLE NAME ===> DSN8910.VPHONE
2 TABLE OWNER ..... ===>
3 AT LOCATION ..... ===> (Optional)
Enter destination data set: (Can be sequential or partitioned)
4 DATA SET NAME ... ===> TEMP(VPHONEC)
5 DATA SET PASSWORD ===> (If password protected)
Enter options as desired:
6 ACTION .......... ===> ADD (ADD new or REPLACE old declaration)
7 COLUMN LABEL .... ===> NO (Enter YES for column label)
8 STRUCTURE NAME .. ===> (Optional)
9 FIELD NAME PREFIX ===> (Optional)
10 DELIMIT DBCS .... ===> YES (Enter YES to delimit DBCS identifiers)
11 COLUMN SUFFIX ... ===> NO (Enter YES to append column name)
12 INDICATOR VARS .. ===> NO (Enter YES for indicator variables)
13 ADDITIONAL OPTIONS===> NO (Enter YES to change additional options)
PRESS: ENTER to process END to exit HELP for more information
Figure 10. DCLGEN panelselecting source table and destination data set
DSNE905I EXECUTION COMPLETE, MEMBER VPHONEC ADDED
***
Figure 11. Successful completion message
138 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
c. Press Enter to return to the DB2I Primary Option menu.
3. Exit from DB2I.
4. Examine the DCLGEN output by selecting either the browse or the edit option
from the ISPF/PDF menu to view the results in the specified data set member.
For this example, the data set to edit is prefix.TEMP.COBOL(VPHONEC). This
data set member contains the following information.
***** DCLGEN TABLE(DSN8910.VPHONE) ***
***** LIBRARY(SYSADM.TEMP.COBOL(VPHONEC)) ***
***** QUOTE ***
***** ... IS THE DCLGEN COMMAND THAT MADE THE FOLLOWING STATEMENTS ***
EXEC SQL DECLARE DSN8910.VPHONE TABLE
( LASTNAME VARCHAR(15) NOT NULL,
FIRSTNAME VARCHAR(12) NOT NULL,
MIDDLEINITIAL CHAR(1) NOT NULL,
PHONENUMBER VARCHAR(4) NOT NULL,
EMPLOYEENUMBER CHAR(6) NOT NULL,
DEPTNUMBER CHAR(3) NOT NULL,
DEPTNAME VARCHAR(36) NOT NULL
) END-EXEC.
***** COBOL DECLARATION FOR TABLE DSN8910.VPHONE ******
01 DCLVPHONE.
10 LASTNAME.
49 LASTNAME-LEN PIC S9(4) USAGE COMP.
49 LASTNAME-TEXT PIC X(15).
10 FIRSTNAME.
49 FIRSTNAME-LEN PIC S9(4) USAGE COMP.
49 FIRSTNAME-TEXT PIC X(12).
10 MIDDLEINITIAL PIC X(1).
10 PHONENUMBER.
49 PHONENUMBER-LEN PIC S9(4) USAGE COMP.
49 PHONENUMBER-TEXT PIC X(4).
10 EMPLOYEENUMBER PIC X(6).
10 DEPTNUMBER PIC X(3).
10 DEPTNAME.
49 DEPTNAME-LEN PIC S9(4) USAGE COMP.
49 DEPTNAME-TEXT PIC X(36).
***** THE NUMBER OF COLUMNS DESCRIBED BY THIS DECLARATION IS 7 ******
You can now pull these declarations into your program by using an SQL
INCLUDE statement.
DSNEDP01 DCLGEN SSID: DSN
===>
Enter table name for which declarations are required:
1 SOURCE TABLE NAME ===> DSN8910.VPHONE
2 TABLE OWNER ..... ===>
3 AT LOCATION ..... ===> (Optional)
Enter destination data set: (Can be sequential or partitioned)
4 DATA SET NAME ... ===> TEMP(VPHONEC)
5 DATA SET PASSWORD ===> (If password protected)
Enter options as desired:
6 ACTION .......... ===> ADD (ADD new or REPLACE old declaration)
7 COLUMN LABEL .... ===> NO (Enter YES for column label)
8 STRUCTURE NAME .. ===> (Optional)
9 FIELD NAME PREFIX ===> (Optional)
10 DELIMIT DBCS .... ===> YES (Enter YES to delimit DBCS identifiers)
11 COLUMN SUFFIX ... ===> NO (Enter YES to append column name)
12 INDICATOR VARS .. ===> NO (Enter YES for indicator variables)
13 ADDITIONAL OPTIONS===> NO (Enter YES to change additional options)
PRESS: ENTER to process END to exit HELP for more information
Figure 12. DCLGEN paneldisplaying system and user return codes
Chapter 3. Including DB2 queries in an application program 139
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Defining the items that your program can use to check whether an
SQL statement executed successfully
If your program contains SQL statements, the program should define some
infrastructure so that it can check whether the statements executed successfully.
You can either include an SQL communications area (SQLCA), which contains
SQLCODE and SQLSTATE variables, or declare individual SQLCODE and
SQLSTATE host variables.
For assembler, C, C++, COBOL, Fortran, or PL/I programs, you must explicitly
define the SQLCA or host variables. For REXX procedures that contain SQL
statements, DB2 automatically includes an SQLCA in the procedure when DB2
prepares it.
Whether you define the SQLCODE or SQLSTATE variables or an SQLCA in your
program depends on what you specify for the SQL processing option STDSQL. Use
the following guidelines to decide which items to define:
v If you specify the SQL processing option STDSQL(YES): Do not define an
SQLCA. If you do, DB2 ignores your SQLCA, and your SQLCA definition causes
compile-time errors.
For COBOL programs, when you specify STDSQL(YES), you must declare an
SQLCODE variable. DB2 declares an SQLCA area for you in the
WORKING-STORAGE SECTION. DB2 controls the structure and location of the
SQLCA.
v If you specify the SQL processing option STDSQL(NO): Include an SQLCA
explicitly.
Related reference
Descriptions of SQL processing options on page 868
Defining the SQL communications area
Assembler, C, C++, COBOL, Fortran, or PL/I programs that contain SQL
statements can include an SQL communications area (SQLCA) to check whether an
SQL statement executed successfully. Alternatively, these programs can declare
individual SQLCODE and SQLSTATE host variables.
REXX applications behave differently. When DB2 prepares a REXX procedure that
contains SQL statements, DB2 automatically includes an SQLCA in the procedure.
The REXX SQLCA differs from the SQLCA for other languages. The REXX SQLCA
consists of a set of separate variables, rather than a structure. If you use the
ADDRESS DSNREXX 'CONNECT' ssid syntax to connect to DB2, the SQLCA variables
are a set of simple variables. If you use the CALL SQLDBS 'ATTACH TO' syntax to
connect to DB2, the SQLCA variables are compound variables that begin with the
stem SQLCA.
Restriction: If you specify the SQL processing option STDSQL(YES), do not define
an SQLCA. If you do, DB2 ignores your SQLCA, and your SQLCA definition
causes compile-time errors.
To define the SQL communications area:
Code the SQLCA directly in the program or use the following SQL INCLUDE
statement to request a standard SQLCA declaration:
EXEC SQL INCLUDE SQLCA
140 Application Programming and SQL Guide
Assembler: If your program is reentrant, you must include the SQLCA within a
unique data area that is acquired for your task (a DSECT). For example, at the
beginning of your program, specify the following code:
PROGAREA DSECT
EXEC SQL INCLUDE SQLCA
As an alternative, you can create a separate storage area for the SQLCA and
provide addressability to that area.
C and C++: The standard declaration includes both a structure definition and a
static data area named sqlca.
COBOL: You can specify INCLUDE SQLCA or a declaration for SQLCODE
wherever you can specify a 77 level or a record description entry in the
WORKING-STORAGE SECTION.
Restriction: You cannot use the INCLUDE SQLCA statement to include an SQLCA
in a REXX program.
DB2 sets the SQLCODE and SQLSTATE values in the SQLCA after each SQL
statement executes. Your application should check these values to determine
whether the last SQL statement was successful.
Related tasks
Accessing the DB2 REXX language support application programming
interfaces on page 305
Declaring SQLCODE and SQLSTATE host variables
Related reference
INCLUDE (DB2 SQL Reference)
Description of SQLCA fields (DB2 SQL Reference)
The REXX SQLCA (DB2 SQL Reference)
Descriptions of SQL processing options on page 868
Declaring SQLCODE and SQLSTATE host variables
If your application contains SQL statements and does not include an SQL
communications area (SQLCA), you must declare individual SQLCODE and
SQLSTATE host variables. Your program can use these variables to check whether
an SQL statement executed successfully.
Restriction: This task does not apply to REXX applications. For REXX applications
that contain SQL statements, DB2 automatically includes an SQLCA in the
procedure when DB2 prepares it.
To declare SQLCODE and SQLSTATE host variables:
1. Declare the SQLCODE variable within a BEGIN DECLARE SECTION statement
and an END DECLARE SECTION statement in your program declarations as
shown in the following table.
Table 41. SQLCODE variable declarations
Language How the SQLCODE variable is declared
Assembler as a fullword integer
C as a long integer
Example:
long SQLCODE;
Chapter 3. Including DB2 queries in an application program 141
Table 41. SQLCODE variable declarations (continued)
Language How the SQLCODE variable is declared
COBOL
a
as PIC S9(9) BINARY, PIC S9(9) COMP-4,
PIC S9(9) COMP-5, or PICTURE S9(9) COMP
Fortran
b
as INTEGER*4
PL/I as BIN FIXED (31)
Note:
1. In COBOL, when you use the DB2 precompiler, you can declare a stand-alone SQLCODE
variable in either the WORKING-STORAGE SECTION or LINKAGE SECTION. When
you use the DB2 coprocessor, you can declare a stand-alone SQLCODE variable in the
WORKING-STORAGE SECTION, LINKAGE SECTION or LOCAL-STORAGE SECTION.
2. In Fortran, this variable can also be called SQLCOD.
2. Declare the SQLSTATE variable within a BEGIN DECLARE SECTION
statement and an END DECLARE SECTION statement in your program
declarations as shown in the following table.
Table 42. SQLSTATE variable declarations
Language How the SQLSTATE variable is declared
assembler as a character string of length 5 (CL5)
C as a character array of length 6
Example:
char SQLSTATE[6];
COBOL as PICTURE X(5)
Fortran
a
as CHARACTER*5
PL/I as CHARACTER(5)
Note:
1. In Fortran, this variable can also be called SQLSTA.
Restriction: Do not declare an SQLSTATE variable as an element of a structure.
Requirement: After you declare the SQLCODE and SQLSTATE variables, ensure
that all SQL statements in the program are within the scope of the declaration of
these variables.
Related tasks
Defining the SQL communications area on page 140
Defining SQL descriptor areas
If your program includes certain SQL statements, you must define at least one SQL
descriptor area (SQLDA). Depending on the context in which it is used, the
SQLDA stores information about prepared SQL statements or host variables. This
information can then be read by either the application program or DB2.
If your program includes any of the following statements, you must include an
SQLDA in your program:
v CALL ... USING DESCRIPTOR descriptor-name
v DESCRIBE statement-name INTO descriptor-name
v DESCRIBE CURSOR host-variable INTO descriptor-name
v DESCRIBE INPUT statement-name INTO descriptor-name
142 Application Programming and SQL Guide
|
|
|
|
v DESCRIBE PROCEDURE host-variable INTO descriptor-name
v DESCRIBE TABLE host-variable INTO descriptor-name
v EXECUTE ... USING DESCRIPTOR descriptor-name
v FETCH ... INTO DESCRIPTOR descriptor-name
v OPEN ... USING DESCRIPTOR descriptor-name
v PREPARE ... INTO descriptor-name
Unlike the SQLCA, a program can have more than one SQLDA, and an SQLDA
can have any valid name.
To define SQL descriptor areas:
Perform one of the following actions depending on the programming language:
Table 43. Declaring the SQLDA
Language How to declare the SQLDA
Assembler, C, C++, PL/I Code the SQLDA directly in the program or use the following
SQL INCLUDE statement to request a standard SQLDA
declaration:
EXEC SQL INCLUDE SQLDA
For C and C++ programs, you can place an SQLDA declaration
wherever C allows a structure definition. Normal C scoping rules
apply. The standard declaration includes only a structure
definition with the name sqlda.
COBOL Perform one of the following actions:
v Code the SQLDA declarations directly in your program. When
you use the DB2 precompiler, you must place SQLDA
declarations in the WORKING-STORAGE SECTION or
LINKAGE SECTION of your program, wherever you can
specify a record description entry in that section. When you
use the DB2 coprocessor, you must place SQLDA declarations
in the WORKING-STORAGE SECTION, LINKAGE SECTION
or LOCAL-STORAGE SECTION of your program, wherever
you can specify a record description entry in that section.
v Call a subroutine that is written in C, PL/I, or assembler
language and that uses the INCLUDE SQLDA statement to
define the SQLDA. The subroutine can also include SQL
statements for any dynamic SQL functions that you need.
Fortran Call a subroutine that is written in C, PL/I, or assembler
language and that uses the INCLUDE SQLDA statement to define
the SQLDA. The subroutine can also include SQL statements for
any dynamic SQL functions that you need.
REXX Code the SQLDA declarations directly in your program.
Each SQLDA consists of a set of REXX variables with a common
stem. The stem must be a REXX variable name that contains no
periods and is the same as the value of descriptor-name that you
specify when you use the SQLDA in an SQL statement.
Restrictions:
1. You must place SQLDA declarations before the first SQL statement that references the
data descriptor, unless you use the TWOPASS SQL processing option.
2. For COBOL, Fortran, and REXX applications, you cannot use the SQL INCLUDE
statement for the SQLDA, because DB2 does not support this statement for those
languages.
Chapter 3. Including DB2 queries in an application program 143
|
|
|
|
|
|
|
|
|
|
Related reference
INCLUDE (DB2 SQL Reference)
Description of SQLCA fields (DB2 SQL Reference)
The REXX SQLCA (DB2 SQL Reference)
SQL descriptor area (SQLDA) (DB2 SQL Reference)
Descriptions of SQL processing options on page 868
Declaring host variables, host variable arrays, and host structures
You can use host variables, host variable arrays, and host structures in SQL
statements in your program to pass data between DB2 and your application.
Restriction: Do not declare host variables in REXX.
To declare host variables, host variable arrays, and host structures:
1. Declare the variables according to the conventions for your particular
programming language and the following rules and guidelines:
Table 44. Rules and guidelines for declaring host variables, host variable arrays, and host
structures
Language Rules and guidelines
All except REXX
v If you specify the ONEPASS SQL
processing option, you must explicitly
declare each host variable and each host
variable array before using them in an
SQL statement. If you specify the
TWOPASS precompiler option, you must
declare each host variable before using it
in the DECLARE CURSOR statement.
Restriction: The DB2 coprocessor for
C/C++ supports only the ONEPASS
option.
v If you specify the STDSQL(YES) SQL
processing option, you must precede the
host language statements that define the
host variables and host variable arrays
with the BEGIN DECLARE SECTION
statement and follow the host language
statements with the END DECLARE
SECTION statement. Otherwise, these
statements are optional.
v Ensure that any SQL statement that uses a
host variable or host variable array is
within the scope of the statement that
declares that variable or array.
v If you are using the DB2 precompiler,
ensure that the names of host variables
and host variable arrays are unique within
the program, even if the variables and
variable arrays are in different blocks,
classes, procedures, functions, or
subroutines. You can qualify the names
with a structure name to make them
unique.
144 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
Table 44. Rules and guidelines for declaring host variables, host variable arrays, and host
structures (continued)
Language Rules and guidelines
Assembler You can declare host variables in normal
assembler style (DC or DS), depending on
the data type and the limitations on that data
type. You can specify a value on DC or DS
declarations (for example, DC H'5'). The DB2
precompiler examines only packed decimal
declarations.
C/C++
v You can have more than one host variable
declaration section in your program.
v When you code SQL statements in a C++
program, you can use class members as
host variables. Class members that are
used as host variables are accessible to any
SQL statement within the class. However,
you cannot use class objects as host
variables.
COBOL
v You must explicitly declare all host
variables and host variable arrays that are
used in SQL statements in the
WORKING-STORAGE SECTION or
LINKAGE SECTION of your programs
DATA DIVISION.
v You must explicitly declare each host
variable and host variable array before
using them in an SQL statement.
v You can specify OCCURS when defining
an indicator structure, a host variable
array, or an indicator variable array. You
cannot specify OCCURS for any other type
of host variable.
v You cannot implicitly declare any host
variables through default typing or by
using the IMPLICIT statement.
Fortran
v When you declare a character host
variable, do not use an expression to
define the length of the character variable.
You can use a character host variable with
an undefined length (for example,
CHARACTER *(*)). The length of any such
variable is determined when the associated
SQL statement executes.
v Host variables must be scalar variables;
they cannot be elements of vectors or
arrays (subscripted variables).
v Be careful when calling subroutines that
might change the attributes of a host
variable. Such alteration can cause an error
while the program is running.
PL/I None other than the restrictions that are
listed for all languages.
Chapter 3. Including DB2 queries in an application program 145
Table 44. Rules and guidelines for declaring host variables, host variable arrays, and host
structures (continued)
Language Rules and guidelines
REXX
v You do not declare host variables in REXX.
When you need a new variable, you use it
in a REXX command. When you use a
REXX variable as a host variable in an
SQL statement, you must precede the
variable with a colon.
v A REXX host variable can be a simple or
compound variable. DB2 REXX Language
Support evaluates compound variables
before DB2 processes SQL statements that
contain the variables. In the following
example, the host variable that is passed to
DB2 is :x.1.2:
a=1
b=2
EXECSQL 'OPEN C1 USING :x.a.b'
2. Optional: Define any associated indicator variables, arrays, and structures.
Related reference
Assembler syntax for host variable declarations on page 147
C and C++ syntax for host variable declarations on page 151
COBOL syntax for host variable declarations on page 161
Fortran syntax for host variable declarations on page 170
PL/I syntax for host variable declarations on page 172
C and C++ syntax for host variable array declarations on page 177
COBOL syntax for host variable array declarations on page 183
PL/I syntax for host variable array declarations on page 190
C and C++ syntax for host structures on page 194
COBOL syntax for host structures on page 197
PL/I syntax for host structures on page 201
Descriptions of SQL processing options on page 868
Host variables
Use host variables to pass a single data item between DB2 and your application.
Ahost variable is a single data item that is declared in the host language to be used
within an SQL statement. You can use host variables to perform the following
actions:
v Retrieve data into the host variable for your application programs use
v Place data into the host variable to insert into a table or to change the contents
of a row
v Use the data in the host variable when evaluating a WHERE or HAVING clause
v Assign the value that is in the host variable to a special register, such as
CURRENT SQLID and CURRENT DEGREE
v Insert null values into columns by using a host indicator variable that contains a
negative value
146 Application Programming and SQL Guide
v Use the data in the host variable in statements that process dynamic SQL, such
as EXECUTE, PREPARE, and OPEN
Related concepts
Rules for host variables in an SQL statement on page 255
Assembler syntax for host variable declarations
In assembler programs, you can specify numeric, character, graphic, binary, LOB,
XML, and ROWID host variables. You can also specify result set, table, and LOB
locators and LOB and XML file reference variables.
Restrictions:
v Only some of the valid assembler declarations are valid host variable
declarations. If the declaration for a host variable is not valid, any SQL
statement that references the variable might result in the message
UNDECLARED HOST VARIABLE.
v The locator data types are assembler language data types and SQL data types.
You cannot use locators as column types.
Recommendations:
v Be careful of overflow. For example, suppose that you retrieve an INTEGER
column value into a DS H host variable, and the column value is larger than
32767. You get an overflow warning or an error, depending on whether you
provide an indicator variable.
v Be careful of truncation. For example, if you retrieve an 80-character CHAR
column value into a host variable that is declared as DS CL70, the rightmost ten
characters of the retrieved string are truncated. If you retrieve a floating-point or
decimal column value into a host variable declared as DS F, any fractional part
of the value is removed.
Numeric host variables
The following diagram shows the syntax for declaring numeric host variables.
Chapter 3. Including DB2 queries in an application program 147
variable-name DC
DS 1
H
L2
F
L4
FD
L8
(1)
P value
Ln
E
L4
EH
L4
EB
L4
ED
L4
D
L8
DH
L8
DB
L8
DD
L8
LD
L16

Notes:
1 value is a numeric value that specifies the scale of the packed decimal
variable. If value does not include a decimal point, the scale is 0.
For floating-point data types (E, EH, EB, D, DH, and DB), use the FLOAT SQL
processing option to specify whether the host variable is in IEEE binary
floating-point or z/Architecture

hexadecimal floating-point format. If you specify


FLOAT(S390), you need to define your floating-point host variables as E, EH, D, or
DH. If you specify FLOAT(IEEE), you need to define your floating-point host
variables as EB or DB. DB2 does not check if the host variable declarations or
format of the host variable contents match the format that you specified with the
FLOAT SQL processing option. Therefore, you need to ensure that your
floating-point host variable types and contents match the format that you specified
with the FLOAT SQL processing option. DB2 converts all floating-point input data
to z/Architecture hexadecimal floating-point format before storing it.
Restriction: The FLOAT SQL processing options do not apply to the decimal
floating-point host variable types ED, DD, or LD.
For the decimal floating-point host variable types ED, DD, and LD, you can specify
the following special values: MIN, MAX, NAN, SNAN, and INFINITY.
Character host variables
You can specify the following forms of character host variables:
v Fixed-length strings
v Varying-length strings
v CLOBs
148 Application Programming and SQL Guide
||||||||
|
|
The following diagrams show the syntax for forms other than CLOBs.
The following diagram shows the syntax for declaring fixed-length character
strings.
variable-name DC C
DS 1 (1)
Ln

Notes:
1 If you declare a character string host variable without a length (for example,
DC C 'ABCD') DB2 interprets the length as 1. To get the correct length, specify
a length attribute (for example, DC CL 4 'ABCD').
The following diagram shows the syntax for declaring varying-length character
strings.
variable-name DC H ,
DS 1 L2 1
CLn
Graphic host variables
You can specify the following forms of graphic host variables:
v Fixed-length strings
v Varying-length strings
v DBCLOBs
The following diagrams show the syntax for forms other than DBCLOBs. In the
syntax diagrams, value denotes one or more DBCS characters, and the symbols <
and > represent the shift-out and shift-in characters.
The following diagram shows the syntax for declaring fixed-length graphic strings.
variable-name DC G
DS Ln
<value>
Ln<value>

The following diagram shows the syntax for declaring varying-length graphic
strings.
variable-name DS H , GLn
DC L2 m <value>

Binary host variables


The following diagram shows the syntax for declaring binary host variables.

(1)
variable-name DS X Ln
Chapter 3. Including DB2 queries in an application program 149
Notes:
1 1 n 255
Varbinary host variables
The following diagram shows the syntax for declaring varbinary host variables.

(1)
variable-name DS H L2 , X Ln
Notes:
1 1 n 32704
Result set locators
The following diagram shows the syntax for declaring result set locators.
variable-name DC F
DS 1 L4

Table Locators
The following diagram shows the syntax for declaring of table locators.
variable-name SQL TYPE IS TABLE LIKE table-name AS LOCATOR
LOB variables, locators, and file reference variables
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variables, locators, and file reference variables.
variable-name SQL TYPE IS BINARY LARGE OBJECT length
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_LOCATOR
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

XML data host and file reference variables


The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variables and file reference variables for XML data types.
150 Application Programming and SQL Guide
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
|

(1)
variable-name SQL TYPE IS XML AS BINARY LARGE OBJECT length
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

Notes:
1 If you specify the length of the LOB in terms of KB, MB, or GB, do not leave
spaces between the length and K, M, or G.
ROWIDs
The following diagram shows the syntax for declaring ROWID host variables.
variable-name SQL TYPE IS ROWID
Related concepts
Large objects (LOBs) on page 400
Related reference
Descriptions of SQL processing options on page 868
Related information
z/OS Internet Library
High Level Assembler (HLASM) and Toolkit Feature library
C and C++ syntax for host variable declarations
In C and C++ programs, you can specify numeric, character, graphic, binary, LOB,
XML, and ROWID host variables. You can also specify result set, table, and LOB
locators and LOB and XML file reference variables.
Restrictions:
v Only some of the valid C declarations are valid host variable declarations. If the
declaration for a variable is not valid, any SQL statement that references the
variable might result in the message UNDECLARED HOST VARIABLE.
v C supports some data types and storage classes with no SQL equivalents, such
as register storage class, typedef, and long long.
v The following locator data types are special SQL data types that do not have C
equivalents:
Result set locator
Table locator
LOB locators
You cannot use them to define column types.
v Although DB2 allows you to use properly formed L-literals in C application
programs, DB2 does not check for all the restrictions that the C compiler
imposes on the L-literal. \
v Do not use L-literals in SQL statements. Use DB2 graphic string constants in
SQL statements to work with the L-literal.
Recommendations:
Chapter 3. Including DB2 queries in an application program 151
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
|
|
|
|
v Be careful of overflow. For example, suppose that you retrieve an INTEGER
column value into a short integer host variable, and the column value is larger
than 32767. You get an overflow warning or an error, depending on whether you
provide an indicator variable.
v Be careful of truncation. Ensure that the host variable that you declare can
contain the data and a NUL terminator, if needed. Retrieving a floating-point or
decimal column value into a long integer host variable removes any fractional
part of the value.
Numeric host variables
The following diagram shows the syntax for declaring numeric host variables.

auto
extern
static
const
volatile
float
double
int
short
sqlint32
int
long
int
long long
decimal ( precision )
, scale


,
variable-name
(1) =expression
*pointer-name
;
Notes:
1 If you use the pointer notation of the host variable, you must use the DB2
coprocessor.
Restrictions:
v The SQL data type DECFLOAT has no equivalent in C.
v If your C compiler does not have a decimal data type, no exact equivalent exists
for the SQL data type DECIMAL. In this case, you can use one of the following
variables or techniques to handle decimal values:
An integer or floating-point variable, which converts the value. If you use an
integer variable, you lose the fractional part of the number. If the decimal
number can exceed the maximum value for an integer or if you want to
preserve a fractional value, use floating-point variables. Floating-point
numbers are approximations of real numbers. Therefore, when you assign a
decimal number to a floating-point variable, the result might be different from
the original number.
A character-string host variable. Use the CHAR function to get a string
representation of a decimal number.
The DECIMAL function to explicitly convert a value to a decimal data type,
as shown in the following example:
152 Application Programming and SQL Guide
||
|
long duration=10100; /* 1 year and 1 month */
char result_dt[11];
EXEC SQL SELECT START_DATE + DECIMAL(:duration,8,0)
INTO :result_dt FROM TABLE1;
For floating-point data types, use the FLOAT SQL processing option to specify
whether the host variable is in IEEE binary floating-point or z/Architecture
hexadecimal floating-point format. DB2 does not check if the format of the host
variable contents match the format that you specified with the FLOAT SQL
processing option. Therefore, you need to ensure that your floating-point host
variable contents match the format that you specified with the FLOAT SQL
processing option. DB2 converts all floating-point input data to z/Architecture
hexadecimal floating-point format before storing it.
Character host variables
You can specify the following forms of character host variables:
v Single-character form
v NUL-terminated character form
v VARCHAR structured form
v CLOBs
The following diagrams show the syntax for forms other than CLOBs.
The following diagram shows the syntax for declaring single-character host
variables.


,
char variable-name ;
auto const unsigned (1) =expression
extern volatile *pointer-name
static

Notes:
1 If you use the pointer notation of the host variable, you must use the DB2
coprocessor.
The following diagram shows the syntax for declaring NUL-terminated character
host variables.

auto
extern
static
const
volatile
char
unsigned


,
variable-name [ length ]
(1) =expression
*pointer-name
(2) (3)
;
Notes:
1 If you use the pointer notation of the host variable, you must use the DB2
coprocessor.
Chapter 3. Including DB2 queries in an application program 153
2 Any string that is assigned to this variable must be NUL-terminated. Any
string that is retrieved from this variable is NUL-terminated.
3 A NUL-terminated character host variable maps to a varying-length character
string (except for the NUL).
The following diagram shows the syntax for declaring varying-length character
host variables that use the VARCHAR structured form.

auto
extern
static
const
volatile

(1) int (2)


struct { short var-1 ;
tag

(2)
char var-2 [ length ] ; }
unsigned


,
variable-name ;
(3) ={expression, expression}
*pointer-name

Notes:
1 You can use the struct tag to define other variables, but you cannot use them
as host variables in SQL.
2 You cannot use var-1 and var-2 as host variables in an SQL statement.
3 If you use the pointer notation of the host variable, you must use the DB2
coprocessor.
Example: The following example code shows valid and invalid declarations of the
VARCHAR structured form:
EXEC SQL BEGIN DECLARE SECTION;
/* valid declaration of host variable VARCHAR vstring */
struct VARCHAR {
short len;
char s[10];
} vstring;
/* invalid declaration of host variable VARCHAR wstring */
struct VARCHAR wstring;
For NUL-terminated string host variables, use the SQL processing options
PADNTSTR and NOPADNTSTR to specify whether the variable should be padded
with blanks. The option that you specify determines where the NUL-terminator is
placed.
154 Application Programming and SQL Guide
If you assign a string of length n to a NUL-terminated string host variable, the
variable has one of the values that is shown in the following table.
Table 45. Value of a NUL-terminated string host variable that is assigned a string of length n
Length of the NUL-terminated string host
variable Value of the variable
Less than or equal to n The source string up to a length of n-1 and a
NUL at the end of the string.
1
DB2 sets SQLWARN[1] to W and any
indicator variable that you provide to the
original length of the source string.
Equal to n+1 The source string and a NUL at the end of
the string.
1
Greater than n+1 and the source is a
fixed-length string
If PADNTSTR is in effect
The source string, blanks to pad the
value, and a NUL at the end of the
string.
If NOPADNTSTR is in effect
The source string and a NUL at the end
of the string.
Greater than n+1 and the source is a
varying-length string
The source string and a NUL at the end of
the string.
1
Note:
1. In these cases, whether NOPADNTSTR or PADNTSTR is in effect is irrelevant.
Restriction: If you use the DB2 precompiler, you cannot use a host variable that is
of the NUL-terminated form in either a PREPARE or DESCRIBE statement.
However, if you use the DB2 coprocessor, you can use host variables of the
NUL-terminated form in PREPARE, DESCRIBE, and EXECUTE IMMEDIATE
statements.
Graphic host variables
You can specify the following forms of graphic host variables:
v Single-graphic form
v NUL-terminated graphic form
v VARGRAPHIC structured form.
v DBCLOBs
Recommendation: Instead of using the C data type wchar_t to define graphic and
vargraphic host variables, use one of the following techniques:
v Define the sqldbchar data type by using the following typedef statement:
typedef unsigned short sqldbchar;
v Use the sqldbchar data type that is defined in the typedef statement in one of
the following files or libraries:
SQL library, sql.h
DB2 CLI library, sqlcli.h
SQLUDF file in data set DSN910.SDSNC.H
v Use the C data type unsigned short.
Chapter 3. Including DB2 queries in an application program 155
|
|
|
|
|
|
|
|
|
|
Using sqldbchar or unsigned short enables you to manipulate DBCS and Unicode
UTF-16 data in the same format in which it is stored in DB2. Using sqldbchar also
makes applications easier to port to other platforms.
The following diagrams show the syntax for forms other than DBCLOBs.
The following diagram shows the syntax for declaring single-graphic host
variables.


,
(1) (2)
sqldbchar variable-name ;
auto const *pointer-name =expression
extern volatile
static

Notes:
1 You cannot use array notation in variable-name.
2 The single-graphic form declares a fixed-length graphic string of length 1.
The following diagram shows the syntax for declaring NUL-terminated graphic
host variables.


,
(2) (3) (4)
sqldbchar variable-name [ length ] ;
auto const (1) =expression
extern volatile *pointer-name
static

Notes:
1 If you use the pointer notation of the host variable, you must use the DB2
coprocessor.
2 length must be a decimal integer constant greater than 1 and not greater than
16352.
3 Any string that is assigned to this variable must be NUL-terminated. Any
string that is retrieved from this variable is NUL-terminated.
4 The NUL-terminated graphic form does not accept single-byte characters for
the variable.
The following diagram shows the syntax for declaring graphic host variables that
use the VARGRAPHIC structured form.

auto
extern
static
const
volatile

(1) int (2) (3)


struct { short var-1 ;
tag

156 Application Programming and SQL Guide


|
|
|

(3) (4)
sqldbchar var-2 [ length ] ; }


,
variable-name
(5) ={ expression, expression}
*pointer-name
;
Notes:
1 You can use the struct tag to define other variables, but you cannot use them
as host variables in SQL.
2 var-1 must be less than or equal to length.
3 You cannot use var-1 or var-2 as host variables in an SQL statement.
4 length must be a decimal integer constant greater than 1 and not greater than
16352.
5 If you use the pointer notation of the host variable, you must use the DB2
coprocessor.
Example: The following example shows valid and invalid declarations of graphic
host variables that use the VARGRAPHIC structured form:
EXEC SQL BEGIN DECLARE SECTION;
/* valid declaration of host variable structured vgraph */
struct VARGRAPH {
short len;
sqldbchar d[10];
} vgraph;
/* invalid declaration of host variable structured wgraph */
struct VARGRAPH wgraph;
Binary host variables
You can specify the following forms of binary host variables:
v Fixed-length strings
v Varying-length strings
v BLOBs
The following diagrams show the syntax for forms other than BLOBs.
The following diagram shows the syntax for declaring binary host variables.


,
(1)
SQL TYPE IS BINARY ( length ) variable-name ;
auto const
extern volatile
static

Notes:
1 The length must be a value from 1 to 255.
The following diagram shows the syntax for declaring VARBINARY host variables.
Chapter 3. Including DB2 queries in an application program 157
|
|
|
|
|
|
|
||||||||||||||||||||||||||||||||||||||||||||
|
|
||
|

auto
extern
static
const
volatile
SQL TYPE IS
(1)
VARBINARY
BINARY VARYING
( length )


,
variable-name
= { init-len , init-data }
;
Notes:
1 For VARBINARY host variables, the length must be in the range from 1 to
32 704.
The C language does not have variables that correspond to the SQL binary data
types BINARY and VARBINARY. To create host variables that can be used with
these data types, use the SQL TYPE IS clause. The SQL precompiler replaces this
declaration with the C language structure in the output source member.
When you reference a BINARY or VARBINARY host variable in an SQL statement,
you must use the variable that you specify in the SQL TYPE declaration. When
you reference the host variable in a host language statement, you must use the
variable that DB2 generates.
Examples of binary variable declarations: The following table shows examples of
variables that DB2 generates when you declare binary host variables.
Table 46. Examples of BINARY and VARBINARY variable declarations for C
Variable declaration that you include in
your C program
Corresponding variable that DB2 generates
in the output source member
SQL TYPE IS BINARY(10) bin_var; char bin_var[10]
SQL TYPE IS VARBINARY(10) vbin_var; struct {
short length;
char data[10];
} vbin_var;
Recommendation: Be careful when you use binary host variables with C and C++.
The SQL TYPE declaration for BINARY and VARBINARY does not account for the
NUL-terminator that C expects, because binary strings are not NUL-terminated
strings. Also, the binary host variable might contain zeroes at any point in the
string.
Result set locators
The following diagram shows the syntax for declaring result set locators.

auto
extern
static
register
const
volatile
SQL TYPE IS RESULT_SET_LOCATOR VARYING
158 Application Programming and SQL Guide
||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
||
||
|
|
|
|
|
|
|
|
|


,
variable-name
*pointer-name = init-value
;
Table locators
The following diagram shows the syntax for declaring table locators.

auto
extern
static
register
const
volatile

SQL TYPE IS TABLE LIKE table-name AS LOCATOR


,
variable-name
*pointer-name =init-value
;
LOB variables, locators, and file reference variables
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variables, locators, and file reference variables.

auto
extern
static
register
const
volatile
SQL TYPE IS
BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_LOCATOR
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

Chapter 3. Including DB2 queries in an application program 159


|||


,
variable-name
*pointer-name (1)
=init-value
;
Notes:
1 Specify the initial value as a series of expressions. For example, specify
={expression, expression}. For BLOB_FILE, CLOB_FILE, and
DBCLOB_FILE, specify ={name_length, data_length, file_option_map,
file_name}.
XML data host and file reference variables
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variables and file reference variables for XML data types.

auto
extern
static
register
const
volatile
SQL TYPE IS XML AS BLOB
XML AS CLOB
XML AS DBCLOB
XML AS BLOB_FILE
XML AS CLOB_FILE
XML AS DBCLOB_FILE


,
variable-name
*pointer-name =init-value
(1)
;
Notes:
1 Specify the initial value as a series of expressions. For example, specify
={expression, expression}. For BLOB_FILE, CLOB_FILE, and
DBCLOB_FILE, specify ={name_length, data_length, file_option_map,
file_name}.
ROWID host variables
The following diagram shows the syntax for declaring ROWID host variables.
variable-name SQL TYPE IS ROWID ;
auto const *pointer-name
extern volatile
static
register

Constants
The syntax for constants in C and C++ programs differs from the syntax for
constants in SQL statements in the following ways:
160 Application Programming and SQL Guide
|
|
|
|
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||
|
|
||
|
|
|
|
v In C, a string of digits with a decimal point is interpreted as a real constant. In
an SQL statement, such a string is interpreted as a decimal constant. You must
use exponential notation when specifying a real (that is, floating-point) constant
in an SQL statement.
v In C, a real (floating-point) constant can have a suffix of f or F to show a data
type of float or a suffix of l or L to show a type of long double. A floating-point
constant in an SQL statement must not use these suffixes.
v In C, you can provide integer constants in hexadecimal form if the first two
characters are 0x or 0X. You cannot use this form in an SQL statement.
v In C, an integer constant can have a suffix of u or U to show that it is an
unsigned integer. An integer constant can have a suffix of l or L to show a long
integer. You cannot use these suffixes in SQL statements.
v In C, character constants and string constants can use escape sequences. You
cannot use the escape sequences in SQL statements.
v Apostrophes and quotation marks have different meanings in C and SQL. In C,
you can use double quotation marks to delimit string constants, and apostrophes
to delimit character constants.
Example of the use of quotation marks in C:
printf( "%d lines read. \n", num_lines);
Example of the use of apostrophes in C:
#define NUL '\0'
In SQL, you can use double quotation marks to delimit identifiers and
apostrophes to delimit string constants.
Example of the use of quotation marks in SQL:
SELECT "COL#1" FROM TBL1;
Example of the use of apostrophes in SQL:
SELECT COL1 FROM TBL1 WHERE COL2 = 'BELL';
v Character data in SQL is distinct from integer data. Character data in C is a
subtype of integer data.
Related concepts
Large objects (LOBs) on page 400
Related reference
Descriptions of SQL processing options on page 868
COBOL syntax for host variable declarations
In COBOL programs, you can specify numeric, character, graphic, binary, LOB,
XML, and ROWID host variables. You can also specify result set and table locators
and LOB and XML file reference variables.
Restrictions:
v Only some of the valid COBOL declarations are valid host variable declarations.
If the declaration for a variable is not valid, any SQL statement that references
the variable might result in the message UNDECLARED HOST VARIABLE.
v You can not use locators as column types.
The following locator data types are COBOL data types and SQL data types:
Result set locator
Table locator
Chapter 3. Including DB2 queries in an application program 161
LOB locators
LOB file reference variables
v One or more REDEFINES entries can follow any level 77 data description entry.
However, you cannot use the names in these entries in SQL statements. Entries
with the name FILLER are ignored.
Recommendations:
v Be careful of overflow. For example, suppose that you retrieve an INTEGER
column value into a PICTURE S9(4) host variable and the column value is larger
than 32767 or smaller than -32768. You get an overflow warning or an error,
depending on whether you specify an indicator variable.
v Be careful of truncation. For example, if you retrieve an 80-character CHAR
column value into a PICTURE X(70) host variable, the rightmost 10 characters of
the retrieved string are truncated. Retrieving a double precision floating-point or
decimal column value into a PIC S9(8) COMP host variable removes any
fractional part of the value. Similarly, retrieving a column value with DECIMAL
data type into a COBOL decimal variable with a lower precision might truncate
the value.
v If your varying-length string host variables receive values whose length is
greater than 9999 bytes, compile the applications in which you use those host
variables with the option TRUNC(BIN). TRUNC(BIN) lets the length field for the
string receive a value of up to 32767 bytes.
Numeric host variables
You can specify the following forms of numeric host variables:
v Floating-point numbers
v Integers and small integers
v Decimal numbers
The following diagram shows the syntax for declaring floating-point or real host
variables.
01
77
(1)
level-1
variable-name
IS
USAGE

(2)
COMPUTATIONAL-1
COMP-1
(3)
COMPUTATIONAL-2
COMP-2
IS
VALUE numeric-constant
.
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 COMPUTATIONAL-1 and COMP-1 are equivalent.
3 COMPUTATIONAL-2 and COMP-2 are equivalent.
The following diagram shows the syntax for declaring integer and small integer
host variables.
162 Application Programming and SQL Guide
01
77
(1)
level-1
variable-name PICTURE
PIC
IS
S9(4)
S9999
S9(9)
S999999999
S9(18)

IS
USAGE
(2)
BINARY
COMPUTATIONAL-4
COMP-4
(3)
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP

IS
VALUE numeric-constant
(4)
.
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 The COBOL binary integer data types BINARY, COMPUTATIONAL, COMP,
COMPUTATIONAL-4, and COMP-4 are equivalent.
3 COMPUTATIONAL-5 (and COMP-5) are equivalent to the other COBOL
binary integer data types if you compile the other data types with
TRUNC(BIN).
4 Any specification for scale is ignored.
The following diagram shows the syntax for declaring decimal host variables.
01
77
(1)
level-1
variable-name PICTURE
PIC
IS (2)
picture-string

IS
USAGE

(3)
PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
IS CHARACTER
DISPLAY SIGN LEADING SEPARATE
NATIONAL

Chapter 3. Including DB2 queries in an application program 163


|

IS
VALUE numeric-constant
.
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 The picture-string that is associated with SIGN LEADING SEPARATE must
have the form S9(i)V9(d) (or S9...9V9...9, with i and d instances of 9 or S9...9V
with i instances of 9).
3 PACKED-DECIMAL, COMPUTATIONAL-3, and COMP-3 are equivalent. The
picture-string that is that is associated with these types must have the form
S9(i)V9(d) (or S9...9V9...9, with i and d instances of 9) or S9(i)V.
In COBOL, you declare the SMALLINT and INTEGER data types as a number of
decimal digits. DB2 uses the full size of the integers (in a way that is similar to
processing with the TRUNC(BIN) compiler option) and can place larger values in
the host variable than would be allowed in the specified number of digits in the
COBOL declaration. If you compile with TRUNC(OPT) or TRUNC(STD), ensure
that the size of numbers in your application is within the declared number of
digits.
For small integers that can exceed 9999, use S9(4) COMP-5 or compile with
TRUNC(BIN). For large integers that can exceed 999 999 999, use S9(10) COMP-3
to obtain the decimal data type. If you use COBOL for integers that exceed the
COBOL PICTURE, specify the column as decimal to ensure that the data types
match and perform well.
If you are using a COBOL compiler that does not support decimal numbers of
more than 18 digits, use one of the following data types to hold values of greater
than 18 digits:
v A decimal variable with a precision less than or equal to 18, if the actual data
values fit. If you retrieve a decimal value into a decimal variable with a scale
that is less than the source column in the database, the fractional part of the
value might be truncated.
v An integer or a floating-point variable, which converts the value. If you use an
integer variable, you lose the fractional part of the number. If the decimal
number might exceed the maximum value for an integer or if you want to
preserve a fractional value, use a floating-point variable. Floating-point numbers
are approximations of real numbers. Therefore, when you assign a decimal
number to a floating-point variable, the result might be different from the
original number.
v A character-string host variable. Use the CHAR function to retrieve a decimal
value into it.
Restriction: The SQL data type DECFLOAT has no equivalent in COBOL.
Character host variables
You can specify the following forms of character host variables:
v Fixed-length strings
v Varying-length strings
v CLOBs
164 Application Programming and SQL Guide
The following diagrams show the syntax for forms other than CLOBs.
The following diagram shows the syntax for declaring fixed-length character host
variables.
01
77
(1)
level-1
variable-name PICTURE
PIC
IS (2)
picture-string

DISPLAY
IS
USAGE
IS
VALUE character-constant
.
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 The picture-string that is associated with these forms must be X(m) (or XX...X,
with m instances of X), where 1 <= m <= 32767 for fixed-length strings.
However, the maximum length of the CHAR data type (fixed-length character
string) in DB2 is 255 bytes.
The following diagrams show the syntax for declaring varying-length character
host variables.
01 variable-name .
(1)
level-1

Notes:
1 level-1 indicates a COBOL level between 2 and 48.

(1) (2)
49 var-1 PICTURE
PIC
IS (3)
S9(4)
S9999 IS
USAGE

BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP
IS
VALUE numeric-constant
.
Notes:
1 You cannot use an intervening REDEFINE at level 49.
2 You cannot directly reference var-1 as a host variable.
3 DB2 uses the full length of the S9(4) BINARY variable even though COBOL
with TRUNC(STD) recognizes values up to only 9999. This behavior can
Chapter 3. Including DB2 queries in an application program 165
cause data truncation errors when COBOL statements execute and might
effectively limit the maximum length of variable-length character strings to
9999. Consider using the TRUNC(BIN) compiler option or USAGE COMP-5
to avoid data truncation.

(1) (2)
49 var-2 PICTURE
PIC
IS (3)
picture-string

DISPLAY
IS
USAGE
IS
VALUE character-constant
.
Notes:
1 You cannot use an intervening REDEFINE at level 49.
2 You cannot directly reference var-2 as a host variable.
3 For fixed-length strings, the picture-string must be X(m) (or XX...X, with m
instances of X), where 1 <= m <= 32767. For other strings, m cannot be greater
than the maximum size of a varying-length character string.
Graphic character host variables
You can specify the following forms of graphic host variables:
v Fixed-length strings
v Varying-length strings
v DBCLOBs
The following diagrams show the syntax for forms other than DBCLOBs.
The following diagram shows the syntax for declaring fixed-length graphic host
variables.
01
77
(1)
level-1
variable-name PICTURE
PIC
IS (2)
picture-string
DISPLAY-1
IS (3) IS
USAGE NATIONAL VALUE graphic-constant
.
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 For fixed-length strings, the picture-string is G(m) or N(m) (or, m instances of
GG...G or NN...N), where 1 <= m <= 127. For other strings, m cannot be
greater than the maximum size of a varying-length graphic string.
3 Use USAGE NATIONAL only for Unicode UTF-16 data. In the picture-string
for USAGE NATIONAL, you must use N in place of G. USAGE NATIONAL
is supported only by the DB2 coprocessor.
166 Application Programming and SQL Guide
The following diagrams show the syntax for declaring varying-length graphic host
variables.
01 variable-name .
(1)
level-1

Notes:
1 level-1 indicates a COBOL level between 2 and 48.

(1)
49 var-1 PICTURE
PIC
IS (2)
S9(4)
S9999 IS
USAGE

BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP
IS
VALUE numeric-constant
.
Notes:
1 You cannot directly reference var-1 as a host variable.
2 DB2 uses the full length of the S9(4) BINARY variable even though COBOL
with TRUNC(STD) recognizes values up to only 9999. This behavior can
cause data truncation errors when COBOL statements execute and might
effectively limit the maximum length of variable-length character strings to
9999. Consider using the TRUNC(BIN) compiler option or USAGE COMP-5
to avoid data truncation.

(1)
49 var-2 PICTURE
PIC
IS (2)
picture-string
IS
USAGE

DISPLAY-1
(3)
NATIONAL
IS
VALUE graphic-constant
.
Notes:
1 You cannot directly reference var-2 as a host variable.
2 For fixed-length strings, the picture-string is G(m) or N(m) (or, m instances of
GG...G or NN...N), where 1 <= m <= 127. For other strings, m cannot be
greater than the maximum size of a varying-length graphic string.
3 Use USAGE NATIONAL only for Unicode UTF-16 data. In the picture-string
for USAGE NATIONAL, you must use N in place of G. USAGE NATIONAL
is supported only by the DB2 coprocessor.
Chapter 3. Including DB2 queries in an application program 167
Binary host variables
You can specify the following forms of binary host variables:
v Fixed-length strings
v Varying-length strings
v BLOBs
The following diagram shows the syntax for declaring BINARY and VARBINARY
host variables.
01 variable-name
IS
USAGE
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING

(1)
( length ) .
Notes:
1 For BINARY host variables, the length must be in the range from 1 to 255.
For VARBINARY host variables, the length must be in the range from 1 to
32 704.
COBOL does not have variables that correspond to the SQL binary types BINARY
and VARBINARY. To create host variables that can be used with these data types,
use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a
COBOL language structure in the output source member.
When you reference a BINARY or VARBINARY host variable in an SQL statement,
you must use the variable that you specify in the SQL TYPE declaration. When
you reference the host variable in a host language statement, you must use the
variable that DB2 generates.
Examples of binary variable declarations: The following table shows examples of
variables that DB2 generates when you declare binary host variables.
Table 47. Examples of BINARY and VARBINARY variable declarations for COBOL
Variable declaration that you include in your COBOL
program
Corresponding variable that DB2 generates in the
output source member
01 BIN-VAR USAGE IS SQL TYPE IS BINARY(10). 01 BIN-VAR PIC X(10).
01 VBIN-VAR USAGE IS SQL TYPE IS VARBINARY(10). 01 VBIN-VAR.
49 VBIN-VAR-LEN PIC S9(4) USAGE BINARY.
49 VBIN-VAR-TEXT PIC X(10).
Result set locators
The following diagram shows the syntax for declaring result set locators.
01 variable-name SQL TYPE IS RESULT-SET-LOCATOR VARYING .
IS
USAGE

168 Application Programming and SQL Guide


|
|
|
|
|
|
|
||||||||||||||||||||||||||||||||
|
|
||||||||||||||
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
||
||
|
|
|
|
Table Locators
The following diagram shows the syntax for declaring table locators.
01 variable-name SQL TYPE IS TABLE LIKE table-name AS LOCATOR .
(1) IS
level-1 USAGE

Notes:
1 level-1 indicates a COBOL level between 2 and 48.
LOB variables and file reference variables
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
variables and file reference variables.
01 variable-name
level-1 IS
USAGE
SQL TYPE IS
BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB-LOCATOR
CLOB-LOCATOR
DBCLOB-LOCATOR
BLOB-FILE
CLOB-FILE
DBCLOB-FILE
.
XML data host and file reference variables
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variables and file reference variables for XML data types.
01 variable-name
(1)
level-1
IS
USAGE
SQL TYPE IS XML AS
BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB-FILE
CLOB-FILE
DBCLOB-FILE
.
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
Chapter 3. Including DB2 queries in an application program 169
|
|
|
|
ROWID host variables
The following diagram shows the syntax for declaring ROWID host variables.
01 variable-name SQL TYPE IS ROWID .
(1) IS
level-1 USAGE

Notes:
1 level-1 indicates a COBOL level between 2 and 48.
Related concepts
Large objects (LOBs) on page 400
Related tasks
Controlling the CCSID for COBOL host variables on page 213
Fortran syntax for host variable declarations
In Fortran programs, you can specify numeric, character, LOB, and ROWID host
variables. You can also specify result set and LOB locators.
Restrictions:
v Only some of the valid Fortran declarations are valid host variable declarations.
If the declaration for a variable is not valid, any SQL statement that references
the variable might result in the message UNDECLARED HOST VARIABLE.
v Fortran supports some data types with no SQL equivalent (for example,
REAL*16 and COMPLEX). In most cases, you can use Fortran statements to
convert between the unsupported data types and the data types that SQL allows.
v You can not use locators as column types.
The following locator data types are Fortran data types and SQL data types:
Result set locator
LOB locators
v Because Fortran does not support graphic data types, Fortran applications can
process only Unicode tables that use UTF-8 encoding.
Recommendations:
v Be careful of overflow. For example, if you retrieve an INTEGER column value
into a INTEGER*2 host variable and the column value is larger than 32767 or
-32768, you get an overflow warning or an error, depending on whether you
provided an indicator variable.
v Be careful of truncation. For example, if you retrieve an 80-character CHAR
column value into a CHARACTER*70 host variable, the rightmost ten characters
of the retrieved string are truncated. Retrieving a double-precision floating-point
or decimal column value into an INTEGER*4 host variable removes any
fractional value.
Numeric host variables
The following diagram shows the syntax for declaring numeric host variables.
170 Application Programming and SQL Guide
INTEGER*2
*4
INTEGER
*4
REAL
REAL*8
DOUBLE PRECISION

,
variable-name
/ numeric-constant /

Restrictions:
v Fortran does not provide an equivalent for the decimal data type. To hold a
decimal value, use one of the following variables:
An integer or floating-point variable, which converts the value. If you use an
integer variable, you lose the fractional part of the number. If the decimal
number can exceed the maximum value for an integer or you want to
preserve a fractional value, use a floating-point variable. Floating-point
numbers are approximations of real numbers. Therefore, when you assign a
decimal number to a floating-point variable, the result might be different from
the original number.
A character string host variable. Use the CHAR function to retrieve a decimal
value into it.
v The SQL data type DECFLOAT has no equivalent in Fortran.
Character host variables
The following diagram shows the syntax for declaring character host variables
other than CLOBs.


,
CHARACTER variable-name
*n *n / character-constant /

Result set locators


The following diagram shows the syntax for declaring result set locators.


,
SQL TYPE IS RESULT_SET_LOCATOR VARYING variable-name
LOB variables and locators
The following diagram shows the syntax for declaring BLOB and CLOB host
variables and locators.
SQL TYPE IS BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
BLOB_LOCATOR
CLOB_LOCATOR

Chapter 3. Including DB2 queries in an application program 171


|
variable-name
ROWID host variables
The following diagram shows the syntax for declarations of ROWID variables.
SQL TYPE IS ROWID variable-name
Constants
The syntax for constants in Fortran programs differs from the syntax for constants
in SQL statements in the following ways:
v Fortran interprets a string of digits with a decimal point to be a real constant.
An SQL statement interprets such a string to be a decimal constant. Therefore,
use exponent notation when specifying a real (that is, floating-point) constant in
an SQL statement.
v In Fortran, a real (floating-point) constant that has a length of 8 bytes uses a D
as the exponent indicator (for example, 3.14159D+04). An 8-byte floating-point
constant in an SQL statement must use an E (for example, 3.14159E+04).
Related concepts
Large objects (LOBs) on page 400
PL/I syntax for host variable declarations
In PL/I programs, you can specify numeric, character, graphic, binary, LOB, XML,
and ROWID host variables. You can also specify result set, table, and LOB locators
and LOB and XML file reference variables.
Restrictions:
v Only some of the valid PL/I declarations are valid host variable declarations.
The precompiler uses the data attribute defaults that are specified in the PL/I
DEFAULT statement. If the declaration for a host variable is not valid, any SQL
statement that references the variable might result in the message
UNDECLARED HOST VARIABLE.
v The alignment, scope, and storage attributes of host variables have the following
restrictions:
A declaration with the EXTERNAL scope attribute and the STATIC storage
attribute must also have the INITIAL storage attribute.
If you use the BASED storage attribute, you must follow it with a PL/I
element-locator-expression.
Host variables can be STATIC, CONTROLLED, BASED, or AUTOMATIC
storage class, or options. However, CICS requires that programs be reentrant.
Although the precompiler uses only the names and data attributes of variables
and ignores the alignment, scope, and storage attributes, you should not ignore
these restrictions. If you do ignore them, you might have problems compiling
the PL/I source code that the precompiler generates.
v PL/I supports some data types with no SQL equivalent (COMPLEX and BIT
variables, for example). In most cases, you can use PL/I statements to convert
between the unsupported PL/I data types and the data types that SQL supports.
v You can not use locators as column types.
The following locator data types are PL/I data types as well as SQL data types:
172 Application Programming and SQL Guide
Result set locator
Table locator
LOB locators
v The precompiler does not support PL/I scoping rules.
Recommendations:
v Be careful of overflow. For example, if you retrieve an INTEGER column value
into a BIN FIXED(15) host variable and the column value is larger than 32767 or
smaller than -32768, you get an overflow warning or an error, depending on
whether you provided an indicator variable.
v Be careful of truncation. For example, if you retrieve an 80-character CHAR
column value into a CHAR(70) host variable, the rightmost ten characters of the
retrieved string are truncated. Retrieving a double-precision floating-point or
decimal column value into a BIN FIXED(31) host variable removes any fractional
part of the value. Similarly, retrieving a column value with a DECIMAL data
type into a PL/I decimal variable with a lower precision might truncate the
value.
Numeric host variables
The following diagram shows the syntax for declaring numeric host variables.
DECLARE
DCL

variable-name
,
( variable-name )
BINARY
BIN
DECIMAL
DEC

(2)
FIXED
( precision )
(1)
,scale
FLOAT ( precision )

Alignment and/or Scope and/or Storage

Notes:
1 You can specify a scale only for DECIMAL FIXED.
2 You can specify host variable attributes in any order that is acceptable to
PL/I. For example, BIN FIXED(31), BINARY FIXED(31), BIN(31) FIXED, and
FIXED BIN(31) are all acceptable.
For floating-point data types, use the FLOAT SQL processing option to specify
whether the host variable is in IEEE binary floating-point or z/Architecture
hexadecimal floating-point format. DB2 does not check if the format of the host
variable contents match the format that you specified with the FLOAT SQL
processing option. Therefore, you need to ensure that your floating-point host
variable contents match the format that you specified with the FLOAT SQL
processing option. DB2 converts all floating-point input data to z/Architecture
hexadecimal floating-point format before storing it.
Chapter 3. Including DB2 queries in an application program 173
If the PL/I compiler that you are using does not support a decimal data type with
a precision greater than 15, use one of the following variable types for decimal
data:
v Decimal variables with precision less than or equal to 15, if the actual data
values fit. If you retrieve a decimal value into a decimal variable with a scale
that is less than the source column in the database, the fractional part of the
value might truncate.
v An integer or a floating-point variable, which converts the value. If you use an
integer variable, you lose the fractional part of the number. If the decimal
number can exceed the maximum value for an integer or you want to preserve a
fractional value, use a floating-point variable. Floating-point numbers are
approximations of real numbers. Therefore, when you assign a decimal number
to a floating-point variable, the result might be different from the original
number.
v A character string host variable. Use the CHAR function to retrieve a decimal
value into it.
Character host variables
The following diagram shows the syntax for declaring character host variables,
other than CLOBs.
DECLARE
DCL

variable-name
,
( variable-name )

CHARACTER ( length )
CHAR VARYING
VAR

Alignment and/or Scope and/or Storage

Graphic host variables


The following diagram shows the syntax for declaring graphic host variables other
than DBCLOBs.
DECLARE
DCL

variable-name
,
( variable-name )

GRAPHIC ( length )
VARYING
VAR

Alignment and/or Scope and/or Storage

Binary host variables


You can specify the following forms of binary host variables:
v Fixed-length strings
174 Application Programming and SQL Guide
|
|
|
v Varying-length strings
v BLOBs
The following diagram shows the syntax for declaring BINARY host variables.
DECLARE
DCL

variable-name
,
( variable-name )
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING

(1)
( length ) ;
Notes:
1 For BINARY host variables, the length must be in the range from 1 to 255.
For VARBINARY host variables, the length must be in the range from 1 to
32 704.
PL/I does not have variables that correspond to the SQL binary data types
BINARY and VARBINARY. To create host variables that can be used with these
data types, use the SQL TYPE IS clause.
When you reference a BINARY or VARBINARY host variable in an SQL statement,
you must use the variable that you specify in the SQL TYPE declaration. When
you reference the host variable in a host language statement, you must use the
variable that DB2 generates.
Examples of binary variable declarations: The following table shows examples of
variables that DB2 generates when you declare binary host variables.
Table 48. Examples of BINARY and VARBINARY variable declarations for PL/I
Variable declaration that you include in
your PL/I program
Corresponding variable that DB2 generates
in the output source member
DCL BIN_VAR SQL TYPE IS BINARY(10); DCL BIN_VAR CHAR(10);
DCL VBIN_VAR SQL TYPE IS VARBINARY(10); DCL VBIN_VAR CHAR(10) VAR;
Result set locators
The following diagram shows the syntax for declaring result set locators.
DECLARE
DCL

variable-name
,
( variable-name )

SQL TYPE IS RESULT_SET_LOCATOR VARYING

Alignment and/or Scope and/or Storage

Chapter 3. Including DB2 queries in an application program 175


|
|
|
||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||
|
|
||
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
||
||
|
|
Table locators
The following diagram shows the syntax for declaring table locators.
DCL
DECLARE

variable-name
,
( variable-name )

SQL TYPE IS TABLE LIKE table-name AS LOCATOR


LOB variables, locators, and file reference variables
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variables, locators, and file reference variables.
DCL
(1)
DECLARE

variable-name
,
( variable-name )
SQL TYPE IS

(2)
BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_LOCATOR
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

Notes:
1 A single PL/I declaration that contains a LOB variable declaration is limited
to no more than 1000 lines of source code.
2 Variable attributes such as STATIC and AUTOMATIC are ignored if specified
on a LOB variable declaration.
Note: Variable attributes such as STATIC and AUTOMATIC are ignored if
specified on a LOB variable declaration.
XML data host and file reference variables
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variables and file reference variables for XML data types.
DCL
DECLARE

variable-name
,
( variable-name )
SQL TYPE IS XML AS
176 Application Programming and SQL Guide
|
|
||||||
|
|
|
|
|
|||||||||||||||||||||||||||||||||
|
||
BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

ROWID host variables


The following diagram shows the syntax for declaring ROWID host variables.
DCL
DECLARE

variable-name
,
( variable-name )
SQL TYPE IS ROWID
Related concepts
Large objects (LOBs) on page 400
Host variable arrays
Use host variable arrays to pass a data array between DB2 and your application.
A host variable array is a data array that is declared in the host language to be used
within an SQL statement. You can use host variable arrays to perform the
following actions:
v Retrieve data into host variable arrays for your application programs use
v Place data into host variable arrays to insert rows into a table
You typically define host variable arrays for use with multiple-row FETCH,
INSERT, and MERGE statements.
C and C++ syntax for host variable array declarations
In C and C++ programs, you can specify numeric, character, graphic, binary, LOB,
XML, and ROWID host variable arrays. You can also specify LOB locators and
LOB and XML file reference variables.
Restrictions:
v Only some of the valid C declarations are valid host variable array declarations.
If the declaration for a variable array is not valid, any SQL statement that
references the variable array might result in the message UNDECLARED HOST
VARIABLE ARRAY.
v For both C and C++, you cannot specify the _packed attribute on the structure
declarations for the following arrays that are used in multiple-row INSERT,
FETCH, and MERGE statements:
varying-length character arrays
varying-length graphic arrays
LOB arrays
In addition, the #pragma pack(1) directive cannot be in effect if you plan to use
these arrays in multiple-row statements.
Chapter 3. Including DB2 queries in an application program 177
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Numeric host variable arrays
The following diagram shows the syntax for declaring numeric host variable
arrays.

auto
extern
static
const
volatile
unsigned

float
double
int
long
short
int
long long
decimal ( precision )
, scale

,
(1)
variable-name [ dimension ]
,
= { expression }
;
Notes:
1 dimension must be an integer constant between 1 and 32767.
Example: The following example shows a declaration of a numeric host variable
array:
EXEC SQL BEGIN DECLARE SECTION;
/* declaration of numeric host variable array */
long serial_num[10];
...
EXEC SQL END DECLARE SECTION;
Character host variable arrays
You can specify the following forms of character host variable arrays:
v NUL-terminated character form
v VARCHAR structured form
v CLOBs
The following diagrams show the syntax for forms other than CLOBs.
The following diagram shows the syntax for declaring NUL-terminated character
host variable arrays.

auto
extern
static
const
volatile
char
unsigned

178 Application Programming and SQL Guide

,
(1) (2) (3)
variable-name [ dimension ] [ length ] ;
,
= { expression }

Notes:
1 dimension must be an integer constant between 1 and 32767.
2 Any string that is assigned to this variable must be NUL-terminated. Any
string that is retrieved from this variable is NUL-terminated.
3 The strings in a NUL-terminated character host variable array map to
varying-length character strings (except for the NUL).
The following diagram shows the syntax for declaring varying-length character
host variable arrays that use the VARCHAR structured form.

auto
extern
static
const
volatile

(1) int (2)


struct { short var-1 ;

(3)
char var-2 [ length ] ; }
unsigned

,
(4)
variable-name [ dimension ] ;
,
= { expression }

Notes:
1 You can use the struct tag to define other variables, but you cannot use them
as host variable arrays in SQL.
2 var-1 must be a scalar numeric variable.
3 var-2 must be a scalar CHAR array variable.
4 dimension must be an integer constant between 1 and 32767.
Example: The following example shows valid and invalid declarations of
VARCHAR host variable arrays.
EXEC SQL BEGIN DECLARE SECTION;
/* valid declaration of VARCHAR host variable array */
struct VARCHAR {
short len;
char s[18];
} name[10];
/* invalid declaration of VARCHAR host variable array */
struct VARCHAR name[10];
Chapter 3. Including DB2 queries in an application program 179
|
|
Binary host variable arrays
The following diagram shows the syntax for declaring binary host variable arrays.

auto
extern
static
register
const
volatile
SQL TYPE IS BINARY
VARBINARY
(length)


,
(1)
variable-name [ dimension ] ;
Notes:
1 dimension must be an integer constant between 1 and 32767.
Graphic host variable arrays
You can specify the following forms of graphic host variable arrays:
v NUL-terminated graphic form
v VARGRAPHIC structured form.
Recommendation: Instead of using the C data type wchar_t to define graphic and
vargraphic host variable arrays, use one of the following techniques:
v Define the sqldbchar data type by using the following typedef statement:
typedef unsigned short sqldbchar;
v Use the sqldbchar data type that is defined in the typedef statement in the
header files that are supplied by DB2.
v Use the C data type unsigned short.
The following diagram shows the syntax for declaring NUL-terminated graphic
host variable arrays.

auto
extern
static
const
volatile
sqldbchar
unsigned

,
(1) (2) (3) (4)
variable-name [ dimension ] [ length ] ;
,
= { expression }

Notes:
1 dimension must be an integer constant between 1 and 32767.
2 length must be a decimal integer constant greater than 1 and not greater than
16352.
3 Any string that is assigned to this variable must be NUL-terminated. Any
string that is retrieved from this variable is NUL-terminated.
180 Application Programming and SQL Guide
|
|
||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||
|
|
||
|
4 Do not assign single-byte characters into a NUL-terminated graphic host
variable array
The following diagram shows the syntax for declaring graphic host variable arrays
that use the VARGRAPHIC structured form.

auto
extern
static
const
volatile

(1) int (2)


struct { short var-1 ;

(3) (4)
sqldbchar var-2 [ length ] ; }
unsigned

,
(5)
variable-name [ dimension ] ;
,
= { expression }

Notes:
1 You can use the struct tag to define other variables, but you cannot use them
as host variable arrays in SQL.
2 var-1 must be a scalar numeric variable.
3 var-2 must be a scalar char array variable.
4 length must be a decimal integer constant greater than 1 and not greater than
16352.
5 dimension must be an integer constant between 1 and 32767.
Example: The following example shows valid and invalid declarations of graphic
host variable arrays that use the VARGRAPHIC structured form.
EXEC SQL BEGIN DECLARE SECTION;
/* valid declaration of host variable array vgraph */
struct VARGRAPH {
short len;
sqldbchar d[10];
} vgraph[20];
/* invalid declaration of host variable array vgraph */
struct VARGRAPH vgraph[20];
LOB, locator, and file reference variable arrays
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variable arrays, locators, and file reference variables.
Chapter 3. Including DB2 queries in an application program 181

auto
extern
static
register
const
volatile
SQL TYPE IS
BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_LOCATOR
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

,
(1)
variable-name [ dimension ] ;
,
= { expression }

Notes:
1 dimension must be an integer constant between 1 and 32767.
XML host and file reference variable arrays
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variable arrays and file reference variable arrays for XML data types.

auto
extern
static
register
const
volatile
SQL TYPE IS XML AS
BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

182 Application Programming and SQL Guide


|||
|
|
|
|||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||

,
(1)
variable-name [ dimension ] ;
,
= { expression }

Notes:
1 dimension must be an integer constant between 1 and 32767.
ROWID variable arrays
The following diagram shows the syntax for declaring ROWID variable arrays.


,
(1)
SQL TYPE IS ROWID variable-name [ dimension ] ;
auto const
extern volatile
static
register

Notes:
1 dimension must be an integer constant between 1 and 32767.
Related concepts
Large objects (LOBs) on page 400
COBOL syntax for host variable array declarations
In COBOL programs, you can specify numeric, character, graphic, LOB, XML, and
ROWID host variable arrays. You can also specify LOB locators and LOB and XML
file reference variables.
Restriction: Only some of the valid COBOL declarations are valid host variable
array declarations. If the declaration for a variable array is not valid, any SQL
statement that references the variable array might result in the message
UNDECLARED HOST VARIABLE ARRAY.
Numeric host variable arrays
You can specify the following forms of numeric host variable arrays:
v Floating-point numbers
v Integers and small integers
v Decimal numbers
The following diagram shows the syntax for declaring floating-point host variable
arrays.

(1)
level-1 variable-name
IS
USAGE
COMPUTATIONAL-1
(2)
COMP-1
COMPUTATIONAL-2
(3)
COMP-2

Chapter 3. Including DB2 queries in an application program 183


||||||||||||||||||||||||||||||||||||||||
|
|
||
|

(4)
OCCURS dimension
TIMES IS
VALUE numeric-constant
.
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 COMPUTATIONAL-1 and COMP-1 are equivalent.
3 COMPUTATIONAL-2 and COMP-2 are equivalent.
4 dimension must be an integer constant between 1 and 32767.
The following diagram shows the syntax for declaring integer and small integer
host variable arrays.

(1)
level-1 variable-name PICTURE
PIC
IS
S9(4)
S9999
S9(9)
S999999999

IS
USAGE
(2)
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
(3)
COMP-5
COMPUTATIONAL
COMP
(4)
OCCURS dimension
TIMES

IS
VALUE numeric-constant
(5)
.
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 The COBOL binary integer data types BINARY, COMPUTATIONAL, COMP,
COMPUTATIONAL-4, and COMP-4 are equivalent.
3 COMPUTATIONAL-5 (and COMP-5) are equivalent to the other COBOL
binary integer data types if you compile the other data types with
TRUNC(BIN).
4 dimension must be an integer constant between 1 and 32767.
5 Any specification for scale is ignored.
The following diagram shows the syntax for declaring decimal host variable
arrays.

(1)
level-1 variable-name PICTURE
PIC
IS
picture-string
184 Application Programming and SQL Guide

IS
USAGE

(2)
PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
IS (3) CHARACTER
DISPLAY SIGN LEADING SEPARATE
NATIONAL

(4)
OCCURS dimension
TIMES IS
VALUE numeric-constant
.
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 PACKED-DECIMAL, COMPUTATIONAL-3, and COMP-3 are equivalent. The
picture-string that is associated with these types must have the form S9(i)V9(d)
(or S9...9V9...9, with i and d instances of 9) or S9(i)V.
3 The picture-string that is associated with SIGN LEADING SEPARATE must
have the form S9(i)V9(d) (or S9...9V9...9, with i and d instances of 9 or S9...9V
with i instances of 9).
4 dimension must be an integer constant between 1 and 32767.
Character host variable arrays
You can specify the following forms of character host variable arrays:
v Fixed-length character strings
v Varying-length character strings
v CLOBs
The following diagrams show the syntax for forms other than CLOBs.
The following diagram shows the syntax for declaring fixed-length character string
arrays.

(1)
level-1 variable-name PICTURE
PIC
IS (2)
picture-string

DISPLAY
IS
USAGE
(3)
OCCURS dimension
TIMES

IS
VALUE character-constant
.
Chapter 3. Including DB2 queries in an application program 185
Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 The picture-string must be in the form X(m) (or XX...X, with m instances of X),
where 1 <= m <= 32767 for fixed-length strings. However, the maximum
length of the CHAR data type (fixed-length character string) in DB2 is 255
bytes.
3 dimension must be an integer constant between 1 and 32767.
The following diagrams show the syntax for declaring varying-length character
string arrays.

(1) (2)
level-1 variable-name OCCURS dimension .
TIMES

Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 dimension must be an integer constant between 1 and 32767.

(1)
49 var-1 PICTURE
PIC
IS (2)
S9(4)
S9999 IS
USAGE

BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP
SYNCHRONIZED
SYNC IS
VALUE numeric-constant

.
Notes:
1 You cannot directly reference var-1 as a host variable array.
2 DB2 uses the full length of the S9(4) BINARY variable even though COBOL
with TRUNC(STD) recognizes values up to only 9999. This behavior can
cause data truncation errors when COBOL statements execute and might
effectively limit the maximum length of variable-length character strings to
9999. Consider using the TRUNC(BIN) compiler option or USAGE COMP-5
to avoid data truncation.

(1)
49 var-2 PICTURE
PIC
IS (2)
picture-string
186 Application Programming and SQL Guide

DISPLAY
IS
USAGE
IS
VALUE character-constant

(3)
.
Notes:
1 You cannot directly reference var-2 as a host variable array.
2 The picture-string must be in the form X(m) (or XX...X, with m instances of X),
where 1 <= m <= 32767 for fixed-length strings; for other strings, m cannot be
greater than the maximum size of a varying-length character string.
3 You cannot use an intervening REDEFINE at level 49.
Example: The following example shows declarations of a fixed-length character
array and a varying-length character array.
01 OUTPUT-VARS.
05 NAME OCCURS 10 TIMES.
49 NAME-LEN PIC S9(4) COMP-4 SYNC.
49 NAME-DATA PIC X(40).
05 SERIAL-NUMBER PIC S9(9) COMP-4 OCCURS 10 TIMES.
Graphic character host variable arrays
You can specify the following forms of graphic host variable arrays:
v Fixed-length strings
v Varying-length strings
v DBCLOBs
The following diagrams show the syntax for forms other than DBCLOBs.
The following diagram shows the syntax for declaring fixed-length graphic string
arrays.

(1)
level-1 variable-name PICTURE
PIC
IS (2)
picture-string

IS
USAGE DISPLAY-1
(3) (4)
NATIONAL
(5)
OCCURS dimension
TIMES

.
IS
VALUE graphic-constant

Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 For fixed-length strings, the format for picture-string is G(m) or N(m) (or, m
Chapter 3. Including DB2 queries in an application program 187
instances of GG...G or NN...N), where 1 <= m <= 127; for other strings, m
cannot be greater than the maximum size of a varying-length graphic string.
3 Use USAGE NATIONAL only for Unicode UTF-16 data. In the picture-string
for USAGE NATIONAL, you must use N in place of G.
4 You can use USAGE NATIONAL only if you are using the DB2 coprocessor.
5 dimension must be an integer constant between 1 and 32767.
The following diagrams show the syntax for declaring varying-length graphic
string arrays.

(1) (2)
level-1 variable-name OCCURS dimension .
TIMES

Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 dimension must be an integer constant between 1 and 32767.

(1)
49 var-1 PICTURE
PIC
IS (2)
S9(4)
S9999 IS
USAGE

BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP
SYNCHRONIZED
SYNC IS
VALUE numeric-constant

.
Notes:
1 You cannot directly reference var-1 as a host variable array.
2 DB2 uses the full length of the S9(4) BINARY variable even though COBOL
with TRUNC(STD) recognizes values up to only 9999. This behavior can
cause data truncation errors when COBOL statements execute and might
effectively limit the maximum length of variable-length character strings to
9999. Consider using the TRUNC(BIN) compiler option or USAGE COMP-5
to avoid data truncation.

(1)
49 var-2 PICTURE
PIC

188 Application Programming and SQL Guide

IS (2) IS
picture-string USAGE DISPLAY-1
(3) (4)
NATIONAL

IS
VALUE graphic-constant
.
Notes:
1 You cannot directly reference var-2 as a host variable array.
2 For fixed-length strings, the format for picture-string is G(m) or N(m) (or, m
instances of GG...G or NN...N), where 1 <= m <= 127; for other strings, m
cannot be greater than the maximum size of a varying-length graphic string.
3 Use USAGE NATIONAL only for Unicode UTF-16 data. In the picture-string
for USAGE NATIONAL, you must use N in place of G.
4 You can use USAGE NATIONAL only if you are using the DB2 coprocessor.
LOB, locator, and file reference variable arrays
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variable, locator, and file reference arrays.

(1)
level-1 variable-name
IS
USAGE
SQL TYPE IS
BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB-LOCATOR
CLOB-LOCATOR
DBCLOB-LOCATOR
BLOB-FILE
CLOB-FILE
DBCLOB-FILE

(2)
OCCURS dimension .
TIMES

Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 dimension must be an integer constant between 1 and 32767.
Chapter 3. Including DB2 queries in an application program 189
|
|
||||||
XML host and file reference variable arrays
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variable and file reference arrays for XML data types.

(1)
level-1 variable-name
IS
USAGE
SQL TYPE IS XML AS
BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB-FILE
CLOB-FILE
DBCLOB-FILE

(2)
OCCURS dimension .
TIMES

Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 dimension must be an integer constant between 1 and 32767.
ROWID variable arrays
The following diagram shows the syntax for declaring ROWID variable arrays.

(1) (2)
level-1 variable-name SQL TYPE IS ROWID OCCURS dimension .
IS TIMES
USAGE

Notes:
1 level-1 indicates a COBOL level between 2 and 48.
2 dimension must be an integer constant between 1 and 32767.
Related concepts
Large objects (LOBs) on page 400
PL/I syntax for host variable array declarations
In PL/I programs, you can specify numeric, character, graphic, binary, LOB, XML,
and ROWID host variable arrays. You can also specify LOB locators and LOB and
XML file reference variables.
Restrictions:
v Only some of the valid PL/I declarations are valid host variable declarations.
The precompiler uses the data attribute defaults that are specified in the PL/I
DEFAULT statement. If the declaration for a host variable is not valid, any SQL
statement that references the host variable array might result in the message
UNDECLARED HOST VARIABLE ARRAY.
190 Application Programming and SQL Guide
|
|
|
||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||
|
|
||
||
|
v The alignment, scope, and storage attributes of host variable arrays have the
following restrictions:
A declaration with the EXTERNAL scope attribute and the STATIC storage
attribute must also have the INITIAL storage attribute.
If you use the BASED storage attribute, you must follow it with a PL/I
element-locator-expression.
Host variables can be STATIC, CONTROLLED, BASED, or AUTOMATIC
storage class, or options. However, CICS requires that programs be reentrant.
Although the precompiler uses only the names and data attributes of variable
arrays and ignores the alignment, scope, and storage attributes, you should not
ignore these restrictions. If you do ignore them, you might have problems
compiling the PL/I source code that the precompiler generates.
v You must specify the ALIGNED attribute when you declare varying-length
character arrays or varying-length graphic arrays that are to be used in
multiple-row INSERT and FETCH statements.
Numeric host variable arrays
The following diagram shows the syntax for declaring numeric host variable
arrays.
DECLARE
DCL

(1)
variable-name ( dimension )
,
( variable-name )
,
(1)
( variable-name ( dimension ) )

(3)
BINARY FIXED
BIN ( precision )
DECIMAL (2)
DEC ,scale
FLOAT ( precision )

Alignment and/or Scope and/or Storage

Notes:
1 dimension must be an integer constant between 1 and 32767.
2 You can specify the scale for only DECIMAL FIXED.
3 You can specify host variable array attributes in any order that is acceptable
to PL/I. For example, BIN FIXED(31), BINARY FIXED(31), BIN(31) FIXED,
and FIXED BIN(31) are all acceptable.
Example: The following example shows a declaration of an indicator array.
DCL IND_ARRAY(100) BIN FIXED(15); /* DCL ARRAY of 100 indicator variables */
Chapter 3. Including DB2 queries in an application program 191
Character host variable arrays
The following diagram shows the syntax for declaring character host variable
arrays other than CLOBs.
DECLARE
DCL

(1)
variable-name ( dimension )
,
( variable-name )
,
(1)
( variable-name ( dimension ) )

CHARACTER ( length )
CHAR VARYING Alignment and/or Scope and/or Storage
VAR

Notes:
1 dimension must be an integer constant between 1 and 32767.
Example: The following example shows the declarations needed to retrieve 10
rows of the department number and name from the department table:
DCL DEPTNO(10) CHAR(3); /* Array of ten CHAR(3) variables */
DCL DEPTNAME(10) CHAR(29) VAR; /* Array of ten VARCHAR(29) variables */
Graphic host variable arrays
The following diagram shows the syntax for declaring graphic host variable arrays
other than DBCLOBs.
DECLARE
DCL

(1)
variable-name ( dimension )
,
( variable-name )
,
(1)
( variable-name ( dimension ) )

GRAPHIC ( length )
VARYING Alignment and/or Scope and/or Storage
VAR

Notes:
1 dimension must be an integer constant between 1 and 32767.
Binary host variable arrays
The following diagram shows the syntax for declaring binary variable arrays.
DCL
DECLARE

variable-name ( dimension )
,
( variable-name )
,
( variable-name ( dimension ) )

192 Application Programming and SQL Guide


|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||
SQL TYPE IS BINARY
VARBINARY

LOB, locator, and file reference variable arrays


The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variable, locator, and file reference variable arrays.
DCL
DECLARE

(1)
variable-name ( dimension )
,
( variable-name )
,
(1)
( variable-name ( dimension ) )

SQL TYPE IS BINARY LARGE OBJECT ( length )


BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_LOCATOR
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

Notes:
1 dimension must be an integer constant between 1 and 32767.
XML host and file reference variable arrays
The following diagram shows the syntax for declaring BLOB, CLOB, and DBCLOB
host variable arrays and file reference variable arrays for XML data types.
DCL
DECLARE

(1)
variable-name ( dimension )
,
( variable-name )
,
(1)
( variable-name ( dimension ) )

Chapter 3. Including DB2 queries in an application program 193


|
|
|||||||||||||||
|
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||
SQL TYPE IS XML AS BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

Notes:
1 dimension must be an integer constant between 1 and 32767.
ROWID variable arrays
The following diagram shows the syntax for declaring ROWID variable arrays.
DCL
DECLARE

(1)
variable-name ( dimension )
,
( variable-name )
,
(1)
( variable-name ( dimension ) )

SQL TYPE IS ROWID


Notes:
1 dimension must be an integer constant between 1 and 32767.
Related concepts
Large objects (LOBs) on page 400
Host structures
Use host structures to pass a group of host variables between DB2 and your
application.
A host structure is a group of host variables that can be referenced with a single
name. You can use host structures in all host languages except REXX. You define
host structures with statements in the host language. You can refer to a host
structure in any context where you want to refer to the list of host variables in the
structure. A host structure reference is equivalent to a reference to each of the host
variables within the structure in the order in which they are defined in the
structure declaration. You can also use indicator variables (or indicator structures)
with host structures.
C and C++ syntax for host structures
A C host structure contains an ordered group of data fields.
194 Application Programming and SQL Guide
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||
|
Host structures
The following diagram shows the syntax for declaring host structures.

auto
extern
static
const
volatile
struct {
packed tag


float var-1 ;
double
int
short
sqlint32
int
long
int
long long
decimal ( precision
, scale )
varchar structure
binary structure
vargraphic structure
SQL TYPE IS ROWID
LOB data type
char var-2 ;
unsigned [ length ]
sqldbchar var-5 ;
[ length ]
}
variable-name ;
=expression

VARCHAR structures
The following diagram shows the syntax for VARCHAR structures that are used
within declarations of host structures.

int
struct { short var-3 ;
tag signed

char var-4 [ length ] ; }


unsigned

VARGRAPHIC structures
The following diagram shows the syntax for VARGRAPHIC structures that are
used within declarations of host structures.
Chapter 3. Including DB2 queries in an application program 195
|||

int
struct { short var-6 ; sqldbchar var-7 [ length ] ; }
tag signed

Binary structures
The following diagram shows the syntax for binary structures that are used within
declarations of host structures.
SQL TYPE IS BINARY (length)
VARBINARY
BINARY VARYING

LOB data types


The following diagram shows the syntax for LOB data types that are used within
declarations of host structures.
SQL TYPE IS BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_LOCATOR
CLOB_LOCATOR
DBCLOB_LOCATOR

LOB data types for XML data


The following diagram shows the syntax for LOB data types that are used within
declarations of host structures for XML data.
SQL TYPE IS XML AS BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

Example
In the following example, the host structure is named target, and it contains the
fields c1, c2, and c3. c1 and c3 are character arrays, and c2 is a host variable that is
equivalent to the SQL VARCHAR data type. The target host structure can be part
of another host structure but must be the deepest level of the nested structure.
struct {char c1[3];
struct {short len;
char data[5];
}c2;
char c3[2];
}target;
196 Application Programming and SQL Guide
|
|
|
|||||||||||||||||||
|
|
|
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
COBOL syntax for host structures
A COBOL host structure is a named set of host variables that are defined in your
programs WORKING-STORAGE SECTION or LINKAGE SECTION.
Requirements: Host structure declarations in COBOL must satisfy the following
requirements:
v COBOL host structures can have a maximum of two levels, even though the
host structure might occur within a structure with multiple levels. However, you
can declare a varying-length character string, which must be level 49.
v A host structure name can be a group name whose subordinate levels name
elementary data items.
v If you are using the DB2 precompiler, do not declare host variables or host
structures on any subordinate levels after one of the following items:
A COBOL item that begins in area A
Any SQL statement (except SQL INCLUDE)
Any SQL statement within an included member
When the DB2 precompiler encounters one of the preceding items in a host
structure, it considers the structure to be complete.
When you write an SQL statement that contains a qualified host variable name
(perhaps to identify a field within a structure), use the name of the structure
followed by a period and the name of the field. For example, for structure B that
contains field C1, specify B.C1 rather than C1 OF B or C1 IN B.
Host structures
The following diagram shows the syntax for declaring host structures.

(1)
level-1 variable-name .


(2) (3) (4)
level-2 var-1 numeric-usage .
IS
PICTURE integer-decimal-usage .
PIC picture-string
char-inner-variable .
varchar-inner-variables
vargraphic-inner-variables
SQL TYPE IS ROWID .
IS
USAGE
SQL TYPE IS TABLE LIKE table-name AS LOCATOR .
IS
USAGE
LOB data type .
IS
USAGE

Notes:
1 level-1 indicates a COBOL level between 1 and 47.
2 level-2 indicates a COBOL level between 2 and 48.
3 For elements within a structure, use any level 02 through 48 (rather than 01
or 77), up to a maximum of two levels.
4 Using a FILLER or optional FILLER item within a host structure declaration
can invalidate the whole structure.
Chapter 3. Including DB2 queries in an application program 197
Numeric usage items
The following diagram shows the syntax for numeric-usage items that are used
within declarations of host structures.
COMPUTATIONAL-1
IS COMP-1 IS
USAGE COMPUTATIONAL-2 VALUE constant
COMP-2

Integer and decimal usage items


The following diagram shows the syntax for integer and decimal usage items that
are used within declarations of host structures.

IS
USAGE

BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP
PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
IS
DISPLAY SIGN LEADING SEPARATE
NATIONAL CHARACTER

IS
VALUE constant

CHAR inner variables


The following diagram shows the syntax for CHAR inner variables that are used
within declarations of host structures.
PICTURE
PIC
IS
picture-string
DISPLAY
IS
USAGE

IS
VALUE constant

198 Application Programming and SQL Guide


VARCHAR inner variables
The following diagrams show the syntax for VARCHAR inner variables that are
used within declarations of host structures.

(1)
49 var-2 PICTURE
PIC
IS
S9(4)
S9999 IS
USAGE

BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP
IS
VALUE numeric-constant
.
Notes:
1 The number 49 has a special meaning to DB2. Do not specify another number.
49 var-3 PICTURE
PIC
IS
picture-string

DISPLAY
IS
USAGE
IS
VALUE character-constant
.
VARGRAPHIC inner variables
The following diagrams show the syntax for VARGRAPHIC inner variables that
are used within declarations of host structures.
49 var-4 PICTURE
PIC
IS
S9(4)
S9999 IS
USAGE

BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP
IS
VALUE numeric-constant
.
49 var-5 PICTURE
PIC
IS (1)
picture-string
IS
USAGE

Chapter 3. Including DB2 queries in an application program 199


|

(2) (3)
DISPLAY-1
NATIONAL IS
VALUE graphic-constant
.
Notes:
1 For fixed-length strings, the format of picture-string is G(m) or N(m) (or, m
instances of GG...G or NN...N), where 1 <= m <= 127; for other strings, m
cannot be greater than the maximum size of a varying-length graphic string.
2 Use USAGE NATIONAL for only Unicode UTF-16 data. In the picture-string
for USAGE NATIONAL, you must use N in place of G.
3 You can use USAGE NATIONAL only if you are using the DB2 coprocessor.
LOB variables, locators, and file reference variables
The following diagram shows the syntax for LOB variables, locators, and file
reference variables that are used within declarations of host structures.
SQL TYPE IS BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB-LOCATOR
CLOB-LOCATOR
DBCLOB-LOCATOR
BLOB-FILE
CLOB-FILE
DBCLOB-FILE

LOB variables and file reference variables for XML data


The following diagram shows the syntax for LOB variables and file reference
variables that are used within declarations of host structures for XML.
SQL TYPE IS XML AS BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB-FILE
CLOB-FILE
DBCLOB-FILE

Example
In the following example, B is the name of a host structure that contains the
elementary items C1 and C2.
01 A
02 B
03 C1 PICTURE ...
03 C2 PICTURE ...
200 Application Programming and SQL Guide
||||||
|
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
To reference the C1 field in an SQL statement, specify B.C1.
PL/I syntax for host structures
A PL/I host structure is a structure that contains subordinate levels of scalars. You
can use the name of the structure as shorthand notation to reference the list of
scalars.
Requirements: Host structure declarations in PL/I must satisfy the following
requirements:
v Host structures are limited to two levels.
v You must terminate the host structure variable by ending the declaration with a
semicolon.
Example:
DCL 1 A,
2 B CHAR,
2 (C, D) CHAR;
DCL (E, F) CHAR;
v You can specify host variable attributes in any order that is acceptable to PL/I.
For example, BIN FIXED(31), BIN(31) FIXED, and FIXED BIN(31) are all
acceptable.
When you reference a host variable, you can qualify it with a structure name. For
example, you can specify STRUCTURE.FIELD.
Host structures
The following diagram shows the syntax for declaring host structures.
DECLARE
DCL
level-1 variable-name ,
Scope and/or storage

,
level-2 var-1 data-type-specification
,
( var-2 )
;
Data types
The following diagram shows the syntax for data types that are used within
declarations of host structures.
Chapter 3. Including DB2 queries in an application program 201
CHARACTER
CHAR ( integer ) VARYING
VAR
GRAPHIC
( integer ) VARYING
VAR
BINARY FIXED
BIN ( precision )
DECIMAL , scale
DEC FLOAT
( precision )
SQL TYPE IS ROWID
LOB data type

LOB data types


The following diagram shows the syntax for LOB data types that are used within
declarations of host structures.
SQL TYPE IS CHARACTER LARGE OBJECT ( length )
CHAR LARGE OBJECT K
CLOB M
DBCLOB G
BINARY LARGE OBJECT
BLOB
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_LOCATOR
CLOB_FILE
DBCLOB_FILE
BLOB_FILE

LOB data types for XML data


The following diagram shows the syntax for LOB data types that are used within
declarations of host structures for XML data.
SQL TYPE IS XML AS BINARY LARGE OBJECT ( length )
BLOB K
CHARACTER LARGE OBJECT M
CHAR LARGE OBJECT G
CLOB
DBCLOB
BLOB_FILE
CLOB_FILE
DBCLOB_FILE

Example
In the following example, B is the name of a host structure that contains the scalars
C1 and C2.
DCL 1 A,
2 B,
3 C1 CHAR(...),
3 C2 CHAR(...);
202 Application Programming and SQL Guide
||
||||||
|
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
Defining indicator variables, arrays, and structures
Use indicator variables, arrays, and structures to store variable information, such as
whether the variable value is null. You must associate an indicator variable, array,
or structure with a particular host variable, array, or structure.
To define indicator variables, arrays, and structures:
1. Declare the indicator variable, array, or structure as you would for any other
variables, arrays, and structures. Follow the rules for the appropriate host
language.
Requirements:
v An indicator variable array must have at least as many entries as the host
variable array with which you plan to associate it.
v For COBOL, define indicator structures in the DATA DIVISION section of
your program.
2. Associate the indicator variable, array, or structure with a particular host
variable, array, or structure in a particular SQL statement. To make this
association, specify the indicator variable, array, or structure, preceded by a
colon, immediately after the host variable, array, or structure. Optionally, you
can also specify the word INDICATOR between the two items.
Examples
Example of defining an indicator variable: The following two examples are
logically equivalent. They both define the indicator variable INDNULL for the host
variable CBLPHONE. However, the second example uses the optional INDICATOR
keyword.
EXEC SQL
SELECT PHONENO
INTO :CBLPHONE:INDNULL
FROM DSN8910.EMP
WHERE EMPNO = :EMPID
END-EXEC.
EXEC SQL
SELECT PHONENO
INTO :CBLPHONE INDICATOR :INDNULL
FROM DSN8910.EMP
WHERE EMPNO = :EMPID
END-EXEC.
After defining the INDNULL indicator variable, you can test INDNULL to
determine if the PHONENO column contains a negative value.
Example of defining an indicator variable array: Suppose that you declare a
scrollable rowset cursor by using the following statement:
EXEC SQL
DECLARE CURS1 SCROLL CURSOR WITH ROWSET POSITIONING FOR
SELECT PHONENO
FROM DSN8810.EMP
END-EXEC.
The following two examples define indicator arrays in a multiple-row FETCH
statement. They both declare the indicator array INDNULL for the host variable
array CBLPHONE. However, the second example uses the optional INDICATOR
keyword.
Chapter 3. Including DB2 queries in an application program 203
EXEC SQL
FETCH NEXT ROWSET CURS1
FOR 10 ROWS
INTO :CBLPHONE :INDNULL
END-EXEC.
EXEC SQL
FETCH NEXT ROWSET CURS1
FOR 10 ROWS
INTO :CBLPHONE INDICATOR :INDNULL
END-EXEC.
After the multiple-row FETCH statement, you can test each element of the
INDNULL array to determine if the corresponding element in the CBLPHONE
host variable array is null.
Example of defining an indicator structure in COBOL: In the following example,
DB2 selects the values for a row of data into the PEMP-ROW host structure. The
corresponding indicator structure, EMP-IND, is an array that contains six values.
01 PEMP-ROW.
10 EMPNO PIC X(6).
10 FIRSTNME.
49 FIRSTNME-LEN PIC S9(4) USAGE COMP.
49 FIRSTNME-TEXT PIC X(12).
10 MIDINIT PIC X(1).
10 LASTNAME.
49 LASTNAME-LEN PIC S9(4) USAGE COMP.
49 LASTNAME-TEXT PIC X(15).
10 WORKDEPT PIC X(3).
10 EMP-BIRTHDATE PIC X(10).
01 INDICATOR-TABLE.
02 EMP-IND PIC S9(4) COMP OCCURS 6 TIMES.
.
.
.
MOVE '000230' TO EMPNO.
.
.
.
EXEC SQL
SELECT EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT, BIRTHDATE
INTO :PEMP-ROW:EMP-IND
FROM DSN8910.EMP
WHERE EMPNO = :EMPNO
END-EXEC.
You can use the values in EMP-IND to determine if any of the selected column
values are null. Because this example selects rows from the table DSN8910.EMP,
some of the values in EMP-IND are always zero. The first four columns of each
row are defined NOT NULL.
After you define an indicator variable, array, or structure, you can use those values
to determine if the corresponding variable values are null.
Related tasks
Determining whether a retrieved value in a host variable is null or truncated
on page 259
Accessing data by using a rowset-positioned cursor on page 646
Indicator variables, arrays, and structures
An indicator variable is associated with a particular host variable. Each indicator
variable contains a small integer value that indicates some information about the
associated host variable. Indicator arrays and structures serve the same purpose for
host variable arrays and structures.
You can use indicator variables to perform the following actions:
204 Application Programming and SQL Guide
v Determine whether the value of an associated output host variable is null or
indicate that the value of an input host variable is null
v Determine the original length of a character string that was truncated when it
was assigned to a host variable
v Determine that a character value could not be converted when it was assigned
to a host variable
v Determine the seconds portion of a time value that was truncated when it was
assigned to a host variable
You can use indicator variable arrays and indicator structures to perform these
same actions for individual items in host data arrays and structures.
If you provide an indicator variable for the variable X, when DB2 retrieves a null
value for X, it puts a negative value in the indicator variable and does not update
X. Your program should check the indicator variable before using X. If the
indicator variable is negative, you know that X is null and any value that you find
in X is irrelevant. When your program uses variable X to assign a null value to a
column, the program should set the indicator variable to a negative number. DB2
then assigns a null value to the column and ignores any value in X.
REXX: The way that you use indicator variables for input host variables in REXX
procedures is slightly different than the way that you use indicator variables in
other languages. When you want to pass a null value to a DB2 column, in addition
to putting a negative value in an indicator variable, you also need to put a valid
value in the corresponding host variable. For example, the following statements set
a value in the WORKDEPT column in table EMP to null:
SQLSTMT="UPDATE EMP" ,
"SET WORKDEPT = ?"
HVWORKDEPT='000'
INDWORKDEPT=-1
"EXECSQL PREPARE S100 FROM :SQLSTMT"
"EXECSQL EXECUTE S100 USING :HVWORKDEPT :INDWORKDEPT"
An indicator variable array contains a series of small integers to help you
determine the associated information for the corresponding item in a host data
array. When you retrieve data into a host variable array, you can check the values
in the associated indicator array to determine how to handle each data item. If a
value in the associated indicator array is negative, you can disregard the contents
of the corresponding element in the host variable array. Values in indicator arrays
have the following meanings:
-1 The corresponding row in the column that is being retrieved is null.
-2 DB2 returns a null value, because an error occurred in numeric conversion
or in an arithmetic expression in the corresponding row.
-3 DB2 returns a null value, because a hole was detected for the
corresponding row during a multiple-row FETCH operation.
An indicator structure is an array of halfword integer variables that supports a
specified host structure. If the column values that your program retrieves into a
host structure can be null, you can attach an indicator structure name to the host
structure name. This name enables DB2 to notify your program about each null
value it returns to a host variable in the host structure.
Chapter 3. Including DB2 queries in an application program 205
Example of how an indicator variable is used in a REXX program
In the following program, the phone number for employee Haas is selected into
variable HVPhone. After the SELECT statement executes, if no phone number for
employee Haas is found, indicator variable INDPhone contains -1.
'SUBCOM DSNREXX'
IF RC THEN ,
S_RC = RXSUBCOM('ADD','DSNREXX','DSNREXX')
ADDRESS DSNREXX
'CONNECT' 'DSN'
SQLSTMT = ,
"SELECT PHONENO FROM DSN8910.EMP WHERE LASTNAME='HAAS'"
"EXECSQL DECLARE C1 CURSOR FOR S1"
"EXECSQL PREPARE S1 FROM :SQLSTMT"
Say "SQLCODE from PREPARE is "SQLCODE
"EXECSQL OPEN C1"
Say "SQLCODE from OPEN is "SQLCODE
"EXECSQL FETCH C1 INTO :HVPhone :INDPhone"
Say "SQLCODE from FETCH is "SQLCODE
If INDPhone < 0 Then ,
Say 'Phone number for Haas is null.'
"EXECSQL CLOSE C1"
Say "SQLCODE from CLOSE is "SQLCODE
S_RC = RXSUBCOM('DELETE','DSNREXX','DSNREXX')
Related concepts
Holes in the result table of a scrollable cursor on page 654
Related tasks
Executing SQL statements by using a rowset cursor on page 647
Assembler syntax for indicator variable declarations
An indicator variable is a 2-byte integer (DS HL2). You declare indicator variables in
the same way as host variables. You can mix the declarations of the two types of
variables.
The following diagram shows the syntax for declaring an indicator variable in
assembler.
variable-name DC H
DS 1 L2

Example
The following example shows a FETCH statement with the declarations of the host
variables that are needed for the FETCH statement and their associated indicator
variables.
EXEC SQL FETCH CLS_CURSOR INTO :CLSCD, X
:DAY :DAYIND, X
:BGN :BGNIND, X
:END :ENDIND
You can declare these variables as follows:
CLSCD DS CL7
DAY DS HL2
BGN DS CL8
END DS CL8
DAYIND DS HL2 INDICATOR VARIABLE FOR DAY
BGNIND DS HL2 INDICATOR VARIABLE FOR BGN
ENDIND DS HL2 INDICATOR VARIABLE FOR END
206 Application Programming and SQL Guide
C and C++ syntax for indicator variable and array declarations
An indicator variable is a 2-byte integer (short int). An indicator variable array is
an array of 2-byte integers (short int). You declare indicator variables in the same
way as host variables. You can mix the declarations of the two types of variables.
The following diagram shows the syntax for declaring an indicator variable in C
and C++.

auto
extern
static
const
volatile
int
short
signed


,
variable-name
= expression
;
The following diagram shows the syntax for declaring an indicator array or a host
structure indicator array in C and C++.

auto
extern
static
const
volatile
int
short
signed


,
(1)
variable-name [ dimension ]
= expression
;
Notes:
1 dimension must be an integer constant between 1 and 32767.
Example
The following example shows a FETCH statement with the declarations of the host
variables that are needed for the FETCH statement and their associated indicator
variables.
EXEC SQL FETCH CLS_CURSOR INTO :ClsCd,
:Day :DayInd,
:Bgn :BgnInd,
:End :EndInd;
You can declare these variables as follows:
EXEC SQL BEGIN DECLARE SECTION;
char ClsCd[8];
char Bgn[9];
char End[9];
short Day, DayInd, BgnInd, EndInd;
EXEC SQL END DECLARE SECTION;
Chapter 3. Including DB2 queries in an application program 207
COBOL syntax for indicator variable and array declarations
An indicator variable is a 2-byte integer (PIC S9(4) USAGE BINARY). An indicator
variable array is an array of 2-byte integers (PIC S9(4) USAGE BINARY). You
declare indicator variables in the same way as host variables. You can mix the
declarations of the two types of variables.
You can define indicator variables as scalar variables or as array elements in a
structure form or as an array variable by using a single level OCCURS clause.
The following diagram shows the syntax for declaring an indicator variable in
COBOL.
01
77
variable-name PICTURE
PIC
IS
S9(4)
S9999 IS
USAGE

BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP
IS
VALUE constant
.
The following diagram shows the syntax for declaring an indicator array in
COBOL.

(1)
level-1 variable-name PICTURE
PIC
IS
S9(4)
S9999

IS
USAGE
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
COMPUTATIONAL
COMP
(2)
OCCURS dimension
TIMES

IS
VALUE constant
.
Notes:
1 level-1 must be an integer between 2 and 48.
2 dimension must be an integer constant between 1 and 32767.
208 Application Programming and SQL Guide
Example
The following example shows a FETCH statement with the declarations of the host
variables that are needed for the FETCH statement and their associated indicator
variables.
EXEC SQL FETCH CLS_CURSOR INTO :CLS-CD,
:DAY :DAY-IND,
:BGN :BGN-IND,
:END :END-IND
END-EXEC.
You can declare these variables as follows:
77 CLS-CD PIC X(7).
77 DAY PIC S9(4) BINARY.
77 BGN PIC X(8).
77 END PIC X(8).
77 DAY-IND PIC S9(4) BINARY.
77 BGN-IND PIC S9(4) BINARY.
77 END-IND PIC S9(4) BINARY.
Fortran syntax for indicator variable declarations
An indicator variable is a 2-byte integer (INTEGER*2). You declare indicator
variables in the same way as host variables. You can mix the declarations of the
two types of variables.
The following diagram shows the syntax for declaring an indicator variable in
Fortran.


,
INTEGER*2 variable-name
/ numeric-constant /

Example
The following example shows a FETCH statement with the declarations of the host
variables that are needed for the FETCH statement and their associated indicator
variables.
EXEC SQL FETCH CLS_CURSOR INTO :CLSCD,
C :DAY :DAYIND,
C :BGN :BGNIND,
C :END :ENDIND
You can declare these variables as follows:
CHARACTER*7 CLSCD
INTEGER*2 DAY
CHARACTER*8 BGN, END
INTEGER*2 DAYIND, BGNIND, ENDIND
PL/I syntax for indicator variable and array declarations
An indicator variable is a 2-byte integer (or an integer declared as BIN FIXED(15)).
An indicator variable array is an array of 2-byte integers. You declare indicator
variables in the same way as host variables. You can mix the declarations of the
two types of variables.
The following diagram shows the syntax for declaring an indicator variable in
PL/I.
Chapter 3. Including DB2 queries in an application program 209
DECLARE
DCL

,
( variable-name ) BINARY
BIN
(1)
FIXED(15) ;
Notes:
1 You can specify host variable attributes in any order that is acceptable to
PL/I. For example, BIN FIXED(31), BIN(31) FIXED, and FIXED BIN(31) are all
acceptable.
The following diagram shows the syntax for declaring an indicator array in PL/I.
DECLARE
DCL

variable-name ( dimension )
,
(1)
( variable-name ( dimension ) )
BINARY
BIN

FIXED(15) ;
Alignment and/or Scope and/or Storage

Notes:
1 dimension must be an integer constant between 1 and 32767.
Example
The following example shows a FETCH statement with the declarations of the host
variables that are needed for the FETCH statement and their associated indicator
variables.
EXEC SQL FETCH CLS_CURSOR INTO :CLS_CD,
:DAY :DAY_IND,
:BGN :BGN_IND,
:END :END_IND;
You can declare these variables as follows:
DCL CLS_CD CHAR(7);
DCL DAY BIN FIXED(15);
DCL BGN CHAR(8);
DCL END CHAR(8);
DCL (DAY_IND, BGN_IND, END_IND) BIN FIXED(15);
Declaring pointer host variables in C and C++ programs
If you use the DB2 coprocessor, you can use pointer host variables with statically
or dynamically allocated storage. These pointer host variables can point to numeric
data, non-numeric data, or a structure.
You can declare the following types of pointer host variables:
scalar pointer host variable
A host variable that points to numeric or non-numeric scalar data.
array pointer host variable
A host variable that is an array of pointers.
structure array host variable
A host variable that points to a structure.
210 Application Programming and SQL Guide
To declare pointer host variables in C and C++ programs:
Include an asterisk (*) in each variable declaration to indicate that the variable is a
pointer.
Restrictions:
v You cannot use pointer host variables that point to character data of an
unknown length. For example, do not specify the following declaration: char *
hvcharpu. Instead, specify the length of the data by using a bounded character
pointer host variable. A bounded character pointer host variable is a host variable
that is declared as a structure with the following elements:
A 4-byte field that contains the length of the storage area.
A pointer to the non-numeric dynamic storage area.
v You cannot use untyped pointers. For example, do not specify the following
declaration: void * untypedprt .
Examples of scalar pointer host variable declarations:
Table 49. Example declarations of scalar pointer host variables
Declaration Description
short *hvshortp;
hvshortp is a pointer host variable that
points to two bytes of storage.
double *hvdoubp;
hvdoubp is a pointer host variable that
points to eight bytes of storage.
char (*hvcharpn) [20];
hvcharpn is a pointer host variable that
points to a nul-terminated character array of
up to 20 bytes.
Example of a bounded character pointer host variable declaration: The following
example code declares a bounded character pointer host variable called hvbcharp
with two elements: len and data.
struct {
unsigned long len;
char * data;
} hvbcharp;
Examples of array pointer host variable declarations:
Table 50. Example declarations of array pointer host variables
Declaration Description
short * hvarrpl[6]
hvarrp1 is an array of 6 pointers that point to
two bytes of storage each.
double * hvarrp2[3]
hvarrp2 is an array of 3 pointers that point to
8 bytes of storage each.
struct {
unsigned long len;
char * data; }
hvbarrp3[5];
hvbarrp3 is an array of 5 bounded character
pointers.
Example of a structure array host variable declaration: The following example
code declares a table structure called tbl_struct.
Chapter 3. Including DB2 queries in an application program 211
struct tbl_struct
{
char colname[20];
small int colno;
small int coltype;
small int collen;
};
The following example code declares a pointer to the structure tbl_struct. Storage is
allocated dynamically for up to n rows.
struct tbl_struct *ptr_tbl_struct =
(struct tbl_struct *) malloc (sizeof (struct tbl_struct) * n);
Related tasks
Referencing pointer host variables in C and C++ programs on page 256
Setting the CCSID for host variables
All DB2 string data, other than binary data, has an encoding scheme and a coded
character set ID (CCSID) associated with it. You can associate an encoding scheme
and a CCSID with individual host variables. Any data in those host variable is
then associated with that encoding scheme and CCSID.
To set the CCSID for host variables:
Specify the DECLARE VARIABLE statement after the corresponding host variable
declaration and before your first reference to that host variable.
This statement associates an encoding scheme and a CCSID with individual host
variables. You can use this statement in static or dynamic SQL applications.
Restriction: You cannot use the DECLARE VARIABLE statement to control the
CCSID and encoding scheme of data that you retrieve or update by using an
SQLDA.
The DECLARE VARIABLE statement has the following effects on a host variable:
v When you use the host variable to update a table, the local subsystem or the
remote server assumes that the data in the host variable is encoded with the
CCSID and encoding scheme that the DECLARE VARIABLE statement assigns.
v When you retrieve data from a local or remote table into the host variable, the
retrieved data is converted to the CCSID and encoding scheme that are assigned
by the DECLARE VARIABLE statement.
Example
Suppose that you are writing a C program that runs on a DB2 for z/OS subsystem.
The subsystem has an EBCDIC application encoding scheme. The C program
retrieves data from the following columns of a local table that is defined with the
CCSID UNICODE option:
PARTNUM CHAR(10)
JPNNAME GRAPHIC(10)
ENGNAME VARCHAR(30)
Because the application encoding scheme for the subsystem is EBCDIC, the
retrieved data is EBCDIC. To make the retrieved data Unicode, use DECLARE
VARIABLE statements to specify that the data that is retrieved from these columns
is encoded in the default Unicode CCSIDs for the subsystem.
212 Application Programming and SQL Guide
Suppose that you want to retrieve the character data in Unicode CCSID 1208 and
the graphic data in Unicode CCSID 1200. Use the following DECLARE VARIABLE
statements:
EXEC SQL BEGIN DECLARE SECTION;
char hvpartnum[11];
EXEC SQL DECLARE :hvpartnum VARIABLE CCSID 1208;
sqldbchar hvjpnname[11];
EXEC SQL DECLARE :hvjpnname VARIABLE CCSID 1200;
struct {
short len;
char d[30];
} hvengname;
EXEC SQL DECLARE :hvengname VARIABLE CCSID 1208;
EXEC SQL END DECLARE SECTION;
Related reference
DECLARE VARIABLE (DB2 SQL Reference)
Controlling the CCSID for COBOL host variables
Setting the CCSID for COBOL host variables is slightly different than the process
for other host languages. In COBOL, several other settings affect the CCSID.
This task applies to programs that use IBM Enterprise COBOL for z/OS and the
DB2 coprocessor.
To control the CCSID for COBOL host variables:
Use one or more of the following items:
The NATIONAL data type
Use this data type to declare Unicode values in the UTF-16 format (CCSID
1200).
If you declare a host variable HV1 as USAGE NATIONAL, DB2 always
handles HV1 as if you had used the following DECLARE VARIABLE
statement:
DECLARE :HV1 VARIABLE CCSID 1200
The COBOL CODEPAGE compiler option
Use this option to specify the default EBCDIC CCSID of character data
items.
The SQLCCSID compiler option
Use this option to control whether the CODEPAGE compiler option
influences the processing of SQL host variables in your COBOL programs
(available in Enterprise COBOL V3R4 or later).
When you specify the SQLCCSID compiler option, the COBOL DB2
coprocessor uses the CCSID that is specified in the CODEPAGE compiler
option. All host variables of character data type, other than NATIONAL,
are specified with that CCSID unless they are explicitly overridden by a
DECLARE VARIABLE statement.
When you specify the NOSQLCCSID compiler option, the CCSID that is
specified in the CODEPAGE compiler option is used for processing only
COBOL statements within the COBOL program. That CCSID is not used
for the processing of host variables in SQL statements. DB2 uses the
CCSIDs that are specified through DB2 mechanisms and defaults as host
variable data value encodings.
Chapter 3. Including DB2 queries in an application program 213
The DECLARE VARIABLE statement.
This statement explicitly sets the CCSID for individual host variables.
Example
Assume that the COBOL SQLCCSID compiler option is specified and that the
COBOL CODEPAGE compiler option is specified as CODEPAGE(1141). The
following code shows how you can control the CCSID:
DATA DIVISION.
01 HV1 PIC N(10) USAGE NATIONAL.
01 HV2 PIC X(20) USAGE DISPLAY.
01 HV3 PIC X(30) USAGE DISPLAY.
...
EXEC SQL
DECLARE :HV3 VARIABLE CCSID 1047
END-EXEC.
...
PROCEDURE DIVISION.
...
EXEC SQL
SELECT C1, C2, C3 INTO :HV1, :HV2, :HV3 FROM T1
END-EXEC.
Each of the host variables have the following CCSIDs:
HV1 1200
HV2 1141
HV3 1047
Assume that the COBOL NOSQLCCSID compiler option is specified, the COBOL
CODEPAGE compiler option is specified as CODEPAGE(1141), and the DB2 default
single byte CCSID is set to 37. In this case, each of the host variables in this
example have the following CCSIDs:
HV1 1200
HV2 37
HV3 1047
Related reference
COBOL syntax for host variable declarations on page 161
Related information
IBM System z Enterprise Development Tools & Compilers information
center
Determining what caused an error when retrieving data into a
host variable
Errors that occur when DB2 passes data to host variables in an application are
usually caused by a problem in converting from one data type to another. These
errors do not affect the position of the cursor.
For example, suppose that you fetch an integer value of 32768 into a host variable
of type SMALLINT. The conversion might cause an error if you do not provide
sufficient conversion information to DB2.
The variable to which DB2 assigns the data is called the output host variable. If you
provide an indicator variable for the output host variable or if data type
214 Application Programming and SQL Guide
conversion is not required, DB2 returns a positive SQLCODE for the row in most
cases. In other cases where data conversion problems occur, DB2 returns a negative
SQLCODE for that row. Regardless of the SQLCODE for the row, no new values
are assigned to the host variable or to subsequent variables for that row. Any
values that are already assigned to variables remain assigned. Even when a
negative SQLCODE is returned for a row, statement processing continues and DB2
returns a positive SQLCODE for the statement (SQLSTATE 01668, SQLCODE
+354).
To determine what caused an error when retrieving data into a host variable:
1. When DB2 returns SQLCODE = +354, use the GET DIAGNOSTICS statement
with the NUMBER option to determine the number of errors and warnings.
Example: Suppose that no indicator variables are provided for the values that
are returned by the following statement:
FETCH FIRST ROWSET FROM C1 FOR 10 ROWS INTO :hva_col1, :hva_col2;
For each row with an error, DB2 records a negative SQLCODE and continues
processing until the 10 rows are fetched. When SQLCODE = +354 is returned
for the statement, you can use the GET DIAGNOSTICS statement to determine
which errors occurred for which rows. The following statement returns
num_rows = 10 and num_cond = 3:
GET DIAGNOSTICS :num_rows = ROW_COUNT, :num_cond = NUMBER;
2. To investigate the errors and warnings, use additional GET DIAGNOSTIC
statements with the CONDITION option.
Example: To investigate the three conditions that were reported in the example
in the previous step, use the following statements:
Table 51. GET DIAGNOSTIC statements to investigate conditions
Statement Output
GET DIAGNOSTICS CONDITION 3 :sqlstate
= RETURNED_SQLSTATE, :sqlcode =
DB2_RETURNED_SQLCODE, :row_num
= DB2_ROW_NUMBER;
sqlstate = 22003
sqlcode = -304
row_num = 5
GET DIAGNOSTICS CONDITION 2 :sqlstate
= RETURNED_SQLSTATE, :sqlcode =
DB2_RETURNED_SQLCODE, :row_num
= DB2_ROW_NUMBER;
sqlstate = 22003
sqlcode = -802
row_num = 7
GET DIAGNOSTICS CONDITION 1 :sqlstate
= RETURNED_SQLSTATE, :sqlcode =
DB2_RETURNED_SQLCODE, :row_num
= DB2_ROW_NUMBER;
sqlstate = 01668
sqlcode = +354
row_num = 0
This output shows that the fifth row has a data mapping error (-304) for
column 1 and that the seventh row has a data mapping error (-802) for column
2. These rows do not contain valid data, and they should not be used.
Related concepts
Indicator variables, arrays, and structures on page 204
Related reference
GET DIAGNOSTICS (DB2 SQL Reference)
+354 (DB2 Codes)
Chapter 3. Including DB2 queries in an application program 215
Compatibility of SQL and language data types
The data types of the host variables that are used in SQL statements must be
compatible with the data types of the columns with which you intend to use them.
When deciding the data types of host variables, consider the following rules and
recommendations:
v Numeric data types are compatible with each other:
Assembler: A SMALLINT, INTEGER, BIGINT, DECIMAL, or FLOAT column is
compatible with a numeric assembler host variable.
C/C++: A SMALLINT, INTEGER, BIGINT, DECIMAL, or FLOAT column is
compatible with any C host variable that is defined as type short int, long int,
long long, long long int, sqlint64, decimal, float, or double.
Fortran: An INTEGER column is compatible with any Fortran host variable that
is defined as INTEGER*2, INTEGER*4, REAL, REAL*4, REAL*8, or DOUBLE
PRECISION.
PL/I: A SMALLINT, INTEGER, BIGINT, DECIMAL, or FLOAT column is
compatible with a PL/I host variable of BIN FIXED(15), BIN FIXED(31),
DECIMAL(s,p), or BIN FLOAT(n), where n is from 1 to 53, or DEC FLOAT(m)
where m is from 1 to 16.
v Character data types are compatible with each other:
Assembler: A CHAR, VARCHAR, or CLOB column is compatible with a
fixed-length or varying-length assembler character host variable.
C/C++: A CHAR, VARCHAR, or CLOB column is compatible with a
single-character, NUL-terminated, or VARCHAR structured form of a C
character host variable.
COBOL: A CHAR, VARCHAR, or CLOB column is compatible with a
fixed-length or varying-length COBOL character host variable.
Fortran: A CHAR, VARCHAR, or CLOB column is compatible with Fortran
character host variable.
PL/I: A CHAR, VARCHAR, or CLOB column is compatible with a fixed-length
or varying-length PL/I character host variable.
v Character data types are partially compatible with CLOB locators. You can
perform the following assignments:
Assign a value in a CLOB locator to a CHAR or VARCHAR column
Use a SELECT INTO statement to assign a CHAR or VARCHAR column to a
CLOB locator host variable.
Assign a CHAR or VARCHAR output parameter from a user-defined function
or stored procedure to a CLOB locator host variable.
Use a SET assignment statement to assign a CHAR or VARCHAR transition
variable to a CLOB locator host variable.
Use a VALUES INTO statement to assign a CHAR or VARCHAR function
parameter to a CLOB locator host variable.
However, you cannot use a FETCH statement to assign a value in a CHAR or
VARCHAR column to a CLOB locator host variable.
v Graphic data types are compatible with each other:
Assembler: A GRAPHIC, VARGRAPHIC, or DBCLOB column is compatible
with a fixed-length or varying-length assembler graphic character host variable.
216 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
C/C++: A GRAPHIC, VARGRAPHIC, or DBCLOB column is compatible with a
single character, NUL-terminated, or VARGRAPHIC structured form of a C
graphic host variable.
COBOL: A GRAPHIC, VARGRAPHIC, or DBCLOB column is compatible with a
fixed-length or varying-length COBOL graphic string host variable.
PL/I: A GRAPHIC, VARGRAPHIC, or DBCLOB column is compatible with a
fixed-length or varying-length PL/I graphic character host variable.
v Graphic data types are partially compatible with DBCLOB locators. You can
perform the following assignments:
Assign a value in a DBCLOB locator to a GRAPHIC or VARGRAPHIC
column
Use a SELECT INTO statement to assign a GRAPHIC or VARGRAPHIC
column to a DBCLOB locator host variable.
Assign a GRAPHIC or VARGRAPHIC output parameter from a user-defined
function or stored procedure to a DBCLOB locator host variable.
Use a SET assignment statement to assign a GRAPHIC or VARGRAPHIC
transition variable to a DBCLOB locator host variable.
Use a VALUES INTO statement to assign a GRAPHIC or VARGRAPHIC
function parameter to a DBCLOB locator host variable.
However, you cannot use a FETCH statement to assign a value in a GRAPHIC
or VARGRAPHIC column to a DBCLOB locator host variable.
v Binary data types are compatible with each other.
v Binary data types are partially compatible with BLOB locators. You can perform
the following assignments:
Assign a value in a BLOB locator to a BINARY or VARBINARY column.
Use a SELECT INTO statement to assign a BINARY or VARBINARY column
to a BLOB locator host variable.
Assign a BINARY or VARBINARY output parameter from a user-defined
function or stored procedure to a BLOB locator host variable.
Use a SET assignment statement to assign a BINARY or VARBINARY
transition variable to a BLOB locator host variable.
Use a VALUES INTO statement to assign a BINARY or VARBINARY function
parameter to a BLOB locator host variable.
However, you cannot use a FETCH statement to assign a value in a BINARY or
VARBINARY column to a BLOB locator host variable.
v Fortran: A BINARY, VARBINARY, or BLOB column or BLOB locator is
compatible only with a BLOB host variable.
v C: For varying-length BIT data, use BINARY. Some C string manipulation
functions process NUL-terminated strings and other functions process strings
that are not NUL-terminated. The C string manipulation functions that process
NUL-terminated strings cannot handle bit data because these functions might
misinterpret a NUL character to be a NUL-terminator.
v Datetime data types are compatible with character host variables.
Assembler: A DATE, TIME, or TIMESTAMP column is compatible with a
fixed-length or varying-length assembler character host variable.
C/C++: A DATE, TIME, or TIMESTAMP column is compatible with a
single-character, NUL-terminated, or VARCHAR structured form of a C
character host variable.
COBOL: A DATE, TIME, or TIMESTAMP column is compatible with a
fixed-length or varying length COBOL character host variable.
Chapter 3. Including DB2 queries in an application program 217
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Fortran: A DATE, TIME, or TIMESTAMP column is compatible with a Fortran
character host variable.
PL/I: A DATE, TIME, or TIMESTAMP column is compatible with a fixed-length
or varying-length PL/I character host variable.
v The ROWID column is compatible only with a ROWID host variable.
v A host variable is compatible with a distinct type if the host variable type is
compatible with the source type of the distinct type.
v XML columns are compatible with the XML host variable types, character types,
and binary string types.
Recommendation: Use the XML host variable types for data from XML
columns.
v Assembler:You can assign LOB data to a file reference variable (BLOB_FILE,
CLOB_FILE, and DBCLOB_FILE).
When necessary, DB2 automatically converts a fixed-length string to a
varying-length string, or a varying-length string to a fixed-length string.
Related concepts
Host variable data types for XML data in embedded SQL applications on
page 330
Distinct types on page 446
Equivalent SQL and assembler data types
When you declare host variables in your assembler programs, the precompiler uses
equivalent SQL data types. When you retrieve data of a particular SQL data type
into a host variable, you need to ensure that the host variable is of an equivalent
data type.
The following table describes the SQL data type and the base SQLTYPE and
SQLLEN values that the precompiler uses for host variables in SQL statements.
Table 52. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in
assembler programs
Assembler host variable data type
SQLTYPE of host
variable
1
SQLLEN of
host variable SQL data type
DS HL2
500 2
SMALLINT
DS FL4
496 4
INTEGER
DS P'value'
DS PLn'value' or
DS PLn
1<=n<=16
484 p in byte 1, s in
byte 2
DECIMAL(p,s)
short decimal FLOAT:
SDFP DC ED
SDFP DC EDL4
SDFP DC EDL4'11.11'
996 4
DECFLOAT
long decimal FLOAT:
LDFP DC DD
LDFP DC DDL8
LDFP DC DDL8'22.22'
996 8
DECFLOAT
218 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
||
|
Table 52. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in
assembler programs (continued)
Assembler host variable data type
SQLTYPE of host
variable
1
SQLLEN of
host variable SQL data type
extended decimal FLOAT:
EDFP DC LD
EDFP DC LDL16
EDFP DC LDL16'33.33'
996 16
DECFLOAT
DS EL4
DS EHL4
DS EBL4
480 4
REAL or FLOAT (n)
1<=n<=21
DS DL8
DS DHL8
DS DBL8
480 8
DOUBLE PRECISION,
or FLOAT (n)
22<=n<=53
DS FDL8
DS FD
492 8
BIGINT
SQL TYPE IS BINARY(n)
1<=n<=255
912 n
BINARY(n)
SQL TYPE IS VARBINARY(n) or
SQL TYPE IS BINARY(n) VARYING
1<=n<=32704
908 n
VARBINARY(n)
DS CLn
1<=n<=255
452 n
CHAR(n)
DS HL2,CLn
1<=n<=255
448 n
VARCHAR(n)
DS HL2,CLn
n>255
456 n
VARCHAR(n)
DS GLm
2<=m<=254
2
468 n
GRAPHIC(n)
3
DS HL2,GLm
2<=m<=254
2
464 n
VARGRAPHIC(n)
3
DS HL2,GLm
m>254
2
472 n
VARGRAPHIC(n)
3
DS FL4
972 4
Result set locator
4
SQL TYPE IS
TABLE LIKE
table-name
AS LOCATOR
976 4
Table locator
4
SQL TYPE IS
BLOB_LOCATOR
960 4
BLOB locator
4
SQL TYPE IS
CLOB_LOCATOR
964 4
CLOB locator
4
Chapter 3. Including DB2 queries in an application program 219
|
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
|
||
|
Table 52. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in
assembler programs (continued)
Assembler host variable data type
SQLTYPE of host
variable
1
SQLLEN of
host variable SQL data type
SQL TYPE IS
DBCLOB_LOCATOR
968 4
DBCLOB locator
4
SQL TYPE IS
BLOB(n)
1n2147483647
404 n
BLOB(n)
SQL TYPE IS
CLOB(n)
1n2147483647
408 n
CLOB(n)
SQL TYPE IS
DBCLOB(n)
1n1073741823
412 n
DBCLOB(n)
3
SQL TYPE IS XML AS BLOB(n)
404 0
XML
SQL TYPE IS XML AS CLOB(n)
408 0
XML
SQL TYPE IS XML AS DBCLOB(n)
412 0
XML
SQL TYPE IS BLOB_FILE
916/917 267
BLOB file reference
4
SQL TYPE IS CLOB_FILE
920/921 267
CLOB file reference
4
SQL TYPE IS DBCLOB_FILE
924/925 267
DBCLOB file reference
4
SQL TYPE IS XML AS BLOB_FILE
916/917 267
XML BLOB file reference
4
SQL TYPE IS XML AS CLOB_FILE
920/921 267
XML CLOB file reference
4
SQL TYPE IS XML AS DBCLOB_FILE
924/925 267
XML DBCLOB file reference
4
SQL TYPE IS ROWID
904 40
ROWID
Notes:
1. If a host variable includes an indicator variable, the SQLTYPE value is the base SQLTYPE value plus 1.
2. m is the number of bytes.
3. n is the number of double-byte characters.
4. This data type cannot be used as a column type.
The following table shows equivalent assembler host variables for each SQL data
type. Use this table to determine the assembler data type for host variables that
you define to receive output from the database. For example, if you retrieve
TIMESTAMP data, you can define variable DS CLn.
This table shows direct conversions between SQL data types and assembler data
types. However, a number of SQL data types are compatible. When you do
assignments or comparisons of data that have compatible data types, DB2 converts
those compatible data types.
Table 53. Assembler host variable equivalents that you can use when retrieving data of a
particular SQL data type
SQL data type
Assembler host variable
equivalent Notes
SMALLINT DS HL2
220 Application Programming and SQL Guide
||
||
||
|
||
|
|
||
|
|
||
|
Table 53. Assembler host variable equivalents that you can use when retrieving data of a
particular SQL data type (continued)
SQL data type
Assembler host variable
equivalent Notes
INTEGER DS F
BIGINT DS FD OR DS FDL8 DS FDL8 requires High Level Assembler
(HLASM), Release 4 or later.
DECIMAL(p,s) or
NUMERIC(p,s)
DS Pvalue DS PLnvalue
DS PLn
p is precision; s is scale. 1<=p<=31 and
0<=s<=p. 1<=n<=16. value is a literal value
that includes a decimal point. You must
use Ln, value, or both. Using only value is
recommended.
Precision: If you use Ln, it is 2n-1;
otherwise, it is the number of digits in
value. Scale: If you use value, it is the
number of digits to the right of the
decimal point; otherwise, it is 0.
For efficient use of indexes: Use value. If
p is even, do not use Ln and be sure the
precision of value is p and the scale of
value is s. If p is odd, you can use Ln
(although it is not advised), but you must
choose n so that 2n-1=p, and value so that
the scale is s. Include a decimal point in
value, even when the scale of value is 0.
REAL or FLOAT(n) DS EL4 DS EHL4 DS
EBL4
1
1<=n<=21
DOUBLE
PRECISION,
DOUBLE, or
FLOAT(n)
DS DL8 DS DHL8 DS
DBL8
1
22<=n<=53
DECFLOAT DC EDL4 DC DDL8 DC
LDL16
CHAR(n) DS CLn 1<=n<=255
VARCHAR(n) DS HL2,CLn
GRAPHIC(n) DS GLm m is expressed in bytes. n is the number
of double-byte characters. 1<=n<=127
VARGRAPHIC(n) DS HL2,GLx DS
HL2m,GLx<value>
x and m are expressed in bytes. n is the
number of double-byte characters. < and
> represent shift-out and shift-in
characters.
BINARY(n) SQL TYPE IS BINARY(n) 1<=n<=255
VARBINARY(n) SQL TYPE IS
VARBINARY(n) or SQL
TYPE IS BINARY(n)
VARYING
1<=n<=32704
DATE DS CLn If you are using a date exit routine, n is
determined by that routine; otherwise, n
must be at least 10.
Chapter 3. Including DB2 queries in an application program 221
|||
|
||
|
|
|||
||
|
|
|
|
Table 53. Assembler host variable equivalents that you can use when retrieving data of a
particular SQL data type (continued)
SQL data type
Assembler host variable
equivalent Notes
TIME DS CLn If you are using a time exit routine, n is
determined by that routine. Otherwise, n
must be at least 6; to include seconds, n
must be at least 8.
TIMESTAMP DS CLn n must be at least 19. To include
microseconds, n must be 26; if n is less
than 26, truncation occurs on the
microseconds part.
Result set locator DS F Use this data type only to receive result
sets. Do not use this data type as a
column type.
Table locator SQL TYPE IS TABLE
LIKE table-name AS
LOCATOR
Use this data type only in a user-defined
function or stored procedure to receive
rows of a transition table. Do not use this
data type as a column type.
BLOB locator SQL TYPE IS
BLOB_LOCATOR
Use this data type only to manipulate
data in BLOB columns. Do not use this
data type as a column type.
CLOB locator SQL TYPE IS
CLOB_LOCATOR
Use this data type only to manipulate
data in CLOB columns. Do not use this
data type as a column type.
DBCLOB locator SQL TYPE IS
DBCLOB_LOCATOR
Use this data type only to manipulate
data in DBCLOB columns. Do not use this
data type as a column type.
BLOB(n) SQL TYPE IS BLOB(n) 1n2147483647
CLOB(n) SQL TYPE IS CLOB(n) 1n2147483647
DBCLOB(n) SQL TYPE IS DBCLOB(n) n is the number of double-byte characters.
1n1073741823
XML SQL TYPE IS XML AS
BLOB(n)
1n2147483647
XML SQL TYPE IS XML AS
CLOB(n)
1n2147483647
XML SQL TYPE IS XML AS
DBCLOB(n)
n is the number of double-byte characters.
1n1073741823
BLOB file reference SQL TYPE IS BLOB_FILE Use this data type only to manipulate
data in BLOB columns. Do not use this
data type as a column type.
CLOB file reference SQL TYPE IS CLOB_FILE Use this data type only to manipulate
data in CLOB columns. Do not use this
data type as a column type.
DBCLOB file
reference
SQL TYPE IS
DBCLOB_FILE
Use this data type only to manipulate
data in DBCLOB columns. Do not use this
data type as a column type.
XML BLOB file
reference
SQL TYPE IS XML AS
BLOB_FILE
Use this data type only to manipulate
XML data as BLOB files. Do not use this
data type as a column type.
222 Application Programming and SQL Guide
||
|
|
||
|
|
||
|
|
|
|||
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Table 53. Assembler host variable equivalents that you can use when retrieving data of a
particular SQL data type (continued)
SQL data type
Assembler host variable
equivalent Notes
XML CLOB file
reference
SQL TYPE IS XML AS
CLOB_FILE
Use this data type only to manipulate
XML data as CLOB files. Do not use this
data type as a column type.
XML DBCLOB file
reference
SQL TYPE IS XML AS
DBCLOB_FILE
Use this data type only to manipulate
XML data as DBCLOB files. Do not use
this data type as a column type.
ROWID SQL TYPE IS ROWID
Notes:
1. Although stored procedures and user-defined functions can use IEEE floating-point host
variables, you cannot declare a user-defined function or stored procedure parameter as
IEEE.
Related concepts
LOB host variable, LOB locator, and LOB file reference variable declarations
on page 671
Host variable data types for XML data in embedded SQL applications on
page 330
Equivalent SQL and C data types
When you declare host variables in your C programs, the precompiler uses
equivalent SQL data types. When you retrieve data of a particular SQL data type
into a host variable, you need to ensure that the host variable is of an equivalent
data type.
The following table describes the SQL data type and the base SQLTYPE and
SQLLEN values that the precompiler uses for host variables in SQL statements.
Table 54. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses
for host variables in C programs
C host variable data type
SQLTYPE of host
variable
1
SQLLEN of host
variable SQL data type
short int 500 2 SMALLINT
long int 496 4 INTEGER
long long
long long int
sqlint64
492 8 BIGINT
5
decimal(p,s)
2
484 p in byte 1, s in
byte 2
DECIMAL(p,s)
2
float 480 4 FLOAT (single
precision)
double 480 8 FLOAT (double
precision)
v
SQL TYPE IS
BINARY(n),
1<=n<=255
912 n BINARY(n)
Chapter 3. Including DB2 queries in an application program 223
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||
|
|
|
|
|
|||
Table 54. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses
for host variables in C programs (continued)
C host variable data type
SQLTYPE of host
variable
1
SQLLEN of host
variable SQL data type
v
SQL TYPE IS
VARBINARY(n),
1<=n<=32704
908 n VARBINARY(n)
Single-character form 452 1 CHAR(1)
NUL-terminated
character form
460 n VARCHAR (n-1)
VARCHAR structured
form 1<=n<=255
448 n VARCHAR(n)
VARCHAR structured
form
n>255
456 n VARCHAR(n)
Single-graphic form 468 1 GRAPHIC(1)
NUL-terminated
graphic form
400 n VARGRAPHIC (n-1)
VARGRAPHIC
structured form
1<=n<128
464 n VARGRAPHIC(n)
VARGRAPHIC
structured form
n>127
472 n VARGRAPHIC(n)
v
SQL TYPE IS
RESULT_SET
_LOCATOR
972 4 Result set locator
3
SQL TYPE IS
TABLE LIKE
table-name
AS LOCATOR
976 4 Table locator
3
SQL TYPE IS
BLOB_LOCATOR
960 4 BLOB locator
3
SQL TYPE IS
CLOB_LOCATOR
964 4 CLOB locator
3
SQL TYPE IS
DBCLOB_LOCATOR
968 4 DBCLOB locator
3
SQL TYPE IS
BLOB(n)
1n2147483647
404 n BLOB(n)
SQL TYPE IS
CLOB(n)
1n2147483647
408 n CLOB(n)
SQL TYPE IS
DBCLOB(n)
1n1073741823
412 n DBCLOB(n)
4
SQL TYPE IS XML AS
BLOB(n)
404 0 XML
224 Application Programming and SQL Guide
|
|
|
|
|
|||
|
|
|||
Table 54. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses
for host variables in C programs (continued)
C host variable data type
SQLTYPE of host
variable
1
SQLLEN of host
variable SQL data type
SQL TYPE IS XML AS
CLOB(n)
408 0 XML
SQL TYPE IS XML AS
DBCLOB(n)
412 0 XML
SQL TYPE IS BLOB_FILE 916/917 267 BLOB file reference
3
SQL TYPE IS CLOB_FILE 920/921 267 CLOB file reference
3
SQL TYPE IS
DBCLOB_FILE
924/925 267 DBCLOB file reference
3
SQL TYPE IS XML AS
BLOB_FILE
916/917 267 XML BLOB file
reference
3
SQL TYPE IS XML AS
CLOB_FILE
920/921 267 XML CLOB file
reference
3
SQL TYPE IS XML AS
DBCLOB_FILE
924/925 267 XML DBCLOB file
reference
3
SQL TYPE IS ROWID 904 40 ROWID
Notes:
1. If a host variable includes an indicator variable, the SQLTYPE value is the base
SQLTYPE value plus 1.
2. p is the precision; in SQL terminology, this the total number of digits. In C, this is called
the size.
s is the scale; in SQL terminology, this is the number of digits to the right of the decimal
point. In C, this is called the precision.
C++ does not support the decimal data type.
3. Do not use this data type as a column type.
4. n is the number of double-byte characters.
5. No exact equivalent. Use DECIMAL(19,0).
6. Starting in Version 9, the C data type long long no longer maps to the SQL data type
DEC (19,0). Instead, the C data type long long maps to the SQL data type BIGINT. This
new mapping applies if the application is precompiled again.
The following table shows equivalent C host variables for each SQL data type. Use
this table to determine the C data type for host variables that you define to receive
output from the database. For example, if you retrieve TIMESTAMP data, you can
define a variable of NUL-terminated character form or VARCHAR structured form
This table shows direct conversions between SQL data types and C data types.
However, a number of SQL data types are compatible. When you do assignments
or comparisons of data that have compatible data types, DB2 converts those
compatible data types.
Table 55. C host variable equivalents that you can use when retrieving data of a particular SQL data type
SQL data type C host variable equivalent Notes
SMALLINT short int
INTEGER long int
Chapter 3. Including DB2 queries in an application program 225
|
|
|||
|
|
|||
||||
||||
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|
Table 55. C host variable equivalents that you can use when retrieving data of a particular SQL data type (continued)
SQL data type C host variable equivalent Notes
DECIMAL(p,s) or
NUMERIC(p,s)
decimal You can use the double data type if your
C compiler does not have a decimal data
type; however, double is not an exact
equivalent.
REAL or FLOAT(n) float 1<=n<=21
DOUBLE PRECISION or
FLOAT(n)
double 22<=n<=53
DECFLOAT No equivalent
BIGINT long long, long long int, and sqlint64
BINARY(n) SQL TYPE IS BINARY(n) 1<=n<=255
If data can contain character NULs (\0),
certain C and C++ library functions might
not handle the data correctly. Ensure that
your application handles the data
properly.
VARBINARY(n) SQL TYPE IS VARBINARY(n) 1<=n<=32 704
CHAR(1) single-character form
CHAR(n) no exact equivalent If n>1, use NUL-terminated character form
VARCHAR(n) NUL-terminated character form If data can contain character NULs (\0),
use VARCHAR structured form. Allow at
least n+1 to accommodate the
NUL-terminator.
VARCHAR structured form
GRAPHIC(1) single-graphic form
GRAPHIC(n) no exact equivalent If n>1, use NUL-terminated graphic form.
n is the number of double-byte characters.
VARGRAPHIC(n) NUL-terminated graphic form If data can contain graphic NUL values
(\0\0), use VARGRAPHIC structured
form. Allow at least n+1 to accommodate
the NUL-terminator. n is the number of
double-byte characters.
VARGRAPHIC structured form n is the number of double-byte characters.
DATE NUL-terminated character form If you are using a date exit routine, that
routine determines the length. Otherwise,
allow at least 11 characters to
accommodate the NUL-terminator.
VARCHAR structured form If you are using a date exit routine, that
routine determines the length. Otherwise,
allow at least 10 characters.
226 Application Programming and SQL Guide
|||
|||
|||
|
|
|
|
|
|||
Table 55. C host variable equivalents that you can use when retrieving data of a particular SQL data type (continued)
SQL data type C host variable equivalent Notes
TIME NUL-terminated character form If you are using a time exit routine, the
length is determined by that routine.
Otherwise, the length must be at least 7;
to include seconds, the length must be at
least 9 to accommodate the
NUL-terminator.
VARCHAR structured form If you are using a time exit routine, the
length is determined by that routine.
Otherwise, the length must be at least 6;
to include seconds, the length must be at
least 8.
TIMESTAMP NUL-terminated character form The length must be at least 20. To include
microseconds, the length must be 27. If the
length is less than 27, truncation occurs on
the microseconds part.
VARCHAR structured form The length must be at least 19. To include
microseconds, the length must be 26. If the
length is less than 26, truncation occurs on
the microseconds part.
Result set locator SQL TYPE IS RESULT_SET_LOCATOR Use this data type only for receiving result
sets. Do not use this data type as a
column type.
Table locator SQL TYPE IS TABLE LIKE table-name AS
LOCATOR
Use this data type only in a user-defined
function or stored procedure to receive
rows of a transition table. Do not use this
data type as a column type.
BLOB locator SQL TYPE IS BLOB_LOCATOR Use this data type only to manipulate data
in BLOB columns. Do not use this data
type as a column type.
CLOB locator SQL TYPE IS CLOB_LOCATOR Use this data type only to manipulate data
in CLOB columns. Do not use this data
type as a column type.
DBCLOB locator SQL TYPE IS DBCLOB_LOCATOR Use this data type only to manipulate data
in DBCLOB columns. Do not use this data
type as a column type.
BLOB(n) SQL TYPE IS BLOB(n) 1n2147483647
CLOB(n) SQL TYPE IS CLOB(n) 1n2147483647
DBCLOB(n) SQL TYPE IS DBCLOB(n) n is the number of double-byte characters.
1n1073741823
XML SQL TYPE IS XML AS BLOB(n) 1n2147483647
XML SQL TYPE IS XML AS CLOB(n) 1n2147483647
XML SQL TYPE IS XML AS DBCLOB(n) n is the number of double-byte characters.
1n1073741823
BLOB file reference SQL TYPE IS BLOB_FILE Use this data type only to manipulate data
in BLOB columns. Do not use this data
type as a column type.
CLOB file reference SQL TYPE IS CLOB_FILE Use this data type only to manipulate data
in CLOB columns. Do not use this data
type as a column type.
Chapter 3. Including DB2 queries in an application program 227
|||
|||
|||
|
|||
|
|
|||
|
|
Table 55. C host variable equivalents that you can use when retrieving data of a particular SQL data type (continued)
SQL data type C host variable equivalent Notes
DBCLOB file reference SQL TYPE IS DBCLOB_FILE Use this data type only to manipulate data
in DBCLOB columns. Do not use this data
type as a column type.
XML BLOB file reference SQL TYPE IS XML AS BLOB_FILE Use this data type only to manipulate
XML data as BLOB files. Do not use this
data type as a column type.
XML CLOB file reference SQL TYPE IS XML AS CLOB_FILE Use this data type only to manipulate
XML data as CLOB files. Do not use this
data type as a column type.
XML DBCLOB file reference SQL TYPE IS XML AS DBCLOB_FILE Use this data type only to manipulate
XML data as DBCLOB files. Do not use
this data type as a column type.
ROWID SQL TYPE IS ROWID
Related concepts
LOB host variable, LOB locator, and LOB file reference variable declarations
on page 671
Host variable data types for XML data in embedded SQL applications on
page 330
Equivalent SQL and COBOL data types
When you declare host variables in your COBOL programs, the precompiler uses
equivalent SQL data types. When you retrieve data of a particular SQL data type
into a host variable, you need to ensure that the host variable is of an equivalent
data type.
The following table describes the SQL data type and the base SQLTYPE and
SQLLEN values that the precompiler uses for host variables in SQL statements.
Table 56. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in
COBOL programs
COBOL host variable data type
SQLTYPE of host
variable
1
SQLLEN of host variable SQL data type
COMP-1 480 4 REAL or FLOAT(n) 1<=n<=21
COMP-2 480 8 DOUBLE PRECISION, or
FLOAT(n) 22<=n<=53
S9(i)V9(d) COMP-3 or S9(i)V9(d)
PACKED-DECIMAL
484 i+d in byte 1, d in byte 2 DECIMAL(i+d,d) or
NUMERIC(i+d,d)
S9(i)V9(d) DISPLAY SIGN
LEADING SEPARATE
504 i+d in byte 1, d in byte 2 No exact equivalent. Use
DECIMAL(i+d,d) or
NUMERIC(i+d,d)
S9(i)V9(d) NATIONAL SIGN
LEADING SEPARATE
504 i+d in byte 1, d in byte 2 No exact equivalent. Use
DECIMAL(i+d,d) or
NUMERIC(i+d,d)
S9(4) COMP-4, S9(4) COMP-5,
S9(4) COMP, or S9(4) BINARY
500 2 SMALLINT
S9(9) COMP-4, S9(9) COMP-5,
S9(9) COMP, or S9(9) BINARY
496 4 INTEGER
228 Application Programming and SQL Guide
|||
|
|
|||
|
|
|||
|
|
|||
|
|
Table 56. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in
COBOL programs (continued)
COBOL host variable data type
SQLTYPE of host
variable
1
SQLLEN of host variable SQL data type
S9(18) COMP-4, S9(18) COMP-5,
S9(18) COMP, or S9(18) BINARY
492 8 BIGINT
Fixed-length character data 452 n CHAR(n)
Varying-length character data
1<=n<=255
448 n VARCHAR(n)
Varying-length character data
m>255
456 m VARCHAR(m)
Fixed-length graphic data 468 m GRAPHIC(m)
Varying-length graphic data
1<=m<=127
464 m VARGRAPHIC(m)
Varying-length graphic data
m>127
472 m VARGRAPHIC(m)
SQL TYPE is BINARY(n),
1<=n<=255
912 n BINARY(n)
SQL TYPE is VARBINARY(n),
1<=n<=32 704
908 n VARBINARY(n)
SQL TYPE IS
RESULT-SET-LOCATOR
972 4 Result set locator
2
SQL TYPE IS TABLE LIKE
table-name AS LOCATOR
976 4 Table locator
2
SQL TYPE IS BLOB-LOCATOR 960 4 BLOB locator
2
SQL TYPE IS CLOB-LOCATOR 964 4 CLOB locator
2
SQL TYPE IS
DBCLOB-LOCATOR
968 4 DBCLOB locator
2
USAGE IS SQL TYPE IS
BLOB(n) 1n2147483647
404 n BLOB(n)
USAGE IS SQL TYPE IS
CLOB(n) 1n2147483647
408 n CLOB(n)
USAGE IS SQL TYPE IS
DBCLOB(m) 1m1073741823
3
412 n DBCLOB(m)
3
SQL TYPE IS XML AS BLOB(n) 404 0 XML
SQL TYPE IS XML AS CLOB(n) 408 0 XML
SQL TYPE IS XML AS
DBCLOB(n)
412 0 XML
SQL TYPE IS BLOB-FILE 916/917 267 BLOB file reference
2
SQL TYPE IS CLOB-FILE 920/921 267 CLOB file reference
2
SQL TYPE IS DBCLOB-FILE 924/925 267 DBCLOB file reference
2
SQL TYPE IS XML AS
BLOB-FILE
916/917 267 XML BLOB file reference
2
SQL TYPE IS XML AS
CLOB-FILE
920/921 267 XML CLOB file reference
2
SQL TYPE IS XML AS
DBCLOB-FILE
924/925 267 XML DBCLOB file reference
2
SQL TYPE IS ROWID 904 40 ROWID
Chapter 3. Including DB2 queries in an application program 229
|
|
|||
|
|
|||
|
|
|||
||||
||||
|
|
|||
||||
||||
||||
|
|
|||
|
|
|||
|
|
|||
Table 56. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in
COBOL programs (continued)
COBOL host variable data type
SQLTYPE of host
variable
1
SQLLEN of host variable SQL data type
Notes:
1. If a host variable includes an indicator variable, the SQLTYPE value is the base SQLTYPE value plus 1.
2. Do not use this data type as a column type.
3. m is the number of double-byte characters.
The following table shows equivalent COBOL host variables for each SQL data
type. Use this table to determine the COBOL data type for host variables that you
define to receive output from the database. For example, if you retrieve
TIMESTAMP data, you can define a fixed-length character string variable of length
n
This table shows direct conversions between SQL data types and COBOL data
types. However, a number of SQL data types are compatible. When you do
assignments or comparisons of data that have compatible data types, DB2 converts
those compatible data types.
Table 57. COBOL host variable equivalents that you can use when retrieving data of a particular SQL data type
SQL data type COBOL host variable equivalent Notes
SMALLINT
S9(4) COMP-4,
S9(4) COMP-5,
S9(4) COMP,
or S9(4) BINARY
INTEGER
S9(9) COMP-4,
S9(9) COMP-5,
S9(9) COMP,
or S9(9) BINARY
DECIMAL(p,s) or
NUMERIC(p,s)
S9(p-s)V9(s) COMP-3 or
S9(p-s)V9(s)
PACKED-DECIMAL
DISPLAY SIGN
LEADING SEPARATE
NATIONAL SIGN
LEADING SEPARATE
p is precision; s is scale. 0<=s<=p<=31. If
s=0, use S9(p)V or S9(p). If s=p, use SV9(s).
If the COBOL compiler does not support
31digit decimal numbers, no exact
equivalent exists. Use COMP-2.
REAL or FLOAT (n)
COMP-1
1<=n<=21
DOUBLE PRECISION,
DOUBLE or FLOAT (n)
COMP-2
22<=n<=53
BIGINT S9(18) COMP-4, S9(18) COMP-5, S9(18)
COMP, or S9(18) BINARY
CHAR(n) Fixed-length character string. For example,
01 VAR-NAME PIC X(n).
1<=n<=255
VARCHAR(n) Varying-length character string. For
example,
01 VAR-NAME.
49 VAR-LEN PIC S9(4)
USAGE BINARY.
49 VAR-TEXT PIC X(n).
The inner variables must have a level of
49.
230 Application Programming and SQL Guide
||
|
|
Table 57. COBOL host variable equivalents that you can use when retrieving data of a particular SQL data
type (continued)
SQL data type COBOL host variable equivalent Notes
GRAPHIC(n) Fixed-length graphic string. For example,
01 VAR-NAME PIC G(n)
USAGE IS DISPLAY-1.
n refers to the number of double-byte
characters, not to the number of bytes.
1<=n<=127
VARGRAPHIC(n) Varying-length graphic string. For
example,
01 VAR-NAME.
49 VAR-LEN PIC S9(4)
USAGE BINARY.
49 VAR-TEXT PIC G(n)
USAGE IS DISPLAY-1.
n refers to the number of double-byte
characters, not to the number of bytes.
The inner variables must have a level of
49.
BINARY(n) SQL TYPE IS BINARY(n) 1<=n<=255
VARBINARY(n) SQL TYPE IS VARBINARY(n) 1<=n<=32 704
DATE Fixed-length character string of length n.
For example,
01 VAR-NAME PIC X(n).
If you are using a date exit routine, n is
determined by that routine. Otherwise, n
must be at least 10.
TIME Fixed-length character string of length n.
For example,
01 VAR-NAME PIC X(n).
If you are using a time exit routine, n is
determined by that routine. Otherwise, n
must be at least 6; to include seconds, n
must be at least 8.
TIMESTAMP Fixed-length character string of length n.
For example,
01 VAR-NAME PIC X(n).
n must be at least 19. To include
microseconds, n must be 26; if n is less
than 26, truncation occurs on the
microseconds part.
Result set locator
SQL TYPE IS
RESULT-SET-LOCATOR
Use this data type only for receiving result
sets. Do not use this data type as a
column type.
Table locator
SQL TYPE IS
TABLE LIKE
table-name
AS LOCATOR
Use this data type only in a user-defined
function or stored procedure to receive
rows of a transition table. Do not use this
data type as a column type.
BLOB locator
USAGE IS SQL TYPE IS
BLOB-LOCATOR
Use this data type only to manipulate data
in BLOB columns. Do not use this data
type as a column type.
CLOB locator
USAGE IS SQL TYPE IS
CLOB-LOCATOR
Use this data type only to manipulate data
in CLOB columns. Do not use this data
type as a column type.
DBCLOB locator
USAGE IS SQL TYPE IS
DBCLOB-LOCATOR
Use this data type only to manipulate data
in DBCLOB columns. Do not use this data
type as a column type.
BLOB(n)
USAGE IS SQL TYPE IS
BLOB(n)
1n2147483647
CLOB(n)
USAGE IS SQL TYPE IS
CLOB(n)
1n2147483647
DBCLOB(n)
USAGE IS SQL TYPE IS
DBCLOB(n)
n is the number of double-byte characters.
1n1073741823
XML SQL TYPE IS XML AS BLOB(n) 1n2147483647
XML SQL TYPE IS XML AS CLOB(n) 1n2147483647
Chapter 3. Including DB2 queries in an application program 231
|||
|||
|||
|||
Table 57. COBOL host variable equivalents that you can use when retrieving data of a particular SQL data
type (continued)
SQL data type COBOL host variable equivalent Notes
XML SQL TYPE IS XML AS DBCLOB(n) n is the number of double-byte characters.
1n1073741823
BLOB file reference
USAGE IS SQL TYPE IS
BLOB-FILE
Use this data type only to manipulate data
in BLOB columns. Do not use this data
type as a column type.
CLOB file reference
USAGE IS SQL TYPE IS
CLOB-FILE
Use this data type only to manipulate data
in CLOB columns. Do not use this data
type as a column type.
DBCLOB file reference
USAGE IS SQL TYPE IS
DBCLOB-FILE
Use this data type only to manipulate data
in DBCLOB columns. Do not use this data
type as a column type.
XML BLOB file reference SQL TYPE IS XML AS BLOB-FILE Use this data type only to manipulate
XML data as BLOB files. Do not use this
data type as a column type.
XML CLOB file reference SQL TYPE IS XML AS CLOB-FILE Use this data type only to manipulate
XML data as CLOB files. Do not use this
data type as a column type.
XML DBCLOB file reference SQL TYPE IS XML AS DBCLOB-FILE Use this data type only to manipulate
XML data as DBCLOB files. Do not use
this data type as a column type.
ROWID
SQL TYPE IS ROWID
Related concepts
LOB host variable, LOB locator, and LOB file reference variable declarations
on page 671
Host variable data types for XML data in embedded SQL applications on
page 330
Equivalent SQL and Fortran data types
When you declare host variables in your Fortran programs, the precompiler uses
equivalent SQL data types. When you retrieve data of a particular SQL data type
into a host variable, you need to ensure that the host variable is of an equivalent
data type.
The following table describes the SQL data type and the base SQLTYPE and
SQLLEN values that the precompiler uses for host variables in SQL statements.
Table 58. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in
Fortran programs
Fortran host variable data type
SQLTYPE of host
variable
1
SQLLEN of host variable SQL data type
INTEGER*2 500 2 SMALLINT
INTEGER*4 496 4 INTEGER
REAL*4 480 4 FLOAT (single precision)
REAL*8 480 8 FLOAT (double precision)
CHARACTER*n 452 n CHAR(n)
232 Application Programming and SQL Guide
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||
|
|
|||
|
|
|||
|
|
Table 58. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in
Fortran programs (continued)
Fortran host variable data type
SQLTYPE of host
variable
1
SQLLEN of host variable SQL data type
SQL TYPE IS
RESULT_SET_LOCATOR
972 4 Result set locator. Do not use
this data type as a column type.
SQL TYPE IS BLOB_LOCATOR 960 4 BLOB locator. Do not use this
data type as a column type.
SQL TYPE IS CLOB_LOCATOR 964 4 CLOB locator. Do not use this
data type as a column type.
SQL TYPE IS BLOB(n)
1n2147483647
404 n BLOB(n)
SQL TYPE IS CLOB(n)
1n2147483647
408 n CLOB(n)
SQL TYPE IS ROWID 904 40 ROWID
Notes:
1. If a host variable includes an indicator variable, the SQLTYPE value is the base
SQLTYPE value plus 1.
The following table shows equivalent Fortran host variables for each SQL data
type. Use this table to determine the Fortran data type for host variables that you
define to receive output from the database. For example, if you retrieve
TIMESTAMP data, you can define a variable of type CHARACTER*n.
This table shows direct conversions between SQL data types and Fortran data
types. However, a number of SQL data types are compatible. When you do
assignments or comparisons of data that have compatible data types, DB2 converts
those compatible data types.
Table 59. Fortran host variable equivalents that you can use when retrieving data of a particular SQL data type
SQL data type Fortran host variable equivalent Notes
SMALLINT INTEGER*2
INTEGER INTEGER*4
BIGINT not supported
DECIMAL(p,s) or
NUMERIC(p,s)
no exact equivalent Use REAL*8
FLOAT(n) single precision REAL*4 1<=n<=21
FLOAT(n) double precision REAL*8 22<=n<=53
CHAR(n) CHARACTER*n 1<=n<=255
VARCHAR(n) no exact equivalent Use a character host variable that is large
enough to contain the largest expected
VARCHAR value.
BINARY not supported
VARBINARY not supported
GRAPHIC(n) not supported
VARGRAPHIC(n) not supported
Chapter 3. Including DB2 queries in an application program 233
|||
|||
|||
Table 59. Fortran host variable equivalents that you can use when retrieving data of a particular SQL data
type (continued)
SQL data type Fortran host variable equivalent Notes
DATE CHARACTER*n If you are using a date exit routine, n is
determined by that routine; otherwise, n
must be at least 10.
TIME CHARACTER*n If you are using a time exit routine, n is
determined by that routine. Otherwise, n
must be at least 6; to include seconds, n
must be at least 8.
TIMESTAMP CHARACTER*n n must be at least 19. To include
microseconds, n must be 26; if n is less
than 26, truncation occurs on the
microseconds part.
Result set locator SQL TYPE IS RESULT_SET_LOCATOR Use this data type only for receiving result
sets. Do not use this data type as a
column type.
BLOB locator SQL TYPE IS BLOB_LOCATOR Use this data type only to manipulate data
in BLOB columns. Do not use this data
type as a column type.
1
CLOB locator SQL TYPE IS CLOB_LOCATOR Use this data type only to manipulate data
in CLOB columns. Do not use this data
type as a column type.
1
DBCLOB locator not supported
BLOB(n) SQL TYPE IS BLOB(n) 1n2147483647
1
CLOB(n) SQL TYPE IS CLOB(n) 1n2147483647
1
DBCLOB(n) not supported
ROWID SQL TYPE IS ROWID
XML not supported
Related concepts
LOB host variable, LOB locator, and LOB file reference variable declarations
on page 671
Equivalent SQL and PL/I data types
When you declare host variables in your PL/I programs, the precompiler uses
equivalent SQL data types. When you retrieve data of a particular SQL data type
into a host variable, you need to ensure that the host variable is of an equivalent
data type.
The following table describes the SQL data type and the base SQLTYPE and
SQLLEN values that the precompiler uses for host variables in SQL statements.
Table 60. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in PL/I
programs
PL/I host variable data type
SQLTYPE of host
variable
1
SQLLEN of host variable SQL data type
BIN FIXED(n) 1<=n<=15 500 2 SMALLINT
BIN FIXED(n) 16<=n<=31 496 4 INTEGER
FIXED BIN(63) 492 8 BIGINT
234 Application Programming and SQL Guide
|||
||||
Table 60. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in PL/I
programs (continued)
PL/I host variable data type
SQLTYPE of host
variable
1
SQLLEN of host variable SQL data type
DEC FIXED(p,s) 0<=p<=31 and
0<=s<=p
2
484 p in byte 1, s in byte 2 DECIMAL(p,s)
BIN FLOAT(p) 1<=p<=21 480 4 REAL or FLOAT(n) 1<=n<=21
BIN FLOAT(p) 22<=p<=53 480 8 DOUBLE PRECISION or
FLOAT(n) 22<=n<=53
DEC FLOAT(m) 1<=m<=6 480 4 FLOAT (single precision)
DEC FLOAT(m) 7<=m<=16 480 8 FLOAT (double precision)
CHAR(n) 452 n CHAR(n)
CHAR(n) VARYING 1<=n<=255 448 n VARCHAR(n)
CHAR(n) VARYING n>255 456 n VARCHAR(n)
GRAPHIC(n) 468 n GRAPHIC(n)
GRAPHIC(n) VARYING
1<=n<=127
464 n VARGRAPHIC(n)
GRAPHIC(n) VARYING n>127 472 n VARGRAPHIC(n)
SQL TYPE IS BINARY(n),
1<=n<=255
912 n BINARY(n)
SQL TYPE IS VARBINARY(n),
1<=n<=32 704
908 n VARBINARY(n)
SQL TYPE IS
RESULT_SET_LOCATOR
972 4 Result set locator
3
SQL TYPE IS TABLE LIKE
table-name AS LOCATOR
976 4 Table locator
3
SQL TYPE IS BLOB_LOCATOR 960 4 BLOB locator
3
SQL TYPE IS CLOB_LOCATOR 964 4 CLOB locator
3
SQL TYPE IS
DBCLOB_LOCATOR
968 4 DBCLOB locator
3
SQL TYPE IS BLOB(n)
1n2147483647
404 n BLOB(n)
SQL TYPE IS CLOB(n)
1n2147483647
408 n CLOB(n)
SQL TYPE IS DBCLOB(n)
1n1073741823
4
412 n DBCLOB(n)
4
SQL TYPE IS XML AS BLOB(n) 404 0 XML
SQL TYPE IS XML AS CLOB(n) 408 0 XML
SQL TYPE IS XML AS
DBCLOB(n)
412 0 XML
SQL TYPE IS BLOB_FILE 916/917 267 BLOB file reference
3
SQL TYPE IS CLOB_FILE 920/921 267 CLOB file reference
3
SQL TYPE IS DBCLOB_FILE 924/925 267 DBCLOB file reference
3
SQL TYPE IS XML AS
BLOB_FILE
916/917 267 XML BLOB file reference
3
SQL TYPE IS XML AS
CLOB_FILE
920/921 267 XML CLOB file reference
3
Chapter 3. Including DB2 queries in an application program 235
|
|
|||
|
|
|||
||||
||||
|
|
|||
||||
||||
||||
|
|
|||
|
|
|||
Table 60. SQL data types, SQLLEN values, and SQLTYPE values that the precompiler uses for host variables in PL/I
programs (continued)
PL/I host variable data type
SQLTYPE of host
variable
1
SQLLEN of host variable SQL data type
SQL TYPE IS XML AS
DBCLOB_FILE
924/925 267 XML DBCLOB file reference
3
SQL TYPE IS ROWID 904 40 ROWID
Notes:
1. If a host variable includes an indicator variable, the SQLTYPE value is the base SQLTYPE value plus 1.
2. If p=0, DB2 interprets it as DECIMAL(31). For example, DB2 interprets a PL/I data type of DEC FIXED(0,0) to be
DECIMAL(31,0), which equates to the SQL data type of DECIMAL(31,0).
3. Do not use this data type as a column type.
4. n is the number of double-byte characters.
The following table shows equivalent PL/I host variables for each SQL data type.
Use this table to determine the PL/I data type for host variables that you define to
receive output from the database. For example, if you retrieve TIMESTAMP data,
you can define a variable of type CHAR(n).
This table shows direct conversions between SQL data types and PL/I data types.
However, a number of SQL data types are compatible. When you do assignments
or comparisons of data that have compatible data types, DB2 converts those
compatible data types.
Table 61. PL/I host variable equivalents that you can use when retrieving data of a particular SQL data type
SQL data type PL/I host variable equivalent Notes
SMALLINT BIN FIXED(n) 1<=n<=15
INTEGER BIN FIXED(n) 16<=n<=31
BIGINT FIXED BIN(63)
DECIMAL(p,s) or
NUMERIC(p,s)
If p<16: DEC FIXED(p) or DEC
FIXED(p,s)
p is precision; s is scale. 1<=p<=31 and
0<=s<=p
If p>15, the PL/I compiler must support
31-digit decimal variables.
REAL or FLOAT(n) BIN FLOAT(p) or DEC FLOAT(m) 1<=n<=21, 1<=p<=21, and 1<=m<=6
DOUBLE PRECISION,
DOUBLE, or FLOAT(n)
BIN FLOAT(p) or DEC FLOAT(m) 22<=n<=53, 22<=p<=53, and 7<=m<=16
CHAR(n) CHAR(n) 1<=n<=255
VARCHAR(n) CHAR(n) VAR
GRAPHIC(n) GRAPHIC(n) n refers to the number of double-byte
characters, not to the number of bytes.
1<=n<=127
VARGRAPHIC(n) GRAPHIC(n) VAR n refers to the number of double-byte
characters, not to the number of bytes.
BINARY(n) SQL TYPE IS BINARY(n) 1<=n<=255
VARBINARY(n) SQL TYPE IS VARBINARY(n) 1<=n<=32 704
DATE CHAR(n) If you are using a date exit routine, that
routine determines n; otherwise, n must be
at least 10.
236 Application Programming and SQL Guide
|
|
|||
|||
|||
|||
Table 61. PL/I host variable equivalents that you can use when retrieving data of a particular SQL data
type (continued)
SQL data type PL/I host variable equivalent Notes
TIME CHAR(n) If you are using a time exit routine, that
routine determines n. Otherwise, n must
be at least 6; to include seconds, n must be
at least 8.
TIMESTAMP CHAR(n) n must be at least 19. To include
microseconds, n must be 26; if n is less
than 26, the microseconds part is
truncated.
Result set locator SQL TYPE IS RESULT_SET_LOCATOR Use this data type only for receiving result
sets. Do not use this data type as a
column type.
Table locator SQL TYPE IS TABLE LIKE table-name AS
LOCATOR
Use this data type only in a user-defined
function or stored procedure to receive
rows of a transition table. Do not use this
data type as a column type.
BLOB locator SQL TYPE IS BLOB_LOCATOR Use this data type only to manipulate data
in BLOB columns. Do not use this data
type as a column type.
1
CLOB locator SQL TYPE IS CLOB_LOCATOR Use this data type only to manipulate data
in CLOB columns. Do not use this data
type as a column type.
1
DBCLOB locator SQL TYPE IS DBCLOB_LOCATOR Use this data type only to manipulate data
in DBCLOB columns. Do not use this data
type as a column type.
1
BLOB(n) SQL TYPE IS BLOB(n) 1n2147483647
1
CLOB(n) SQL TYPE IS CLOB(n) 1n2147483647
1
DBCLOB(n) SQL TYPE IS DBCLOB(n) n is the number of double-byte characters.
1n1073741823
1
XML SQL TYPE IS XML AS BLOB(n) 1n2147483647
2
XML SQL TYPE IS XML AS CLOB(n) 1n2147483647
2
XML SQL TYPE IS XML AS DBCLOB(n) n is the number of double-byte characters.
1n1073741823
2
BLOB file reference SQL TYPE IS BLOB_FILE Use this data type only to manipulate data
in BLOB columns. Do not use this data
type as a column type.
1
CLOB file reference SQL TYPE IS CLOB_FILE Use this data type only to manipulate data
in CLOB columns. Do not use this data
type as a column type.
1
DBCLOB file reference SQL TYPE IS DBCLOB_FILE Use this data type only to manipulate data
in DBCLOB columns. Do not use this data
type as a column type.
1
XML BLOB file reference SQL TYPE IS XML AS BLOB_FILE Use this data type only to manipulate
XML data as BLOB files. Do not use this
data type as a column type.
2
XML CLOB file reference SQL TYPE IS XML AS CLOB_FILE Use this data type only to manipulate
XML data as CLOB files. Do not use this
data type as a column type.
2
Chapter 3. Including DB2 queries in an application program 237
|||
|||
|||
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
Table 61. PL/I host variable equivalents that you can use when retrieving data of a particular SQL data
type (continued)
SQL data type PL/I host variable equivalent Notes
XML DBCLOB file reference SQL TYPE IS XML AS DBCLOB_FILE Use this data type only to manipulate
XML data as DBCLOB files. Do not use
this data type as a column type.
2
ROWID SQL TYPE IS ROWID
Related concepts
LOB host variable, LOB locator, and LOB file reference variable declarations
on page 671
Host variable data types for XML data in embedded SQL applications on
page 330
Determining equivalent SQL and REXX data types
All REXX data is string data. Therefore, when a REXX procedure assigns input
data to a column, DB2 converts the data from a string type to the column type.
When a REXX procedure assigns column data to an output variable, DB2 converts
the data from the column type to a string type.
When you assign input data to a DB2 table column, you can either let DB2
determine the type that your input data represents, or you can use an SQLDA to
tell DB2 the intended type of the input data.
Data types that DB2 assigns to REXX input
When a REXX procedure assigns data to a column, it can either let DB2 determine
the data type or use an SQLDA to specify the intended data type. If the procedure
lets DB2 assign a data type for the input data, DB2 bases its choice on the input
string format.
The following table shows the SQL data types that DB2 assigns to input data and
the corresponding formats for that data. The two SQLTYPE values that are listed
for each data type are the value for a column that does not accept null values and
the value for a column that accepts null values.
Table 62. SQL input data types and REXX data formats
SQL data type
assigned by DB2
SQLTYPE for
data type REXX input data format
INTEGER 496/497 A string of numerics that does not contain a decimal point or exponent
identifier. The first character can be a plus (+) or minus (-) sign. The
number that is represented must be between -2147483647 and 2147483647,
inclusive.
BIGINT 492/493 A string of numbers that does not contain a decimal point or an exponent
identifier. The first character can be a plus (+) or minus (-) sign. The
number that is represented must be between -9223372036854775808 and
-2147483648, inclusive, or between 2147483648 and 9223372036854775807.
238 Application Programming and SQL Guide
|||
|
|
|||
|
|
|
Table 62. SQL input data types and REXX data formats (continued)
SQL data type
assigned by DB2
SQLTYPE for
data type REXX input data format
DECIMAL(p,s) 484/485 One of the following formats:
v A string of numerics that contains a decimal point but no exponent
identifier. p represents the precision and s represents the scale of the
decimal number that the string represents. The first character can be a
plus (+) or minus (-) sign.
v A string of numerics that does not contain a decimal point or an
exponent identifier. The first character can be a plus (+) or minus (-)
sign. The number that is represented is less than -9223372036854775808
or greater than 9223372036854775807.
FLOAT 480/481 A string that represents a number in scientific notation. The string consists
of a series of numerics followed by an exponent identifier (an E or e
followed by an optional plus (+) or minus (-) sign and a series of
numerics). The string can begin with a plus (+) or minus (-) sign.
VARCHAR(n) 448/449 One of the following formats:
v A string of length n, enclosed in single or double quotation marks.
v The character X or x, followed by a string enclosed in single or double
quotation marks. The string within the quotation marks has a length of
2*n bytes and is the hexadecimal representation of a string of n
characters.
v A string of length n that does not have a numeric or graphic format, and
does not satisfy either of the previous conditions.
VARGRAPHIC(n) 464/465 One of the following formats:
v The character G, g, N, or n, followed by a string enclosed in single or
double quotation marks. The string within the quotation marks begins
with a shift-out character (X0E) and ends with a shift-in character
(X0F). Between the shift-out character and shift-in character are n
double-byte characters.
v The characters GX, Gx, gX, or gx, followed by a string enclosed in single
or double quotation marks. The string within the quotation marks has a
length of 4*n bytes and is the hexadecimal representation of a string of n
double-byte characters.
For example, when DB2 executes the following statements to update the MIDINIT
column of the EMP table, DB2 must determine a data type for HVMIDINIT:
SQLSTMT="UPDATE EMP" ,
"SET MIDINIT = ?" ,
"WHERE EMPNO = '000200'"
"EXECSQL PREPARE S100 FROM :SQLSTMT"
HVMIDINIT='H'
"EXECSQL EXECUTE S100 USING" ,
":HVMIDINIT"
Because the data that is assigned to HVMIDINIT has a format that fits a character
data type, DB2 REXX Language Support assigns a VARCHAR type to the input
data.
If you do not assign a value to a host variable before you assign the host variable
to a column, DB2 returns an error code.
Chapter 3. Including DB2 queries in an application program 239
|
|
|
|
Embedding SQL statements in your application
You can code SQL statements in an assembler, C, C++, COBOL, Fortran, or PL/I
program or REXX procedure wherever you can use executable statements.
Embedding SQL statements in assembler applications
You can code SQL statements in an assembler program wherever you can use
executable statements.
Each SQL statement in an assembler program must begin with EXEC SQL. The
EXEC and SQL keywords must appear on one line, but the remainder of the
statement can appear on subsequent lines.
You might code an UPDATE statement in an assembler program as follows:
EXEC SQL UPDATE DSN8910.DEPT X
SET MGRNO = :MGRNUM X
WHERE DEPTNO = :INTDEPT
Comments: You cannot include assembler comments in SQL statements. However,
you can include SQL comments in any embedded SQL statement.
Continuation for SQL statements: The line continuation rules for SQL statements
are the same as those for assembler statements, except that you must specify EXEC
SQL within one line. Any part of the statement that does not fit on one line can
appear on subsequent lines, beginning at the continuation margin (column 16, the
default). Every line of the statement, except the last, must have a continuation
character (a non-blank character) immediately after the right margin in column 72.
Declaring tables and views: Your assembler program should include a DECLARE
statement to describe each table and view the program accesses.
Including code: To include SQL statements or assembler host variable declaration
statements from a member of a partitioned data set, place the following SQL
statement in the source code where you want to include the statements:
EXEC SQL INCLUDE member-name
You cannot nest SQL INCLUDE statements.
Margins: Use the precompiler option MARGINS to set a left margin, a right
margin, and a continuation margin. The default values for these margins are
columns 1, 71, and 16, respectively. If EXEC SQL starts before the specified left
margin, the DB2 precompiler does not recognize the SQL statement. If you use the
default margins, you can place an SQL statement anywhere between columns 2
and 71.
Multiple-row FETCH statements: You can use only the FETCH ... USING
DESCRIPTOR form of the multiple-row FETCH statement in an assembler
program. The DB2 precompiler does not recognize declarations of host variable
arrays for an assembler program.
Names: You can use any valid assembler name for a host variable. However, do
not use external entry names or access plan names that begin with DSN or host
variable names that begin with SQL. These names are reserved for DB2.
240 Application Programming and SQL Guide
The first character of a host variable that is used in embedded SQL cannot be an
underscore. However, you can use an underscore as the first character in a symbol
that is not used in embedded SQL.
Statement labels: You can prefix an SQL statement with a label. The first line of an
SQL statement can use a label beginning in the left margin (column 1). If you do
not use a label, leave column 1 blank.
WHENEVER statement: The target for the GOTO clause in an SQL WHENEVER
statement must be a label in the assembler source code and must be within the
scope of the SQL statements that WHENEVER affects.
Special assembler considerations: The following considerations apply to programs
written in assembler:
v To allow for reentrant programs, the precompiler puts all the variables and
structures it generates within a DSECT called SQLDSECT, and it generates an
assembler symbol called SQLDLEN. SQLDLEN contains the length of the
DSECT. Your program must allocate an area of the size indicated by SQLDLEN,
initialize it, and provide addressability to it as the DSECT SQLDSECT. The
precompiler does not generate code to allocate the storage for SQLDSECT; the
application program must allocate the storage.
CICS: An example of code to support reentrant programs, running under CICS,
follows:
DFHEISTG DSECT
DFHEISTG
EXEC SQL INCLUDE SQLCA
*
DS 0F
SQDWSREG EQU R7
SQDWSTOR DS (SQLDLEN)C RESERVE STORAGE TO BE USED FOR SQLDSECT
.
.
.
XXPROGRM DFHEIENT CODEREG=R12,EIBREG=R11,DATAREG=R13
*
*
* SQL WORKING STORAGE
LA SQDWSREG,SQDWSTOR GET ADDRESS OF SQLDSECT
USING SQLDSECT,SQDWSREG AND TELL ASSEMBLER ABOUT IT
*
In this example, the actual storage allocation is done by the DFHEIENT macro.
TSO: The sample program in prefix.SDSNSAMP(DSNTIAD) contains an example
of how to acquire storage for the SQLDSECT in a program that runs in a TSO
environment. The following example code contains pieces from
prefix.SDSNSAMP(DSNTIAD) with explanations in the comments.
DSNTIAD CSECT CONTROL SECTION NAME
SAVE (14,12) ANY SAVE SEQUENCE
LR R12,R15 CODE ADDRESSABILITY
USING DSNTIAD,R12 TELL THE ASSEMBLER
LR R7,R1 SAVE THE PARM POINTER
*
* Allocate storage of size PRGSIZ1+SQLDSIZ, where:
* - PRGSIZ1 is the size of the DSNTIAD program area
* - SQLDSIZ is the size of the SQLDSECT, and declared
* when the DB2 precompiler includes the SQLDSECT
*
L R6,PRGSIZ1 GET SPACE FOR USER PROGRAM
A R6,SQLDSIZ GET SPACE FOR SQLDSECT
GETMAIN R,LV=(6) GET STORAGE FOR PROGRAM VARIABLES
Chapter 3. Including DB2 queries in an application program 241
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LR R10,R1 POINT TO IT
*
* Initialize the storage
*
LR R2,R10 POINT TO THE FIELD
LR R3,R6 GET ITS LENGTH
SR R4,R4 CLEAR THE INPUT ADDRESS
SR R5,R5 CLEAR THE INPUT LENGTH
MVCL R2,R4 CLEAR OUT THE FIELD
*
* Map the storage for DSNTIAD program area
*
ST R13,FOUR(R10) CHAIN THE SAVEAREA PTRS
ST R10,EIGHT(R13) CHAIN SAVEAREA FORWARD
LR R13,R10 POINT TO THE SAVEAREA
USING PRGAREA1,R13 SET ADDRESSABILITY
*
* Map the storage for the SQLDSECT
*
LR R9,R13 POINT TO THE PROGAREA
A R9,PRGSIZ1 THEN PAST TO THE SQLDSECT
USING SQLDSECT,R9 SET ADDRESSABILITY
...
LTORG
**********************************************************************
* *
* DECLARE VARIABLES, WORK AREAS *
* *
**********************************************************************
PRGAREA1 DSECT WORKING STORAGE FOR THE PROGRAM
...
DS 0D
PRGSIZE1 EQU *-PRGAREA1 DYNAMIC WORKAREA SIZE
...
DSNTIAD CSECT RETURN TO CSECT FOR CONSTANT
PRGSIZ1 DC A(PRGSIZE1) SIZE OF PROGRAM WORKING STORAGE
CA DSECT
EXEC SQL INCLUDE SQLCA
...
v DB2 does not process set symbols in SQL statements.
v Generated code can include more than two continuations per comment.
v Generated code uses literal constants (for example, =F-84), so an LTORG
statement might be necessary.
v Generated code uses registers 0, 1, 14, and 15. Register 13 points to a save area
that the called program uses. Register 15 does not contain a return code after a
call that is generated by an SQL statement.
CICS: A CICS application program uses the DFHEIENT macro to generate the
entry point code. When using this macro, consider the following:
If you use the default DATAREG in the DFHEIENT macro, register 13 points
to the save area.
If you use any other DATAREG in the DFHEIENT macro, you must provide
addressability to a save area.
For example, to use SAVED, you can code instructions to save, load, and
restore register 13 around each SQL statement as in the following example.
ST 13,SAVER13 SAVE REGISTER 13
LA 13,SAVED POINT TO SAVE AREA
EXEC SQL . . .
L 13,SAVER13 RESTORE REGISTER 13
242 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
v If you have an addressability error in precompiler-generated code because of
input or output host variables in an SQL statement, check to make sure that you
have enough base registers.
v Do not put CICS translator options in the assembly source code. Instead, pass
the options to the translator by using the PARM field.
Embedding SQL statements in C or C++ applications
You can code SQL statements in a C program wherever you can use executable
statements.
Each SQL statement in a C program must begin with EXEC SQL and end with a
semicolon (;). The EXEC and SQL keywords must appear on one line, but the
remainder of the statement can appear on subsequent lines.
In general, because C is case sensitive, use uppercase letters to enter all SQL
keywords. However, if you use the FOLD precompiler suboption, DB2 folds
lowercase letters in SBCS SQL ordinary identifiers to uppercase. For information
about host language precompiler options, see Table 153 on page 868.
You must keep the case of host variable names consistent throughout the program.
For example, if a host variable name is lowercase in its declaration, it must be
lowercase in all SQL statements. You might code an UPDATE statement in a C
program as follows:
EXEC SQL
UPDATE DSN8910.DEPT
SET MGRNO = :mgr_num
WHERE DEPTNO = :int_dept;
Comments: You can include C comments (/* ... */) within SQL statements
wherever you can use a blank, except between the keywords EXEC and SQL. You
can use single-line comments (starting with //) in C language statements, but not
in embedded SQL. You can use SQL comments within embedded SQL statements.
You can nest comments.
To include EBCDIC DBCS characters in comments, you must delimit the characters
by a shift-out and shift-in control character; the first shift-in character in the DBCS
string signals the end of the DBCS string.
Continuation for SQL statements: You can use a backslash to continue a
character-string constant or delimited identifier on the following line. However,
EBCDIC DBCS string constants cannot be continued on a second line.
Declaring tables and views: Your C program should use the DECLARE TABLE
statement to describe each table and view the program accesses. You can use the
DB2 declarations generator (DCLGEN) to generate the DECLARE TABLE
statements. For more information, see DCLGEN (declarations generator) on page
129.
Including SQL statements and variable declarations in source code that is to be
processed by the DB2 precompiler: To include SQL statements or C host variable
declarations from a member of a partitioned data set, add the following SQL
statement to the source code where you want to include the statements:
EXEC SQL INCLUDE member-name;
Chapter 3. Including DB2 queries in an application program 243
|
|
|
|
|
|
|
You cannot nest SQL INCLUDE statements. Do not use C #include statements to
include SQL statements or C host variable declarations.
Names:Margins: Code SQL statements in columns 1 through 72, unless you specify
other margins to the DB2 precompiler. If EXEC SQL is not within the specified
margins, the DB2 precompiler does not recognize the SQL statement. The margin
rules do not apply to the DB2 coprocessor. The DB2 coprocessor allows variable
length source input.
You can use any valid C name for a host variable, subject to the following
restrictions:
v Do not use DBCS characters.
v Do not use external entry names or access plan names that begin with DSN,
and do not use host variable names or macro names that begin with SQL (in
any combination of uppercase or lowercase letters). These names are reserved
for DB2.
Nulls and NULs: C and SQL differ in the way they use the word null. The C
language has a null character (NUL), a null pointer (NULL), and a null statement
(just a semicolon). The C NUL is a single character that compares equal to 0. The C
NULL is a special reserved pointer value that does not point to any valid data
object. The SQL null value is a special value that is distinct from all non-null
values and denotes the absence of a (nonnull) value. NUL (or NUL-terminator) is
the null character in C and C++, and NULL is the SQL null value.
Sequence numbers: The DB2 precompiler generates statements without sequence
numbers. (The DB2 coprocessor does not perform this action, because the source is
read and modified by the compiler. )
Statement labels: You can precede SQL statements with a label.
Trigraph characters: Some characters from the C character set are not available on
all keyboards. You can enter these characters into a C source program using a
sequence of three characters called a trigraph. The trigraph characters that DB2
supports are the same as those that the C compiler supports.
WHENEVER statement: The target for the GOTO clause in an SQL WHENEVER
statement must be within the scope of any SQL statements that the statement
WHENEVER affects.
Special C considerations:
v Using the C/370

multi-tasking facility, in which multiple tasks execute SQL


statements, causes unpredictable results.
v Except for the DB2 coprocessor, you must run the DB2 precompiler before
running the C preprocessor.
v Except for the DB2 coprocessor, DB2 precompiler does not support C
preprocessor directives.
v If you use conditional compiler directives that contain C code, either place them
after the first C token in your application program, or include them in the C
program using the #include preprocessor directive.
Refer to the appropriate C documentation for more information about C
preprocessor directives.
244 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Embedding SQL statements in COBOL applications
You can code SQL statements in certain COBOL program sections.
The allowable sections are shown in the following table.
Table 63. Allowable SQL statements for COBOL program sections
SQL statement Program section
BEGIN DECLARE SECTION
END DECLARE SECTION
WORKING-STORAGE SECTION
1
or LINKAGE
SECTION
INCLUDE SQLCA WORKING-STORAGE SECTION
1
or LINKAGE
SECTION
INCLUDE text-file-name PROCEDURE DIVISION or DATA DIVISION
2
DECLARE TABLE
DECLARE CURSOR
DATA DIVISION or PROCEDURE DIVISION
DECLARE VARIABLE WORKING-STORAGE SECTION
1
Other PROCEDURE DIVISION
Notes:
1. If you use the DB2 coprocessor, you can use the LOCAL-STORAGE SECTION wherever
WORKING-STORAGE SECTION is listed in the table.
2. When including host variable declarations, the INCLUDE statement must be in the
WORKING-STORAGE SECTION or the LINKAGE SECTION.
You cannot put SQL statements in the DECLARATIVES section of a COBOL
program.
Each SQL statement in a COBOL program must begin with EXEC SQL and end
with END-EXEC. If you are using the DB2 precompiler, the EXEC and SQL
keywords must appear on one line, but the remainder of the statement can appear
on subsequent lines. If you are using the DB2 coprocessor, the EXEC and SQL
keywords can be on different lines. Do not include any tokens between the two
keywords EXEC and SQL except for COBOL comments, including debugging lines.
Do not include SQL comments between the keywords EXEC and SQL.
If the SQL statement appears between two COBOL statements, the period after
END-EXEC is optional and might not be appropriate. If the statement appears in
an IF...THEN set of COBOL statements, omit the ending period to avoid
inadvertently ending the IF statement.
You might code an UPDATE statement in a COBOL program as follows:
EXEC SQL
UPDATE DSN8910.DEPT
SET MGRNO = :MGR-NUM
WHERE DEPTNO = :INT-DEPT
END-EXEC.
Comments: You can include COBOL comment lines (* in column 7) in SQL
statements wherever you can use a blank. If you are using the DB2 precompiler,
you cannot include COBOL comment lines between the keywords EXEC and SQL.
The precompiler treats COBOL debugging lines and page-eject lines (/ in column
7) as comment lines. The DB2 coprocessor treats the debugging lines based on the
COBOL rules, which depend on the WITH DEBUGGING mode setting.
Chapter 3. Including DB2 queries in an application program 245
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
For an SQL INCLUDE statement, the DB2 precompiler treats any text that follows
the period after END-EXEC, and on the same line as END-EXEC, as a comment.
The DB2 coprocessor treats this text as part of the COBOL program syntax.
In addition, you can include SQL comments (--) in any embedded SQL statement.
Debugging lines: The DB2 precompiler ignores the D in column 7 on debugging
lines and treats it as a blank. The DB2 coprocessor follows the COBOL language
rules regarding debugging lines.
Continuation for SQL statements: The rules for continuing a character string
constant from one line to the next in an SQL statement embedded in a COBOL
program are the same as those for continuing a non-numeric literal in COBOL.
However, you can use either a quote or an apostrophe as the first nonblank
character in area B of the continuation line. The same rule applies for the
continuation of delimited identifiers and does not depend on the string delimiter
option.
To conform with SQL standard, delimit a character string constant with an
apostrophe, and use a quote as the first nonblank character in area B of the
continuation line for a character string constant.
Continued lines of an SQL statement can be in columns 8 through 72 when using
the DB2 precompiler and columns 12 through 72 when using the DB2 coprocessor.
COPY: If you use the DB2 precompiler, do not use a COBOL COPY statement
within host variable declarations. If you use the DB2 coprocessor, you can use
COBOL COPY.
REPLACE: If you use the DB2 precompiler, the REPLACE statement has no effect
on SQL statements. It affects only the COBOL statements that the precompiler
generates.
If you use the DB2 coprocessor, the REPLACE statement replaces text strings in
SQL statements as well as in generated COBOL statements.
Declaring tables and views: Your COBOL program should include the statement
DECLARE TABLE to describe each table and view the program accesses. You can
use the DB2 declarations generator (DCLGEN) to generate the DECLARE TABLE
statements. You should include the DCLGEN members in the DATA DIVISION.
For more information, see DCLGEN (declarations generator) on page 129.
Dynamic SQL in a COBOL program: In general, COBOL programs can easily
handle dynamic SQL statements. COBOL programs can handle SELECT statements
if the data types and the number of fields returned are fixed. If you want to use
variable-list SELECT statements, use an SQLDA. See Defining SQL descriptor
areas on page 142 for more information on SQLDA.
Including code: To include SQL statements or COBOL host variable declarations
from a member of a partitioned data set, use the following SQL statement in the
source code where you want to include the statements:
EXEC SQL INCLUDE member-name END-EXEC.
If you are using the DB2 precompiler, you cannot nest SQL INCLUDE statements.
In this case, do not use COBOL verbs to include SQL statements or host variable
declarations, and do not use the SQL INCLUDE statement to include CICS
246 Application Programming and SQL Guide
|
|
|
|
|
|
|
|
|
preprocessor related code. In general, if you are using the DB2 precompiler, use the
SQL INCLUDE statement only for SQL-related coding. If you are using the COBOL
DB2 coprocessor, none of these restrictions apply.
Margins: You must code SQL statements that begin with EXEC SQL in columns 12
through 72. Otherwise the DB2 precompiler does not recognize the SQL statement.
Names: You can use any valid COBOL name for a host variable. Do not use
external entry names or access plan names that begin with DSN, and do not use
host variable names that begin with SQL. These names are reserved for DB2.
Sequence numbers: The source statements that the DB2 precompiler generates do
not include sequence numbers.
Statement labels: You can precede executable SQL statements in the PROCEDURE
DIVISION with a paragraph name, if you wish.
WHENEVER statement: The target for the GOTO clause in an SQL statement
WHENEVER must be a section name or unqualified paragraph name in the
PROCEDURE DIVISION.
Special COBOL considerations: The following considerations apply to programs
written in COBOL:
v In a COBOL program that uses elements in a multi-level structure as host
variable names, the DB2 precompiler generates the lowest two-level names.
v Using the COBOL compiler options DYNAM and NODYNAM depends on the
operating environment.
TSO and IMSYou can specify the option DYNAM when compiling a COB