Professional Documents
Culture Documents
Introduction SQL General Information Using SQL SQL Error Handling DB2 Tools & Environment Design Considerations Focus Considerations DB2 Program Development Procedures Internal DB2 Processing Considerations
A. INTRODUCTION
In order to standardize DB2 development and improve maintainability, sample DB2 programs and program shells have been created for both online and batch environments. Before beginning a new program, it would be helpful to review both the shell and the sample program. Ideally, either the shell or the sample program will serve as a starting point for creating new programs. The shells and sample programs are found in DS.TEST.PANVALET as follows:
Online:
Shell program Sample program Error routine DB2SHELLC DB2SAMPLEC DB2SQLERRC
Common CICS program messages DB2WSMSG CICS error display program DB2019DB
Batch:
Shell program Sample program Error routine Other Components: DB2 error working storage Edit date routine DB2/edit date working storage DB2WSERROR DB2EDATE DB2WS DB2SHELLB DB2SAMPLEB DB2SQLERRB
The shells, sample programs, and common modules have been made available to give application programmers a starting point when creating DB2 programs. They were meant to enhance, not replace the following standards. Please refer to the following sections for more detail on programming with DB2. If you still can't find an answer, contact the DBA team for assistance. Prepared By P.Srinath Reddy 26th march 1999 1/17
Sample tables and a sample application program that accesses these tables were also shipped with DB2. Copies of the sample program in several different languages can be found in Appendix B of the DB2 Application Programming and SQL Guide. The programs are also stored in library 'DS.PANVALET' accessible through ISPF. The Cobol batch program is 'DB2COBOL'.
2/17
Multicolumn indexes
If a table has only multicolumn indexes, try to specify the high-level column in the WHERE clause of your query. This results in an index scan with at least one matching column.
Explicitly specify all column names in any SQL statement. Avoid using the substring function in an SQL predicate.
II. Application Development Standards & Guidelines
Do not use dynamic SQL in application programs. DDL and DCL in application programs
Do not use data definition (DDL) and data control (DCL) SQL statements in application programs. CICS/DB2 programs coded in Cobol II should use command-level CICS rather than macro.
Use of DCLGEN
Create the table layout ('include' member) by executing a DCLGEN in SPUFI. The DCLGEN includes a DECLARE statement and a cobol layout for the table.
Move the member from the default library to DS.TEST.PANVALET and use the standard '++INCLUDE' to bring the definition into your program.
(Do not use the 'EXEC SQL INCLUDE' statement as seen in some sample programs.)
6/17
About COMMITting
It is important to issue COMMIT commands in batch programs for two reasons; it will improve recovery time by reducing the amount of work that has to backed out and redone in the case of an abnormal termination, and it will free locks used by the batch job allowing more concurrency. A checkpoint/restart routine must be established for batch programs which will store all relevant information needed to restart the program in a separate DB2 table followed by a COMMIT call. When the program runs or reruns, an initialization routine will read the DB2 restart table to obtain a starting point. It will be your responsibility to recover any non-DB2 resources that are updated by the program. The frequency at which checkpoints should be taken will vary from application to application. There are a number of considerations for selecting the commit frequency. If the batch program is accessing tables that are also being accessed by online transactions, you should checkpoint very frequently. If the data accessed by the batch program is not used concurrently by online transactions, the checkpoint interval should be such that the restart time is acceptable.
Checkpoint/Restart
Once a COMMIT is issued in the batch program, the program must be written to support a restart at the point of the COMMIT. This would include repositioning the cursor, repositioning in an input transaction file, and handling the output files, including reports, so that there will not be any lost data. It is generally advisable not to write to a non-DB2 file at the same time you are updating a DB2 database. If an output file must be written DB2 table(s) could be used to contain pertinent information for a later process. If the output file is too large for DB2 then the program must insure that all data information is written to the file at the time of the COMMIT (externalize the output records). This can be accomplished through the MVS checkpoint/restart facility, or by closing and then reopening the files (see Section H for details and examples of checkpoint/restart). IV. Online Programming Standards & Guidelines
7/17
S9999-sql-error will call DSNTIAR and fill in ws-error-msg and XCTL to DB2019DB. When calling DSNTIAR from a batch program, the batch program will need to be compiled with the DYNAM parameter.
SQLCA
Always include the SQLCA include member in your application program.
Error Checking
Always check the SQL return code available in the SQLCODE field after every SQL statement: General checking: After OPEN or CLOSE, check SQLCODE = OTHER Statement not executed; error detected SQLCODE = zeroes SQLCODE > zeroes SQLCODE < zeroes detected Normal execution Statement executed; error detected Statement not executed; error
8/17
9/17
Timestamp error Updating a foreign key that does not have a matching primary key value in the parent table Duplicate primary key Timestamp error or bad date Record not found Updating primary key that has dependent rows in another table Record not found Timestamp error Deleting parent rows with dependent children rows in another table
DB2 Deadlocks
The use of the DB2 locking scheme may lead to a problem called deadlocking. This situation may arise when two programs are attempting to update tables that have been previously locked by the other. In a deadlock situation, DB2 arbitrarily selects a "winner" and a "loser". The "loser" will receive SQL error code -911 or -913 and the current processing is rolled back. As a precautionary step it is important to update all tables in related applications in the same sequence.
10/17
F. DESIGN CONSIDERATIONS
1. Indexes
Index Usage
Indexes are used in a WHERE clause with the following predicate types: * column = value * column is null * column > value * column < value * column >= value * column <= value * column BETWEEN value1 and value2 * column LIKE 'char%' * column IN list Indexes are NOT used in WHERE clauses with the following predicates: * column not null * column not BETWEEN value1 and value2 * column LIKE '%char' * column LIKE '_char' * column LIKE host variable * column not IN list ** Use the EXPLAIN utility to determine if indexes are being used.
11/17
Avoid the use of LIKE predicates with host variables or predicates beginning with % or _
They may prevent DB2 from using indexes that might be defined on a column to limit the number of rows scanned.
Guidelines
Index-based retrievals are generally more efficient than a tablespace scan. When every page in the tablespace is retrieved, a tablespace scan is more efficient. Always fully qualify the search criterion that you specify in your SQL statement. Always specify the same data type, precision, and scale when comparing column values against host variables and literals.
G. Focus Considerations
1. Background The primary tool for ad hoc reporting against DB2 data will be Focus. While the Focus syntax is the same regardless of the data structure accessed (VSAM, sequential files, DB2 tables, etc.), there are special considerations when accessing DB2 data. It is advisable for the query writer to understand the appropriate coding techniques for writing efficient queries which will provide accurate information. 2. Master File Description (MFD) A Master File Description (MFD) is required for each table and view which will be accessed via Focus queries. This can be generated by a member of Information Access Group (IAG) staff using the Focus utility 'Auto-DB2'. The utility uses the DB2 catalog tables to generate the Focus code. This is a convenient way to create an MFD and also ensure that all table/view names and column names exactly match the DB2 objects. This utility will be used both in test and production 3. Access File Description (AFD) An Access File Description (AFD) is also required for each table and view to be accessed via Focus queries. An AFD makes the connection between the table name, as used in a Focus query, and the actual, fully-qualified DB2 table name (owner.tablename). This will also be generated by Auto-DB2. Because the fully-qualified name will indicate the subsystem by the owner name (TESTDBA for test, PRODDBA for production), it must agree with the subsystem id being accessed (see item 4 below).
12/17
Selected, representative Focus queries will be used to test access and provide benchmark statistics for test DB2 tables which will implemented in the Information Center.
JCL to compile COBOL II programs is in DS.TEST.PANVALET as 'DB2COMPCIC' for CICS programs, 'DB2COMPBAT' for batch programs, and 'DB2COMPINT' to compile under intertest.
13/17
Background
To access DB2 data, an SQL statement requires an access path. For dynamic SQL, such as statements issued through SPUFI, DB2 determines the access path when the statement executes. For statements that do not execute often, this method is usually acceptable. However, an application typically runs the same SQL statements repeatedly. In this case, determining the access path at run time wastes system resources, because the system must determine the same path repeatedly. To conserve your system resources, use static SQL. Access paths for static SQL are determined only at BIND or REBIND time. When a DB2 program is compiled, it produces a load module and a DBRM (Database Request Module) containing the executable SQL. For this program to be executed, the DBRM must either be bound into a package or directly into plan. A package can contain only 1 DBRM, but a plan can include many DBRMs and/or packages. To run the program, you must specify a program and it's plan. Depending upon how you design your DB2 application, you might bind all your DBRMs in one operation, creating only a single application plan. Or, you might bind some or all of your DBRMs into separate packages in separate operations. After that, you must still bind the entire application as a single plan, listing the included packages or collections and binding any DBRMs not already bound into packages. Regardless of what the plan contains, you must bind a plan before the application can run. Here are some advantages to using packages: Ease of Maintenance: 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 associated with the changed SQL statement. This feature is similiar to compiling called and calling programs with the "DYNAM" option. Incremental Development of Your Program: Binding packages into package collections allows you to add packages to an existing application plan without having to bind the entire plan again. A collection is a group of associated packages. 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 even 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. Versioning: 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. When to use Packages: For plans which are bound with only one DBRM, packages don't offer any advantage. However, for plans that use multiple DBRMs, it is sometimes better to bind each DBRM into a package and then bind the packages into the plan. This feature will be especially valuable for CICS applications where concurrency is more of an issue.
Bind Standards
The program, DBRM, and plan names should always be the same. The program should use unqualified table names to allow the 'OWNER' parameter of the bind to supply the qualifier ('TESTDBA' or 'PRODDBA'). This will require the programmer to edit the sql 'declare table' statement 26th march 1999 14/17
Guidelines
The following BIND parameters are recommended: Retain Execution Authority: YES Isolation Level: CS Plan Validation Time: BIND Resource Allocation Time: USE Resource Release Time: COMMIT Explain Path: YES
The parameters for a program named 'AA0100BB' to be bound in test for the first time would be as follows: DSN SYSTEM(DBT1) BIND PLAN(AA0100BB) MEMBER(AA0100BB) LIBRARY ('DBT1.DB2.DBRMLIB') OWNER(TESTDBA) ACTION(ADD) RETAIN ISOLATION(CS) VALIDATE(BIND) RELEASE(COMMIT) Subsequent executions of the bind would specify 'ACTION(REPL)' to replace the previous plan.
15/17
MATCHCOLS # columns of index used in predicate match ACCESSCREATOR Creator of index, if one is used ACCESSNAME Name of index, if one is used INDEXONLY Is this step fully serviced by index only or will data be accessed? (Y/N) SORTN_xxxx Sort to create the "new" (input) table to this step? (Y/N) (want to see "Y" for most efficient access) SORTC_xxxx Sort to create the "composite" (results) table (Y/N) (want to see "Y" for most efficient access) TSLOCKMODE Type of tablespace lock chosen by DB2 1. 2. 3. 4. S - shared X - exclusive IS - shared page locks IX - exclusive page locks
PREFETCH Are pages fetched ahead? 1. 2. S - sequential (e.g. cursor FETCH) L - list (e.g. union of index entries)
Information
The thread concept is how applications access DB2 data. A thread is responsible for the following: identifies the user, allocates DB2 resources, and executes user requests. 2. Locking & Performance Considerations
Information
The lock size is determined by the creator of the tablespace. A DB2 object may be locked at the page, table (segmented tablespaces), or tablespace level. The lock type is determined by the type of statement that is executed. For example, a SELECT or FETCH statement from a read-only cursor uses a shared lock; a Prepared By P.Srinath Reddy 26th march 1999 17/17
End Of Document
18/17