Sie sind auf Seite 1von 246

Mainframe Application Programming

Volume II: DB2, CICS

INDEX

DB2 ............................................................................................................................................... 3
Chapter 1 : Introduction to RDBMS .................................................................................. 4 Chapter 2 : Overview of DB2/UDB ver 7 for OS/390 ...................................................... 12 Chapter 3 : DB2 Objects ................................................................................................... 13 Chapter 4 : Structured Query Language ........................................................................ 18 Chapter 5 : DB2 Interfaces ............................................................................................... 46 Chapter 6 : DB2 Application Development Overview ................................................... 47 Chapter 7 : SQL Execution Validation ............................................................................ 83 Chapter 8 : Advanced SQL .............................................................................................. 86 Chapter 9 : Performance Monitoring/Tuning ................................................................. 95 Chapter 10 : Locking and Concurrency ........................................................................ 101 Chapter 11 : DB2 Utilities ................................................................................................ 106 Chapter 12 : DB2 Environment for OS/390 and Z/OS ................................................... 110 Appendix ........................................................................................................................... 113

CICS........................................................................................................................................... 140
Objective ........................................................................................................................... 141 Introduction to CICS ........................................................................................................ 141 Application Programming Concepts ............................................................................. 158 Exceptional Conditions ................................................................................................... 167 Basic Mapping Support ................................................................................................... 182 File Control ....................................................................................................................... 199 CICS File Handling Program ........................................................................................... 207 Queues .............................................................................................................................. 210 Communication with Databases .................................................................................... 221 Common Abend Codes ................................................................................................... 236 CICS Commands Summary ........................................................................................... 240 Glossary ............................................................................................................................ 243

Maples ESM Technologies Pvt. Ltd

Page 2 of 246

DB2

DB2
(DATABASE 2)

Maples ESM Technologies Pvt. Ltd

Page 3 of 246

DB2

Objective
Before learning the details of coding DB2 COBOL programs, you need to know some basic RDBMS concepts and terms. In this chapter you will learn about DB2 Object, SQL Queries with SPUFI and QMF. After you are introduced to DB2 Basics and SQL processing, you wuill learning how the application program gets communicated to DB2 and processing steps involved in that.Then coding of Embedded SQL in Applicaion program with SQLCA and DCLGEN member. Also you will be learning how to retrieve and process multiple rows into application programming for processing. At the end of module performance tuning parameters and utilities in DB2 is described for you.

Chapter 1 : Introduction to RDBMS


Relational Database is a collection of programs that enables user to create and maintain a database based on formal mathematical concepts and definitions. It has to maintain the data integrity and data consistency. In relational database, the datas are arranged in row and column wise and there is only one value for each column. RDBMS is nothing more than a computerbased record keeping system, i.e. data stored in the form of tables, which consists of multiple rows and columns.

Examples: DB2, ORACLE, SYBASE, INGRES, etc

Relational Concepts (Terminology)


Relation Tuple Attributes Domain Entity Null Atomic Value : : : : : : : A table or File Row contains an entry for each attribute Columns or the characteristics that define the entity A range of values (or Pool) Some object about which we wish to store information Represents an unknown/empty value Smallest unit of data; the individual data value Some attribute (or a set of attributes) that may uniquely identify each row (tuple) in the relation (table) Primary key : The candidate key is chosen for primary attributes to uniquely identify each row.

Candidate key :

Maples ESM Technologies Pvt. Ltd

Page 4 of 246

DB2

Alternate key Foreign key

: :

The remaining candidate keys that were not chosen as primary key An attribute of one relation that might be a primary key of another relation.

Advantages of RDBMS over File Management Systems


Data redundancy Multiple views Shared data Data independence (logical/physical) Data dictionary Search versatility Cost effective Security & Control Recovery restart & Backup Concurrency

CODDs Relational Rules


1. All information in a relational database is represented explicitly at the logical level and in exactly one way - by values in tables 2. Each and every datum(atomic value) in a relational database is guaranteed to be logically accessible by resorting to a combination of table name, primary key value, and column name 3. Null values are supported for representing missing information in a systematic way irrespective of the data type. 4. The database description is represented at the logical level in the same way as ordinary data, so that authorized users can apply the same relational language to its interrogation as they apply to the regular data. 5. A relational system may support several languages and various modes of terminal use. However there must be one language whose statements can express all of the following items: (1) data definitions (2) view definitions (3) data manipulation (interactive and by program) (4) integrity constraints (5) authorization (6) transaction boundaries (begin, commit, rollback) 6. All views are theoretically updatable, are also updatable by the system

Maples ESM Technologies Pvt. Ltd

Page 5 of 246

DB2

7. The capability of handling a base relation or a derived relation (view) as a single operand applies not only to the retrieval of data but also to the insertion, updation and deletion of data 8. Application programs and terminal activities remain logically unimpaired whenever any changes are made in either storage representations or access methods 9. Application programs and terminal activities remain logically unimpaired when informationpreserving changes of any kind that theoretically permit unimpairment are made to the base tables. 10. Integrity constraints specific to a particular relational database must be definable in relational data sublanguage and storable in the catalog, not in application programs. 11. The data manipulation sublanguage of a relational DBMS must enable application programs and inquiries to remain logically the same whether and whenever data are physically centralized or distributed. 12. If a relational system has a low-level (single-record-at-a-time) language, that low level cannot be used to subvert or bypass the integrity rules and constraints expressed in the higher-level relational language (multiple-records-at-a-time)

Normalisation
Normalization is a database design approach that minimizes data redundancy and optimizes data structures by systematically and properly placing data elements into appropriate groupings. A normalized data model can be translated into a physical database that is organized correctly.

Another way of putting it is that normalization is the process of putting one fact in one appropriate place.E.F Codd, the father of the relational model, also created normalization. Like the relational model, normalization is based on the mathematical principles of set theory. With a normalized data model, one fact is stored in one place, related facts about a single entity are stored together, and every column of each entity refers non-transitively to only the unique identifier for that entity. The data in the database can be considered to be in one of a number of `normal forms'. Basically the normal form of the data indicates how much redundancy is in that data. The normal forms have a strict ordering: 1. First Normal Form 2. Second Normal Form 3. Third Normal Form

Employee and Projects example illustrates the above three Normalisation


The table below depicts the requirements for a business consultancy working on local and international projects.

Maples ESM Technologies Pvt. Ltd

Page 6 of 246

DB2

EmpNo 005

EmpName Smith

Dept Marketing

Manager Projid Jones A B C B D C A B D

Proj-StartDate 12-93 6-94 09-94 06-94 06-94 09-94 12-93 06-94 06-94

Location Poole Plymouth Portsmouth Plymouth Berlin Portsmouth Poole Belfast Hamburg

Weeks-onProject 11 15 6 3 9 10 21 10 12

007 009 010

Bond King Holt

Accounts Info Systems Accounts

Bloggs Hurne Bloggs

Notes: Employees work on a number of projects concurrently. Weeks-on-project represents the number of weeks to date that an employee has spent on a particular project. The employee number, emp-no, and the project identifier, project-id, are unique identifiers. The department manager, manager, is the name of the current manager, i.e., there can only be one manager per department. A project can take place in several locations. You are required to show the first, second and third normal forms. Explain the normalisation process used.

First Normal Form


Relations in first normal form represent data as a set of tuples each of which is uniquely identified by a primary key value. The most difficult part of constructing a first normal form set of relations is identifying the primary key for each relation. It is best to select the primary key attributes which reduce the number of attributes that repeat. An attribute repeats when it contains two or more values for each value of the primary key. The following guidelines should produce a set of first normal form relations. 1. Select a primary key for the set of attributes. 2. Identify the set of attributes which repeats for each value of this primary key. 3. Create a relation from the attributes which are not in the repeating group. 4. Make the key of this relation the key identified in (a). 5. Identify the primary key for the repeating group by taking each value of the primary key in (a) and identifying a unique attribute(s) in the repeating group. 6. Create a relation from the attributes in the repeating group and the primary key identified in (a). 7. Make the key for this relation the key identified in (e) and (if the key in (e) is not unique) the key identified in (a). 8. If the repeating group contains a set of attributes which repeat then apply the guidelines from (a). In this example:

Maples ESM Technologies Pvt. Ltd

Page 7 of 246

DB2

1. The primary key is emp-no. 2. The set of attributes which repeat for each value of emp-no are proj-id, proj-start-date, location, and weeks-on-project. 3. Removing these attributes from the full attribute set produces the relation: (emp-no, emp-name, dept, manager) 4. The primary key is emp-no. (emp-no, emp-name, dept, manager) 5. The primary key for the repeating group is proj_id. This is because for each emp_no the proj_id uniquely identifies the proj-start-date, location, and weeks-on-project attributes. For example, for employee 005, project A is always in Poole and weeks on project is always 11. 6. The new relation is: (emp-no, proj-id, proj-start-date, location, weeks-on-project) 7. The primary key for the repeating group, proj-id, is not unique in this relation and so the key of this relation is (emp-no, proj-id). (emp-no, proj-id, proj-start-date, location, weeks-on-project) 8. There are no more repeating groups. The first normal form relations are: employee1(emp-no, emp-name, dept, manager) emp-on-proj1(emp-no, proj-id, proj-start-date, location, weeks-on) Second Normal Form Relations which are in second normal form contain no partial key dependencies. A partial dependency occurs in a relation when a non-key attribute depends on only part of the primary key. A partial dependency can only occur in a relation with a composite key. If we have a relation in first normal form with three attributes: R(A,B,C) As the primary key is unique the following dependencies must be true: (A,B) -> C "C depends on A and B together. A and B together determine C."

Maples ESM Technologies Pvt. Ltd

Page 8 of 246

DB2

This means that each time a value of A,B occurs in the database the same values for C occurs. For example, in the above relation every time that employee 5 occurs and the project-id is A, the location is always Poole. That is, emp-id and proj-id determine the location. A partial dependency exists when only some of the attributes in a composite key are required to determine a non-key attribute. That is, a partial dependency occurs if one of the following dependencies is true: A -> C B -> C "C depends on A alone. A alone determines C." "C depends on B alone. B alone determines C."

Assuming that the dependency B->C holds then R must be decomposed into two relations: R1(A,B) R2(B,C) In the example, only one of the first normal form relations, emp-on-proj1, has a composite key and so it is the only relation which can have a partial dependency. The following dependencies are true in this relation: emp-no,proj-id -> proj-start-date, location, weeks_on The primary key determines all attributes. The project start date depends on the proj-id -> proj-start-date project and is the same for all employees. This is a problem because each tuple in emp-on-proj1 which contains the same proj-id value will also have the same proj-start-date. For example, all tuples with proj-id="A" will also have projstart-date="12-93". Therefore, we remove the proj-start-date attribute to a new relation which has a primary key composed of those attributes on which proj-start-date is partially dependent: emp-on-proj2(emp-no, proj-id, location, weeks-on) project2(proj-id, proj-start-date) The key of emp-on-proj is the same in first normal form and second normal form. The final set of second normal form relations are: employee2(emp-no, emp-name, dept, manager) emp-on-proj2(emp-no, proj-id, location, weeks-on) project2(proj-id, proj-start-date)

Maples ESM Technologies Pvt. Ltd

Page 9 of 246

DB2

Third Normal Form


Third normal form relations contain no transitive dependencies. A transitive dependency occurs when one or more attributes are determined by one or more attributes which are not part of the primary key. If we have a relation: R(A,B,C) then because the primary key determines every attribute in the relation the following dependencies must be true: A -> B A -> C "B depends on A alone. A alone determines B." "C depends on A alone. A alone determines C."

For example, in employee2, emp-no determines both emp-name, dept, and manager. If the following dependency is also true: B -> C "C depends on B alone. B alone determines C."

then R contains the transitive dependency: A -> B -> C "C depends on B and B depends on A""

This is a problem because for every value of B the attribute C will always have the same value. For example, in employee2, when the dept attribute contains "Accounts" the manager attribute always contains "Bloggs". To resolve this problem relation R should be decomposed into two relations: R1(A,B) R2(B,C) In the above example the relation employee2 contains the transitive dependency: emp-no -> dept -> manager Therefore, the employee2 relation can be decomposed into two relations: employee3(emp-no, emp-name, dept) department3(dept, manager) There are no transitive dependencies in the other relations and the final set of third normal form relations are: employee3(emp-no, emp-name, dept) department3(dept, manager) emp-on-proj3(emp-no, proj-id, location, weeks-on) project3(proj-id, proj-start-date)

Maples ESM Technologies Pvt. Ltd

Page 10 of 246

DB2

Denormalization:

Speeding the retrieval of data from DB2 tables is a frequent requirement for DBAs and performance analysts. One way to accomplish this is to denormalize DB2 tables for physical implementation. The opposite of normalization, denormalization is the process of putting one fact in many places. This speeds data retrieval at the expense of data modification. This is not necessarily a bad decision, but should be undertaken only when a completely normalized design will not perform optimally.

Maples ESM Technologies Pvt. Ltd

Page 11 of 246

DB2

Chapter 2 : Overview of DB2/UDB ver 7 for OS/390


DB2 for OS/390 and z/OS is a relational database management system that is the foundation of many e-business, business intelligence, and mission-critical systems. It is the primary focus of this certification guide. DB2 for OS/390 and z/OS is the largest of the DB2 family, often serving as an enterprise server handling many of the largest applications in the world. The environment provided by System/390 and either OS/390, or z/OS is IBMs largest and most powerful, providing the most scalable and available platform.

The DB2 Universal Database (DB2 UDB) family of products is available for S/390, zSeries, UNIX and Intel platforms. DB2 has the ability to store all kinds of electronic information. This includes traditional relational data as well as structured and unstructured binary information, documents and text in many languages, graphics, images, multimedia (audio and video), information specific to business needs such as engineering drawings, maps, insurance claims, forms, numerical control streams, or any type of electronic information. The DB2 database is an important part of IBMs e-business software portfolio. The e-business Application Framework provides an open blueprint on how to build e-business applications.

The DB2 code base is optimized for each platform to ensure maximum performance. The SQL API is common to all platforms, which allows applications written on one platform to access data on any platform. Internally, DB2 on the OS/400, VM/VSE, and OS/390 differ from Db2 on the UNIX and Intel Platforms, but it is the common SQL API that enables applications to work together. The DB2 code base on Intel and UNIX platforms are identical.

DB2 Migration from OS/390 to Z/OS


Installation is the process of preparing DB2 to operate as an OS/390 or Z/OS Subsystem. Migration is the process of upgrading from a release of DB2 to a more current release.

There are many issues when migrating to a data sharing environment, but with careful planning and testing the process can be made to go very smoothly.

Maples ESM Technologies Pvt. Ltd

Page 12 of 246

DB2

Chapter 3 : DB2 Objects


System Objects

DB2 Catalog
The DB2 catalog and directory act as central repositories for all information about objects, authorizations and communications regarding the support and operations of DB2.

The catalog is composed of several DB2 tables and can be accessed via SQL. The catalog contains details about DB2 objects obtained from the DDL. It consists of tables of data about every object defined in the DB2 system. When an object is created, altered or dropped, a row is inserted, updated or deleted in the Catalog.

DB2 Directory
The DB2 directory is used to store information regarding the operation and housekeeping of the DB2 environment, and it cannot be accessed by using SQL, as the DB2 catalog can be accessed. It contains information required to start DB2, and there are activities and utilities in the DB2 environment. Directory objects are not described in DB2 catalog

Bootstrap Dataset
Contains inventory of all active and archive log datasets. During installation of DB2, two BSDS datasets are created, and are kept in different volumes.

BSDS (Boot Strap Data Set):


It is a VSAM key sequenced data sets known to DB2. It is an inventory of all active log and archive log data set known to DB2. Db2 uses this information to track the active and archive log data set. It is an inventory of the Bufferpools used.

Maples ESM Technologies Pvt. Ltd

Page 13 of 246

DB2

Active & Archive Logs


DB2 records all data changes and significant events in active logs as they occur. In case of failure, it uses this data to recover the lost information. When the active log is full, DB2 copies the contents of the active log to a DASD or magnetic tape data set called archive logs.

Buffer Pools
Buffer pools are areas of virtual storage in which DB2 temporarily stores pages of table spaces or indexes.

When an application program accesses a row of a table, DB2 retrieves the page containing that row and places the page in a buffer, when row is required again, the application program does not have to wait for it to be retrieved from DASD, significantly reducing the cost of retrieving the page.

Locks
DB2 guarantees data integrity by using several locking mechanisms. These strategies permits multiple users from multiple environments to access and modify data concurrently without loss of data integrity.

DB2 supports locking at four levels.


Table Space Level Table Level Page Level Row Level.

DB2 uses locks to control concurrency & prevent inconsistent data.

Maples ESM Technologies Pvt. Ltd

Page 14 of 246

DB2

Data Objects
Accessed and organized by the user but controlled by DB2.

Stogroup
It is a collection of direct access volumes, all of the same device type The option is defined as a part of tablespace definition When a given space needs to be extended, storage is acquired from appropriate stogroup

Database
A collection of logically related objects - like Tablespaces, Indexspaces, Tables etc. Not a physical kind of object - may occupy more than one disk space A STOGROUP & BUFFERPOOL (is buffer area used to maintain recently accessed table and index pages) must be defined for each database. Stogroup and user-defined VSAM are the two storage allocations for a DB2 dataset definition. In a given database, all the spaces need not have the same stogroup These are, in a sense, the most physical of various storage objects in DB2 More than one volume can be defined in a stogroup. DB2 keeps track of which volume was defined first & uses that volume.

Tablespaces:
Logical address space on secondary storage to hold one or more tables A SPACE is basically an extendable collection of pages with each page of size 4K or 32K bytes. It is the storage unit for recovery and reorganizing purpose Three Type of Tablespaces - Simple, Partitioned & Segmented

Maples ESM Technologies Pvt. Ltd

Page 15 of 246

DB2

Simple Tablespaces
Can contain more than one stored table Depending on application, storing more than one Table might enable faster retrieval for joins using these tables Usually only one is preferred. This is because a single page can contain rows from all tables defined in the database. LOAD with replace option deletes all data

Segmented Tablespaces
Can contain more than one stored table, but in a segmented space A Segment consists of a logically contiguous set of n pages. Segsize parameter decides the allocation size for the tablespace No segment is allowed to contain records for more than one table Sequential access to a particular table is more efficient Mass Delete is much more efficient than in any other Tablespace Reorganizing the tablespace will restore every table to its clustered order Lock Table on table locks only the table, not the entire tablespace If a table is dropped, the space for that table can be reclaimed with minimum REORG

Partitioned Tablespaces
Primarily used for Very large tables Only one table in a partitioned TS; 1 to 64 partitions/TS Numpart parameter specifies the no. of partitions It is partitioned in accordance with value ranges for single or a combination of columns. Hence these column(s) cannot be updated Individual partitions can be independently recovered and reorganized Different partitions can be stored on different storage groups for efficient access.

Maples ESM Technologies Pvt. Ltd

Page 16 of 246

DB2

Tables
All data is stored in tables. A table is a collection of rows, all having same columns Rows are records and Columns are fields. Intersection of a column & row is a Value SQL is used to access data in DB2 tables.

Indexes
An ordered set of pointers to the data in DB2 table Stored separately from the table Each index occupies its own space Used to Improve performance; Ensure Uniqueness Multiple indexes can be defined on a table A table having a primary key will necessarily have a primary unique index.

Views
Is a virtual table derived from one or more base tables The view definition is stored in a catalog. View is an alternate way of representing data that exists in one or more tables Can include all or some of the columns from one or more base tables Indexes on Base table can improve the performance operations on the views

Maples ESM Technologies Pvt. Ltd

Page 17 of 246

DB2

Chapter 4 : Structured Query Language


Structured Query Language (SQL) is a powerful tool for manipulating data. Also, it is the standard query language for relational database management systems (RDBMS). It is not only used by DB2, but also by the other leading RDBMS products such as Oracle, Sybase and Informix.

SQL is fashioned so that the programmer can specify what data is needed but cannot specify how to retrieve it.

When a user issues the SQL request, it is sent to the DBMS. This request may need to access one or many DB2 tables. The DBMS analyses the SQL request and determine which pieces of information are necessary to resolve the users request.

One retrieval statement can return more than one row. Similarly, one modification statement can modify multiple rows.

A single SQL statement can produce an entire report.

Another feature of SQL is that it is not merely a query language. The same language can also be used to define data structures, control access to the data, and insert, modify and delete occurrences of the data. This consolidation of functions into a single language eases communication between different types of users like DBAs, system programmers, application programmers, system analysts, system designers and end users.

A simple query goes like SELECT EMPNAME FROM EMP WHERE EMPNO = 12345;

Record level processing is one where we read each and every record separately and then process the same.

SQLs are categorized based on its functionality. SQL can be used to control, define and manipulate data.

Data Definition Language (DDL) creates and maintains the physical data structure with the CREATE, DROP and ALTER verbs.

Maples ESM Technologies Pvt. Ltd

Page 18 of 246

DB2

Data Manipulation Language (DML) accesses and modifies data with the SELECT, INSERT, DELETE and UPDATE verbs.

Data Control Language (DCL) provides the control statements that govern data security with the GRANT and REVOKE verbs.

Another way to categorize SQL is by execution type. SQL can be planned and executed as embedded SQL in an application program or it can be unplanned (ad hoc).

Embedded SQLs are well defined and can be planned before the execution of the SQL. Example is batch processing.

Ad-hoc SQL is undefined until an immediate need is identified. Upon identification, an unplanned query is composed and executed. Example is information center queries.

One more way to categorize SQL is according to its dynamism. This is probably the most difficult one to define and provides the greatest flexibility of all the categories. SQL can either be static or dynamic.

Static SQL is the one, which is embedded in an application program written in a high-level language.

Dynamic SQL is either typed in at a terminal for real time execution or constructed in an application programs at runtime.

Data Types
Integer A column of whole numbers, positive or negative PIC S9 (09) COMP Smallint Decimal (x, y) PIC S9 (04) COMP 4 byte binary integer. 2 byte binary integer

A column of decimal numbers, where x is the maximum length in digits of the decimal numbers in this column, and y is the maximum number of digits allowed after the decimal point. The maximum (4, 2) number would be 99.99.

Maples ESM Technologies Pvt. Ltd

Page 19 of 246

DB2

Char (n)

A column of characters, where n is a number designating the maximum number of characters allowed (maximum length) in the column. PIC X(n).

Varchar (n)

A column of characters, where n is a number designating the maximum number of characters allowed (maximum length) in the column. 01 VAR. 49 49 Var1 Var2 PIC S9 (04) COMP. PIC X (n).

Date

PIC X (10)

YYYYMMDD 4 bytes 8 unsigned packed decimal digits HHMMSS 3 bytes - 6 unsigned packed decimal digits. YYYYMMDDHHMMSS 20 bytes - 20 unsigned packed

Time Timestamp

PIC X (08) PIC X (26) decimal digits.

DB2 Database Design

DB2 Data Types


Datatype SMALLINT INTEGER DECIMAL (X,Y) CHAR (N) VARCHAR (N) COBOL Declaration 01 Var PIC S9 (4)Comp 01 Var PIC S9(9) Comp 01 Var PIC S9(X)v(9)(Y) Comp-3 01 Var PIC X(N) 01 Var 49 Var-len PIC S9(4) Comp 49 Var-text PIC X(N) DATE TIME TIMESTAMP Numeric Character Graphics Data/Time User Defined Types 01 Var PIC X(10) 01 Var PIC X(8) 01 Var PIC X(26)

Maples ESM Technologies Pvt. Ltd

Page 20 of 246

DB2

Numeric Formats Smallint - Binary half word Integer Binary full word Decimal(x,y) - can be read as X numeric digits of which the last Y to be decimal fraction.

Character String Formats CHAR (X) - O to 255 length VARCHAR (X) - Page Size LONG VARCHAR

Date/Time Formats Date - YYYYMMDD Time - HHMMSS Time Stamp - YYYYMMDDHHMMSSNNNNNN

Nulls
Every column has a Null characteristic.(Rule for when a value is not available) NOT NULL ALLOW NULL NOT NULL WITH DEFAULT

Not Null Allow Null Not Null with Default

Value must be given If value is not given it is marked UNKNOWN If value is not given, DB2 fills the Default Value

Numeric Becomes Zero, Character Becomes Blank, Date becomes Current Date, Time becomes Current Time, Timestamp becomes Current Timestamp.

Maples ESM Technologies Pvt. Ltd

Page 21 of 246

DB2

Using Nulls
A null is used to record missing or unknown information.

For example, a table contains information on the hair color of employees. Three new employees are added today; a man with a black hair, a woman with unknown hair color and a bald man. The woman with unknown hair color and the bald man both could be assigned null HAIR_COLOR.

DB2 does not differentiate between nulls that signify unknown data.

DB2 represents null in a variable known as indicator variable. An indicator variable is defined to DB2 for each column that can accept nulls. The indicator variable must be provided while programming.

The default definition for columns in a DB2 table is to allow nulls. Nulls can be prohibited for a column by specifying the NOT NULL or NOT NULL WITH DEFAULT option in the CREATE TABLE statement.

Avoid nulls in columns that must participate in arithmetic logic. The AVG, COUNT DISTINCT, SUM, MAX & MIN functions omit column occurrences set to null. The COUNT (*) function, however, doesnt omit columns set to null because it operates on rows.

Consider these rules: Nulls are considered to be equal when duplicates are eliminated by SELECT DISTINCT or COUNT. When a nullable column participates in a calculation, the result is null. Columns that participate in a primary key cannot be null. To test for the existence of nulls, use the special predicate IS NULL in the WHERE clause of the SELECT statement. You must state WHERE column IS NULL. You can assign a column to null using the = predicate in the SET clause of the UPDATE statement.

Processing Rules Every Primary key value is unique and is not null. Every Foreign key value matches a primary key.

Maples ESM Technologies Pvt. Ltd

Page 22 of 246

DB2

Terms

Referential Constraint: The Limiting of a set of Foreign Key Values to a set of primary key values Referential Integrity: The automatic enforcement of referential constraints

DB2 Table Parameters


Data type Numeric Fixed-length string Varying-length string Date Time Timestamp Default Value Zero Blanks String of length zero Current date Current time Current timestamp

Primary Key: The primary key of a table is a column (or a combination of number of column) from that table which can be used for uniquely identifying rows in the table and it should be declared as not null column.

Candidate Key: Some tables contain more than one column (or combination of columns) that can act as a primary key. These columns possess all the properties of a primary key and are called candidate keys.

Alternate Key: A candidate key that is not the primary key of a table is called an alternate key.

Foreign Key: Identifies a row of related data in another table

EMP No Primary Key Group Dept No

EMP Name

Dept No

Salary

Foreign Key

Dept Name

Bonus

Primary Key

Maples ESM Technologies Pvt. Ltd

Page 23 of 246

DB2

Referential Integrity:
A mechanism that ensures data integrity between tables related by Primary and Foreign Keys. It is the relationships among different columns and tables in a relational database. The values in one column or set of columns refer to or must match the values in a related column or set of columns.

Referential Integrity Rules:


Insert Rules

When inserting a row with the foreign key, DB2 checks the value of the foreign key columns against the value of the primary key columns in the parent table. If no matching primary key columns are found, the insert is disallowed. A new primary key can be inserted as long as it is unique.

You cannot insert a row into a dependent table unless there is a row in the parent table with a parent key value equal to the foreign key value of the row that is being inserted unless the foreign key value is null. If an INSERT operation fails for one row during an attempt to insert more than one row, all rows inserted by the statement are removed from the database.

Update Rules

When updating foreign key values, DB2 performs the same checks as when it is inserting a row with a foreign key.

Delete Rules When a row with a primary key is deleted what should be done about the rows with matching foreign keys Designer chooses one of CASCADE, SET NULL, RESTRICT Cascade When a row of the parent table is deleted, any related rows in the dependent table are also deleted.

Maples ESM Technologies Pvt. Ltd

Page 24 of 246

DB2

Restrict Rows of parent table that have dependent rows cannot be deleted. Set Null When a row of a parent is deleted, the corresponding values of the foreign key in any dependent rows are set to null.

Data Definition Language


Let us consider for our discussions EMP table and DEPT table. How can we create DEPT table and EMP table?

CREATE STATEMENT DEPT TABLE CREATE TABLE DEPT (DEPTNO CHAR(4) NOT NULL PRIMARY KEY, DEPTNAME CHAR(10) NOT NULL) IN <DBNAME>.<TS-NAME>

If you do not give a database name and a tablespace name the table would get created in the default database for which users may not have permissions. So ask your DBA the database name and tablespace name and then create the table. In the DEPT table created above we have mentioned the deptno as the primary key. The primary key has to be declared as NOT NULL. Primary key will not allow any duplicates. So the table should have an UNIQUE INDEX on the column defined as primary key - otherwise the table definition would be incomplete and DB2 does not allow any manipulations on the table.

So the next step is to create a unique index CREATE UNIQUE INDEX inddept on DEPT (DEPTNO);

Now the table definition becomes complete and DB2 allows you to start your operations on the table. Let us create the EMP table that contains a Foreign Key to the DEPT table.

CREATE STATEMENT EMP TABLE CREATE TABLE EMP (EMPNO CHAR(4) NOT NULL PRIMARY KEY,

Maples ESM Technologies Pvt. Ltd

Page 25 of 246

DB2

EMPNAME CHAR(10) NOT NULL, DEPTNO CHAR(4), SALARY DECIMAL(7,2) NOT NULL FOREIGN KEY(DEPTNO) REFERENCES DEPT ON DELETE CASCADE) IN <DBNAME>.<TS-NAME>

ALTER STATEMENT ALTER TABLE DEPT ADD PRIMARY KEY (DEPTNO);

ALTER TABLE DEPT DROP PRIMARY KEY;

ALTER ADD

TABLE NOOFEMP

DEPT SMALLINT;

DROP STATEMENT DROP TABLE DEPT;

Data Manipulation Language (DML)


SQL Single row INSERT INSERT INTO DEPT VALUES(D001,FINANCE)

INSERT INTO EMP VALUES(E001,ABC,D001,25000)

INSERT INTO EMP(EMPNO,EMPNAME,SALARY) VALUES (E002, DEF, 21000)

INSERT INTO EMP VALUES(E003,UVW, NULL, 14000)

Maples ESM Technologies Pvt. Ltd

Page 26 of 246

DB2

UPDATE a value in single row UPDATE EMP SET DEPTNO = D002 WHERE EMPNO = E002;

UPDATE multiple values in a single row UPDATE EMP SET DEPTNO = D003, SALARY=SALARY +1000 WHERE EMPNO = E003;

UPDATE multiple rows using a single UPDATE statement

UPDATE WHERE

EMP SET SALARY + 1000 DEPTNO = D001;

DELETE single row DELETE FROM EMP WHERE EMPNO=E001

DELETE multiple rows DELETE FROM EMP WHERE SALARY > 20000

DELETE ALL rows DELETE FROM EMP

Selection and Projection

The selection operation retrieves a specified subset of rows from a DB2 table. WHERE clause is to specify the search criteria. SELECT * FROM EMP WHERE DEPTNO = D001;

To retrieve all rows from a table, discard the WHERE clause from the statement.

The projection operation retrieves a specified subset of columns from a given DB2 table. Projection retrieves all of the rows but only the specified columns.

SELECT EMPNAME, DEPTNO, SALARY FROM EMP;

Maples ESM Technologies Pvt. Ltd

Page 27 of 246

DB2

To be simpler, the selection operation determines which rows are retrieved and the projection operation determines which columns are retrieved.

In most cases, queries combine selection and projection to retrieve data.

The following SQL statement combines the selection and projection operations in the preceding two examples. SELECT EMPNAME, DEPTNO, SALARY FROM EMP WHERE DEPTNO = D001;

Simple Retrieval SELECT * FROM EMP;

Unique Retrieval SELECT DISTINCT DEPTNO FROM EMP;

Computed Values Retrieval SELECT EMPNO, SALARY * 1.1 FROM EMP;

Qualified Retrieval SELECT EMPNO FROM EMP WHERE DEPTNO= D001;

Retrieval with Ordering SELECT EMPNO, SALARY FROM EMP ORDER BY DEPTNO;

SELECT EMPNO, SALARY FROM EMP ORDER BY DEPTNO DESC;

Retrieval using BETWEEN SELECT EMPNO FROM EMP WHERE SALARY BETWEEN 10000 AND 150000

Maples ESM Technologies Pvt. Ltd

Page 28 of 246

DB2

THE ABOVE QUERY CAN ALSO BE WRITTEN AS

SELECT EMPNO FROM EMP WHERE SALARY >= 10000 AND SALARY <=15000

Retrieval using NOT BETWEEN SELECT EMPNO FROM EMP WHERE SALARY NOT BETWEEN 10000 AND 15000;

THE ABOVE QUERY CAN ALSO BE WRITTEN AS

SELECT EMPNO FROM EMP WHERE SALARY < 10000 OR SALARY >15000

Retrieval using IN SELECT EMPNO FROM EMP WHERE DEPTNO IN (D001,D002)

THE ABOVE QUERY CAN ALSO BE WRITTEN AS

SELECT EMPNO FROM EMP WHERE DEPTNO = D001 OR DEPTNO=D002

AND & OR can be combined, for example: SELECT EMPNO FROM EMP WHERE DEPTNO = 'D001' OR DEPTNO =D002 AND SALARY > 60000;

First, SQL finds the rows where the salary is greater than $60,000 and the department number is D002. Then it also finds out the list of rows where the department number is D001. Note that the AND operation is done first.

To generalize this process, SQL performs the AND operation to determine the rows where the AND operation holds true (remember: all of the conditions are true). Then, these results are used to compare with the OR conditions, and display those remaining rows where any of the conditions joined by the OR operator holds true. Mathematically, SQL evaluates all of the conditions, then evaluates the AND "pairs", and then evaluates the OR's (where both operators evaluate left to right).

Maples ESM Technologies Pvt. Ltd

Page 29 of 246

DB2

True AND False OR True AND True OR False AND False First simplify the AND pairs: False OR True OR False Now do the OR's, left to right: True OR False True

The result is True, and the row passes the query conditions. Be sure to see the next section on NOT's, and the order of logical operations. To perform OR's before ANDs, like if you wanted to see a list of employees who belong to either department D001 or in D002 but their salary should be greater than 60000, use parentheses: SELECT EMPNO FROM EMP WHERE (DEPTNO = 'D001' OR DEPTNO =D002 )AND SALARY > 60000;

Retrieval using LIKE SELECT EMPNAME,DEPTNO FROM EMP WHERE EMPNAME LIKE A%;

SELECT EMPNAME,DEPTNO FROM EMP WHERE EMPNAME LIKE _A%;

% MATCHES ZERO OR MORE CHARACTERS _ (UNDERSCORE) MATCHES SINGLE CHARACTER

Retrieval using NOT LIKE SELECT EMPNAME FROM EMP WHERE EMPNAME NOT LIKE E%;

Retrieval involving NULL SELECT NAME FROM EMP WHERE DEPTNO is NULL;

Retrieval involving NOT NULL SELECT NAME FROM EMP WHERE DEPTNO is NOT NULL;

Maples ESM Technologies Pvt. Ltd

Page 30 of 246

DB2

COLUMN and SCALAR functions


COLUMN functions

Column functions compute from a group of rows, a single value. They are AVG, COUNT, MAX, MIN and SUM.

AVG

The AVG function computes the average of the column or expression

specified as an argument. This function operates only on numeric arguments.

SELECT AVG (SALARY) FROM EMP;

The above calculates the average salary of all employees.

COUNT -

The COUNT function counts the number of rows in a table, or the number of

distinct values for a given column. It can operate, therefore, at the column or row level. The syntax differs for each.

To count the number of rows in the EMP table, issue this SQL statement:

SELECT COUNT (*) FROM EMP;

To count the number of distinct departments represented in the EMP table, issue the following:

SELECT COUNT (DISTINCT DEPTNO) FROM EMP;

MAX

The MAX function returns the largest value in the specified column. The following

SQL statement determines the project with the latest end date.

SELECT MAX (SALARY) FROM EMP;

MIN

The MIN function returns the smallest value in the specified column. To retrieve

the lowest bonus given to any employee, issue this SQL statement.

SELECT MIN (SALARY) FROM EMP;

Maples ESM Technologies Pvt. Ltd

Page 31 of 246

DB2

SUM

The accumulated total of all values in the specified column are returned by the

SUM column function.

For example, the following SQL statement calculates the total salary for all the employees:

SELECT SUM (SALARY) FROM EMP;

Some rules for the column functions: Column functions can be executed only in SELECT statements. Each column function returns only one value for the set of selected rows. The result of any column function (except the COUNT function) will have the same date type as the column to which it was applied. The COUNT function returns an integer number. The result of any column function (except the COUNT function) can be null. COUNT always returns a numeric result. Column functions will not return a SQLCODE of +100 if the predicate specified in the WHERE clause finds no data. Instead, a null is returned.

For example, consider the following SQL statement: EMP WHERE EMPNO = 999999;

SELECT MAX (SALARY) FROM

There is no employee with an EMPNO of 999999 in the EMP table. This statement therefore returns a null for the MAX (SALARY). When using the AVG, MAX, MIN and SUM functions on nullable columns, all occurrences of null are eliminated before applying the function. You can use the DISTINCT keyword with all column functions to eliminate duplicates before applying the given function. DISTINCT has no effect, however on the MAX and MIN functions. You can use the ALL keyword to indicate that duplicates should not be eliminated. ALL is the default.

Maples ESM Technologies Pvt. Ltd

Page 32 of 246

DB2

SCALAR functions

Scalar functions are applied to a column or expression and operate on a single value.

There are 22 scalar functions, each of which can be applied to a column value or expression.

CHAR

Converts a DB2 date, time, timestamp, or decimal value to a character value.

COALESCE

For nullable columns, returns a value instead of a null (equivalent to the VALUE function).

DATE

Converts a value representing a date to a DB2 date. The value to be converted can be a DB2 timestamp, a DB2 date, a positive integer or a character string.

DAY DAYS

Returns the day portion of a DB2 date or timestamp. Converts a DB2 date or timestamp into an integer value representing one more than the number of days since January 01, 0001.

DECIMAL DIGITS

Converts any numeric value to a decimal value. Converts a number to a character string of digits. Beware that the DIGITS function will truncate the negative sign for negative numbers.

FLOAT HEX HOUR INTEGER

Converts any numeric value to a floating-point value. Converts any value other than a long string to a hexadecimal. Returns the hour portion of a time, a timestamp, or duration. Converts any number to an integer by truncating the portion of the number to the right of the decimal point. If the whole number of the portion is not a valid integer, an error results.

LENGTH

Returns the length of any column, which may be null. Does not include the length of null indicators, but does include trailing blanks for character columns.

NULLIF

Returns a null when two specified expressions are equal; if not equal, the first expression is returned.

MICROSECOND MINUTE MONTH SECOND

returns the microsecond portion of a timestamp. Returns the minute portion of a time, timestamp or duration. Returns the month portion of a time, timestamp or duration. Returns the second portion of a time, timestamp or duration.

Maples ESM Technologies Pvt. Ltd

Page 33 of 246

DB2

STRIP

Returns the leading, trailing, or both leading and trailing blanks from a string expression.

SUBSTR

Returns the specified portion of a character column from any starting point to any ending point.

TIME

Converts a value representing a valid time to a DB2 time. The value to be converted can be a DB2 timestamp, a DB2 time, or a character string.

TIMESTAMP

Obtains a timestamp from another timestamp, a valid character string representation of a timestamp, or a combination of date and time values.

VALUE

For nullable columns, returns a value instead of a null (equivalent to COALESCE function).

VARGRAPHIC YEAR

Converts a character string to a graphic string. Returns the year portion of a date, a timestamp or duration.

Some rules for the scalar functions: Scalar functions can be executed in the select list of the SQL SELECT statement or as part of a WHERE or HAVING clause. The argument for a scalar function can be a column function.

Sorting and Grouping


SQL can also sort and group retrieved data. The ORDER BY clause sorts the results of a query in the specified order (ascending or descending) for each column. The GROUP BY clause collates the resultant rows to apply functions that consolidate the data.

For example, the following query groups employee data by department, returning the aggregate salary for each department.

SELECT DEPTNO, SUM (SALARY) FROM EMP GROUP BY DEPTNO;

By adding a HAVING clause to this query, you can eliminate aggregated data that is not required.

Maples ESM Technologies Pvt. Ltd

Page 34 of 246

DB2

For example, if you are interested in departments with an average salary of less than $17, 500, you can code the following query:

SELECT

DEPTNO, SUM (SALARY)

FROM EMP GROUP BY DEPTNO HAVING AVG (SALARY) < 17500;

The GROUP BY clause does not sort the data for the result set; it only consolidates the data values for grouping. To return the results of this query in a particular order, you must use the ORDER BY clause.

For example, to order the resultant data into descending department number order,

SELECT

DEPTNO, SUM (SALARY)

FROM DEP GROUP BY DEPTNO HAVING AVG (SALARY) < 17500 ORDER BY DEPTNO;

The ORDER BY, GROUP BY, HAVING clauses are important SQL features that can increase productivity.

The Difference between HAVING and WHERE

The WHERE and HAVING clauses are similar in terms of functionality. However, they operate on different types of data.

Any SQL statement can use a WHERE clause to indicate which rows of data are to be returned.

The HAVING clause operates on aggregated groups of information. Only SQL statements that specify the GROUP BY clause can use the HAVING clause. The predicates in the HAVING clause are applied after the GROUP BY has been applied.

If both a WHERE clause and a HAVING clause are coded on the same SQL statement, the following occurs:

Maples ESM Technologies Pvt. Ltd

Page 35 of 246

DB2

The WHERE clause is applied to the detail rows. The GROUP BY is applied to aggregate the data. The HAVING clause is applied to the aggregate rows.

Consider the following SQL:

SELECT

DEPTNO, AVG (SALARY) FROM EMP

WHERE DEPTNO NOT IN (D001, D002) GROUP BY DEPTNO HAVING COUNT (*) > 1; This query will return the average salary for each department except D001 and D002, as long as the department has more than 1 employee. The steps DB2 take to satisfy this query are: Apply the WHERE clause to eliminate departments D001 and D002. Apply the GROUP BY clause to aggregate the data by department. Apply the HAVING clause to eliminate any department groups consisting of only one employee.

Joins & Sub Queries


Cartesian Products

A Cartesian product is the result of a join that does not specify matching columns.

SELECT

* FROM DEPT, EMP;

This query combines every row from the DEP table with every row in the EMP table. All the columns of the DEP table and all the columns of the EMP table are included in the Cartesian product.

When a table with 100 rows is joined as a Cartesian product with a table having 10 rows, the result is 100x10 rows, 1000 rows (since no criteria were specified). Avoid Cartesian products.

Maples ESM Technologies Pvt. Ltd

Page 36 of 246

DB2

Joins

The art of combining data from multiple tables is called joining. A join also called inner join matches the data from two or more tables, based on the value of one or more columns in each table. All matches are combined, creating a resulting row that is the concatenation of the column from each table where the specified columns match.

Although, the maximum number of tables that can be joined in a single SQL statement is 15, the practical limit is usually fewer.

For example, to query employees and their department names, the EMP table is joined to the DEP table.

SELECT

EMPNO, EMPNAME, DEPTNO, DEPTNAME

FROM EMP, DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO;

The above query can also be written as SELECT FROM EMP JOIN DEP ON EMP.DEPTNO=DEPT.DEPTNO EMPNO, EMPNAME, DEPTNO, DEPTNAME

SELECT FROM EMP INNER JOIN DEP

EMPNO, EMPNAME, DEPTNO, DEPTNAME

ON EMP.DEPTNO=DEPT.DEPTNO

Here, the employee table is joined to the department table using a department code that exists as a column in both the tables (DEPTNO in the employee table and DEPTNO in the department table)

The INNER keyword will be assumed even if not said.

Consider these two tables EMP and DEPT.

Maples ESM Technologies Pvt. Ltd

Page 37 of 246

DB2

EMP

EMPNO E001 E002 E003 E004

EMPNAME A B C D

DEPNO D001 D002 D001 NULL

SALARY 12000 15000 11000 21000

DEPT

DEPTNO D001 D002 D003

DEPNAME FINANCE ACCOUNTS SALES

i) Inner join -

When two tables are brought close by inner join, those rows in which the

columns are common to both the tables are highlighted.

SELECT FROM EMP INNER JOIN DEP

EMPNAME,DEPTNAME

ON EMP.DEPTNO=DEPT.DEPTNO

EMPNAME E001 E002 E003

DEPNAME FINANCE ACCOUNTS FINANCE

ii) Outer join - When tables are joined, the rows that are returned contain matching values for the columns specified in the join predicates. Sometimes, it is desirable to return both matching and non-matching rows for one or more of the tables being joined. This is known as an outer join.

a) Left outer join - This invokes an outer join, returning all the rows from the table on the left side of the join and the corresponding values in the table on the right side of the join. Also, the missing values in the result set will be filled with nulls.

Maples ESM Technologies Pvt. Ltd

Page 38 of 246

DB2

SELECT FROM EMP

EMPNAME, DEPTNAME

LEFT OUTER JOIN DEP ON EMP.DEPTNO=DEPT.DEPTNO

EMPNAME E001 E002 E003 E004

DEPNAME FINANCE ACCOUNTS FINANCE NULL

b) Right outer join -

An outer join, returning all the rows from the table on the right side of the

join and the corresponding values in the table on the left side of the join. Also, the missing values in the result set will be filled with nulls.

SELECT FROM EMP

EMPNAME,DEPTNAME

RIGHT OUTER JOIN DEP ON EMP.DEPTNO=DEPT.DEPTNO

EMPNAME E001 E002 E003 NULL

DEPNAME FINANCE ACCOUNTS FINANCE SALES

c) Full outer join - Like all previous outer joins, it returns matching rows from both the tables. In addition, it returns non-matching rows from both tables, left and right. A full outer join can use only the equal (=) operator. Left and right outer joins are able to use all the comparison operators.

SELECT FROM EMP

EMPNAME, DEPTNAME

FULL OUTER JOIN DEP ON EMP.DEPTNO=DEPT.DEPTNO

Maples ESM Technologies Pvt. Ltd

Page 39 of 246

DB2

EMPNAME E001 E002 E003 NULL E004

DEPNAME FINANCE ACCOUNTS FINANCE SALES NULL

SUBQUERIES

A subquery is a SELECT statement within a condition of a SELECT statement. Other words for subquery are subselect or innerselect.

SQL facilitates us to nest SELECT statements. When one or more SELECT statements are nested in another SELECT statement, the query is referred to as subquery. A subquery enables a user to base the search criteria of one SELECT statement on the results of another SELECT statement.

One SELECT statement is connected to another in one of these ways: Using the IN or NOT IN predicate, Using the EXISTS or NOT EXISTS predicate, Specifying the equality predicate (=) or the inequality predicate (<>) Specifying a predicate using a comparative operator (<, <=, =>, >)

The following SELECT statement is an example of a SQL subquery. SELECT WHERE * FROM EMP SALARY > (SELECT SALARY FROM EMP WHERE EMPNO = E001);

DB2 evaluates this SQL statement by first evaluating the nested SELECT statement to retrieve the salary of employee with an employeenumber E001. It then matches the rows in the EMP table that have salaries more than E001s salary retrieved by the nested SELECT.

The following example shows an alternate way of nesting SELECT statements, by means of an equality predicate.

SELECT

EMPNO, EMPNAME FROM EMP

WHERE DEPTNO = (SELECT DEPTNO FROM DEPT WHERE DEPTNAME = FINANCE);

Maples ESM Technologies Pvt. Ltd

Page 40 of 246

DB2

DB2 processes this SQL statement by retrieving the proper DEPTNO with the nested SELECT statement that is coded to search for the FINANCE department. It then matches rows in the EMP table that correspond to the DEPTNO of the FINANCE department. This match produces a result table that lists all employees in the FINANCE department.

Ofcourse, it also assumes that there is only one PLANNING department. If there were more, the SQL statement would fail because the nested SELECT statement can return only one row when the = predicate is used.

Another method of subquery, called a correlated subquery permits the nested SELECT statement to refer back to the columns in the previous SELECT statement.

SELECT WHERE = B.DEPTNO);

A.DEPTNO, A.EMPNO, A.SALARY FROM EMP A A.SALARY > (SELECT AVG (B.SALARY) FROM EMP B WHERE A.DEPTNO

This subquery differs from a normal subquery in the way that the nested SELECT statement refers back to the table in the first SELECT statement.

In the nested SELECT statement, in the condition part, we employ A.WORKDEP through which we are referring the table in the first SELECT EMP A.

A non-correlated subquery is processed in bottom-to-top fashion. The bottom most query is initiated first and based on the results, the top most query is resolved.

A correlated subquery works in a top-bottom-top fashion. The topmost query is analyzed, and based on the analysis the bottommost query is triggered. The bottom most query, however relies on the topmost query to evaluate.

Joins Vs Subqueries
Lets look at a subquery here.

SELECT FINANCE);

EMPNO, EMPNAME FROM EMP DEPT WHERE DEPTNAME =

WHERE DEPTNO = (SELECT DEPTNO FROM

Maples ESM Technologies Pvt. Ltd

Page 41 of 246

DB2

Now, we replace the same query above by a join.

SELECT FROM EMP JOIN WHERE

EMPNO, EMPNAME DEPT DEPT.DEPTNAME = FINANCE;

EMP.DEPTNO = DEPT.DEPTNO AND

Though the system doesnt have any problem dealing with join or subquery, from the users point of view, it is easy to understand joins rather than subqueries.

Union
The Union operation combines two sets of rows into a single set composed of all the rows in either or both of the two original sets. The two original sets must be union-compatible.

For union compatibility: The two sets must contain the same number of columns. Each column of the first set must be either the same data type as the corresponding column of the second set or convertible to the same data type as the corresponding column of the second set. In this form, the union of two sets doesnt have any duplicates at all. EMPNAME = DRAVID UNION

SELECT

EMPNO FROM EMP A WHERE

SELECT EMPNO FROM EMP A WHERE DEPTNO = D001; While using the UNION operation in the same table, we can also use OR. The advantage of using OR is that the users can understand easily. Also, OR tends to outperform UNION. The above query is rewritten using OR.

SELECT

EMPNO FROM EMP A

WHERE EMPNAME = DRAVID OR DEPTNO = D001;

Maples ESM Technologies Pvt. Ltd

Page 42 of 246

DB2

View
Is like a window through which data and tables can be viewed or changed. Derived from another table or another view which stores data physically Stored as a SELECT statement only-it is a virtual table that does not physically exist in its own right, but appears to the user as if it does. A view has no data it manipulates data in the underlying base table Allows the same data to be seen by different users in different views. A view cannot contain an order by clause - orderby is specified when select clause is given.

Syntax CREATE VIEW EMP1 AS SELECT EMPNO,EMPNAME FROM EMP;

Example Create a view from the tables DEPT and EMP, which would store the department name, minimum salary, maximum salary and average salary for every department.

Solution

CREATE VIEW DEPT_SUMMARY (NAME,MINSAL,MAXSAL,AVGSAL) AS SELECT DEPTNAME, MIN(SAL), MAX(SAL).AVG(SAL) FROM EMP,DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO GROUP BY DEPT.DEPTNO;

Modifying a View In order to modify a view you simply drop and re-create it. You cannot alter a view.

Removing a View DROP VIEW EMP_VIEW2

Maples ESM Technologies Pvt. Ltd

Page 43 of 246

DB2

ALIAS An alias is a substitute for the three-part name of a table or view. The alias can be up to 18 characters long, qualified by an owner ID.

CREATE

ALIAS

TESTTAB

FOR

locationname.userid.EMP;

SYNONYM An alternative name for a table or view. Synonyms can only be used to refer to objects at the subsystem in which the synonym is defined.

Eg : CREATE

SYNONYM DEPT

FOR

userid.DEPT;

SPUFI (SQL Processor Using File Input)


This supports the online execution of SQL statements from a TSO terminal. You can create a text file with SQL statements (using ISPF editor), then execute that file (via SPUFI) and then use ISPF browse to browse through the results of those statements which will be in another text file.

QMF (Query Management Facility)


IBMs Query Management Facility is an interactive query tool used to produce formatted query output. QMF enables you to submit SQL queries dynamically, much like DB2Is SPUFI facility. Using a mechanism called a QMF form, you can format the results of your SQL queries into professional-looking reports.

You invoke QMF by choosing an option from the ISPF main menu.

You can use three basic QMF objects to produce formatted reports of DB2 data: Queries, forms and procs.

F6 F9 F10

Query. Form. Proc.

Maples ESM Technologies Pvt. Ltd

Page 44 of 246

DB2

Press F6 will fetch you the QMF Query panel. Type in a query. To run this query, press F2. A report is prepared. Printing this report can be accomplished by F4. Formatting the report is done by F9. When you say F9, the report form appears. A default form is generated for each query when it is run.

The third QMF object, the QMF Proc, is another important feature of QMF.

A QMF query can contain only one SQL statement. This is contrast to that of SPUFI, which can contain multiple SQL statements.

To execute multiple SQL statements at one time, you use a QMF Proc. QMF Procs contains QMF commands that are tied together and executed serially.

Using QMF is a quick way to produce high-quality professional reports.

A QMF session goes as follows: Enter QMF and the QMF Home Panel appears. Press F6 to display the QMF Query panel. Code the SQL SELECT statement. Press F2 to display the QMF Report panel. Execute the SQL statement to produce the report. Press F9 to display the QMF Form panel. Modify the report parameters and headings as needed. Press F12 to display the QMF Report panel. Print the final formatted report.

Maples ESM Technologies Pvt. Ltd

Page 45 of 246

DB2

Chapter 5 : DB2 Interfaces

DCLGEN
DCLGEN, the declarations generator supplied with DB2, produces a DECLARE statement for the use in an Embedded SQL applications program to produce a Cobol copy book which contains SQL DECLARE TABLE statement along with the WORKING-STORAGE host-variable definitions for each column of the table. When the DCLGEN command is issued DB2 reads the catalog to determine the structure of the table and builds the COBOL copybook.

The source table name and the dataset name for the copybook has to be entered during DCLGEN, invoked from the DB2I panel. Issued for a single table. Prepares the structure of the table in a COBOL copybook The copybook contains a SQL DECLARE TABLE statement along with a working storage host variable definition for the table

Note: DCLGEN can be used only on an existing table or view table.

The DCLGEN must be used and the DCLGEN name of the table or view must be supplied before the program is precompiled. In order to use the declarations generated by DCLGEN in the program, the SQL INCLUDE statement is used. The example below shows this INCLUDE statement for the CAND DCLGEN

EXEC SQL INCLUDE CAND;

DB2 must be active before DCLGEN can be used. It can be started in different ways:

From ISPF through DB2I: Select the DCLGEN option on the DB2I Primary Option Menu panel. Next, fill in the DCLGEN panel with the information it needs to built the declarations, press ENTER.

INCLUDE: The INCLUDE statement is used to generate the DCLGEN in the application program at the run time.

Maples ESM Technologies Pvt. Ltd

Page 46 of 246

DB2

Chapter 6 : DB2 Application Development Overview

DB2 Program Preparation Steps


Issue the DCLGEN command

DCLGEN - to invoke the declarations generator program.

Issue the DCLGEN command for a single table. On a table-by-table basis, DCLGEN produces a module that can be included in DB2 application programs. It reads the DB2 catalog to determine the structure of the table and builds a copybook for the host language. The copybook contains a SQL DECLARE TABLE statement along with WORKING-STORAGE host variable definitions for each column in the table.

DCLGEN is not a required step because the DECLARE TABLE statement and corresponding host variables could be hard coded in the application program. Skipping this step is not recommended. Run the DCLGEN command for every table that will be embedded in a COBOL program. Then every program that accesses that table should be required to INCLUDE the generated copybook as the only means of declaring that table for embedded use.

For the EMPTABL copybook, use the following include statement:

EXEC SQL INCLUDE EMPTABL END-EXEC.

DB2 must be running to invoke the DCLGEN command. A sample DCLGEN for the DEP table is as follows:

DCLGEN

TABLE (EMP) LIBRARY (XXX.DB2.CNTL (DCLEMP)) ACTION (REPLACE) QUOTE

EXEC SQL

DECLARE EMP TABLE CHAR (4) NOT NULL,

(EMPNO

Maples ESM Technologies Pvt. Ltd

Page 47 of 246

DB2

EMPNAME DEPTNO SALARY END-EXEC.

CHAR (10) CHAR (4),

NOT NULL,

DECIMAL(7,2) NOT NULL)

*** COBOL DECLARATION FOR TABLE EMP *** 01 DCLEMP. 10 10 10 10 EMPNO EMPNAME DEPTNO SALARY PIC X(4). PIC X(10). PIC X (4). PIC S9(5)V99 COMP-3.

The DCLGEN process gives the conversion of DB2 datatypes into equivalent COBOL datatypes as follows: DB2 SMALLINT INTEGER (or) INT DECIMAL(5,2) (or) DEC(5,2) FLOAT(21) (or) REAL FLOAT (or) FLOAT (53) (or) DOUBLE PRECISION CHAR(10) COBOL 01 N1 PIC S9(4) COMP 01 N1 PIC S9(9) COMP 01 N1 PIC S9(3) V 9(2) COMP-3 01 N1 COMP-1 01 N1 COMP-2 01 N1 PIC X(10) 01 STR1 VARCHAR (80) 02 STR1-LEN PIC S9(4) COMP. 02 STR1-TXT PIC X(80). GRAPHIC(5) 01 N1 PIC G(5) DISPLAY-1 01 STR2 VARGRAPHIC(40) 02 STR2L PIC S9(4) COMP. 02 STR2C PIC G(40) DISPLAY-1.

DB2 DATE TIME TIMESTAMP

COBOL 01 N1 PIC X(10) 01 N1 PIC X(8) 01 N1 PIC X(26)

Maples ESM Technologies Pvt. Ltd

Page 48 of 246

DB2

As shown above, the DCLGEN command produces a DECLARE TABLE statement and a COBOL field layout for DB2 host variables that can be used with the table. The output from DCLGEN is stored as a member of a partitioned dataset from which it can be copied into an application program by means of an embedded SQL INCLUDE statement.

S o urce P ro gra m

M odi fie d So urc e N o n-SQ L

D B2 P rec o mpi le r o r H ostL a n gu a ge C o m p ile r

SQ L

C o m p ila tio n D B2 C a ta lo g L i nk E dit

D BRM

B ind

P ac ka ge / P la n

L oa d M o d ul e

Plan

Pre-compilation
The precompiler prepares the source program for compilation by replacing EXEC SQL by a CALL and by putting the SQL in comment. The precompiler performs the following: Includes DCLGEN member Includes SQLCA Looks for SQL statements and for host variable definitions Verifies the SQL syntax Matches each column and table name in the SQL to the DECLARE TABLE statements. Prepares the SQL for compilation or assembly in the host language Produces a DBRM and stores it in a PDS Can be invoked in DB2I or in batch.

Maples ESM Technologies Pvt. Ltd

Page 49 of 246

DB2

DBRM
A Data Base Request Module is nothing more than a module containing SQL statements

extracted from a source program by the DB2 precompiler. It is stored as a member of a partitioned data set. It is not stored in the DB2 Catalog or DB2 Directory. Although a DB2 Catalog table named SYSIBM. SYSDBRM exists, it does not contain the DBRM. It also does not contain every DBRM created by the precompiler.

When a DBRM is bound into a plan, all its SQL statements are placed into the SYSIBM.SYSSTMT DB2 catalog table. When a DBRM is bound into a package, all its SQL statements are placed into the SYSIBM.SYSPACKSTMT table.

Binding
The bind process establishes a relationship between an application program and its relational data. This step is necessary before a program can be executed. DB2 allows two basic ways of binding a program: to a package, or directly to an application plan.

The bind process performs the following Checks SQL syntax Checks security (validity & authorization) Compares column/table names against DB2 catalog Builds access path strategy for each SQL statement.

Issue the BIND command

The DBRM goes through a process by name BIND to produce an executable plan or package.

The BIND command is a type of compiler for SQL statements. In general, BIND reads SQL statements from DBRMs and produces a mechanism to access data as directed by the SQL statements being bound.

Two types of binds: BIND PLAN and BIND PACKAGE.

Maples ESM Technologies Pvt. Ltd

Page 50 of 246

DB2

What Is a Plan?
A plan is an executable module containing the access path logic produced by the DB2 optimizer. It can be composed of one or more DBRMs and packages.

BIND

PLAN (PLAN1) MEMBER (PROGRAM1, PROGRAM2, PROGRAM3) LIBRARY (MTRGIT.DBRMLIB) QUALIFIER (TRG001) OWNER (TRG001)

Plans are created by the BIND command. When a plan is bound, DB2 reads the f DB2 catalog tables:

SYSIBM.SYSCOLDIST

The DB2 catalog stores only information about the plans.

What Is a Package?
A package is a single, bound DBRM with optimized access paths, by using packages, the table logic is packaged at a lower level of granularity, at the package (or program) level.

To execute a package, you first must include it in the package list of a plan. Packages are not directly executed they are only indirectly executed when the plan in which they are contained executes (as discussed previously, UDFs and triggers are exceptions to this rule). A plan can consist of one or more DBRMs, one or more packages, or a combination of packages and DBRMs.

To help differentiate between plans and packages, consider a grocery store analogy. Before going to the grocery store, you should prepare a shopping list. As you go through the aisles, when you find an item on your list, you place the item in your shopping cart. After your paying for the items at the check-out register, the clerk places your grocery items in a bag. You can think of the purchased items as DBRMs. The bag is the plan. You have multiple DBRMs (grocery items) in your plan (Shopping bag).

Maples ESM Technologies Pvt. Ltd

Page 51 of 246

DB2

Name of the package is same as the name of the DBRM. BIND PACKAGE (COLLECTION1)

To execute a package, you must first include it in the package list of a plan. Packages are never directly executed they are only indirectly executed when the plan in which they are contained executes.

A plan can consist of one or more DBRMs, one or more packages, or a combination of packages and DBRMs.

The plan contains a list pointing to the physical location of the packages and one or more DBRMs.

Package information is stored in its own DB2 catalog tables. When a package is bound, DB2 reads the DB2 catalog tables:

Information about the package is then stored in the DB2 catalog tables:

The DB2 catalog stores only information about the packages.

A package contains a location identifier, a collection identifier and a package identifier.

The location identifier specifies the site at which the package was bound. The collection identifier represents a logical grouping of packages. The package identifier is the DBRM name bound into the package. This ties the package to the program to which it applies.

A Package also contains a location identifier, a collection identifier, and a package identifier. The location identifier specifies the site at which the package was bound. If your processing is local, you can forgo the specification of the location ID for packages.

LOCATION.COLLECTION.PACKAGE

One final consideration when using packages is versioning. A package can have multiple versions, each with its own version identifier. The version identifier is carried as text in the DBRM, and is covered in more depth in the Package version Maintenance section.

Maples ESM Technologies Pvt. Ltd

Page 52 of 246

DB2

Package Benefits:

Reduced bind time is the package benefit most often cited. When you are utilizing packages and the SQL within a program changes, only the package for that particular program needs to be rebound. If packages are not used when multiple DBRMs are bound into a plan and the SQL within one of those programs changes, the entire plan must be rebound. This wastes time because you must still rebind all the other DBRMs in that plan that did not change.

Another benefit of packages involves the granularity of bind parameters. With packages, you can specify your bind options at the program level because many of the bind parameters are now available to BIND PACKAGE command, such as the ISOLATION level and RELEASE parameters. By specifying different parameters for specific packages and including these packages in a plan, many combinations of isolation level and release are possible. You can, for example, create a single plan that provides an isolation level of cursor stability (CS) for one of its packages and an isolation level of repeatable read (RR) for another package. This combination of strategies is not possible in a plan-only environment.

The third benefit, versioning, probably is the biggest benefit of all. Packages can be versioned, thus enabling you to have multiple versions of the same package existing at the same time in the DB2 Catalog. Simply by running the appropriate lad module, DB2 chooses the correct package to execute. DB2 uses a package selection algorithm to execute the correct access path.

Packages also provide improved support for mirror tables. Because a package has a high level qualifier of collection, you can specify a collection for each of your mirror table environments. Suppose that you have an environment in which you have current and history data in separate tables. Using only plans, the following two options were available:

You could write a program that specifically selected the appropriate high-level
qualifier for each appropriate table, such as CURRENT or HISTORY, and hard-code that qualifier into your program.

You could BIND the programs DBRM into different plans, specifying a different owner for
each.

Maples ESM Technologies Pvt. Ltd

Page 53 of 246

DB2

Every time a DBRM with a different version identifier is bound to a package, a new version is created. This can cause many unused package versions to be retained. When packages are freed, you must specify the location, collection, package and version of package you want to free.

FREE PACKAGE

(MYCOLLN1.MYPACK1.TEST)

(MYCOLLN1.MYPACK1) (MYCOLLN1. *)

Note: DB2 is not accessed during this process.

DB2 programs must be parsed and modified before normal compilation. The DB2 precompiler performs this task. When invoked, the precompiler performs the following functions: Searches for and expands DB2 related INCLUDE members. Searches for SQL statements in the body of the programs source code. Creates a modified version of the source program in which every SQL statement in the program is commented out and a CALL to the DB2 runtime interface module, along with applicable parameters, replaces each original SQL statement. Extracts all SQL statements from the program and places them in a database request module (DBRM). DBRM is a member of a partitioned dataset. Places a timestamp token in the modified source and the DBRM to ensure that these two items are inextricably tied. Reports on the success or failure of the precompile process. The consistency token is passed to the load module from the modified source code during the compiling and linking process.

The precompiler searches for SQL statements embedded in EXEC SQL and END-EXEC keywords. For this reason, every SQL statement, table declaration, or host variable in an INCLUDE copybook must be in an EXEC SQL block.

The timestamp token or consistency token is a DB2 internal timestamp unless we specify. If we use the LEVEL keyword in the precompile JCL, the consistency token becomes the value we specify. Hence, we can control the changes in the consistency token using LEVEL keyword.

Maples ESM Technologies Pvt. Ltd

Page 54 of 246

DB2

What Is a Collection?
A collection is a user-defined name from 1 to 128 characters that the programmer must specify for every package. A collection is not an actual, physical database object. You can compare collections to databases. A DB2 database is not actually a physical object (ignoring, for the moment, the DBD). In much the same way that a database is a grouping of DB2 objects, a collection is grouping of DB2 packages.

But how do you access these packages? Assume that both packages were generated from a DBRM named SAMPPROG. This would give you packages named ORIG. SAMPRPROG and CLONE. SAMPPROG. You can bind both these packages into a plan called SAMPPLAN, for example, as in the following:

BIND PLAN (SAMPPLAN) PKLIST (ORIG.SAMPPROG, CLONE.SAMPPROG)

BIND PLAN accepts as input one or more DBRMs produced from previous DB2 program precompilations, one or more packages produced from previous BIND PACKAGE commands, or a combination of DBRMs and package lists.

The output of the BIND PLAN command is an application plan containing executable logic representing optimized access paths to DB2 data. An application plan is executable only with a corresponding load module. Before you can run a DB2 program, regardless of environment, an application plan name must be specified.

The BIND PACKAGE command accepts as input a DBRM and produces a single package containing optimized access path logic. Then, we can bind packages into an application plan using the BIND PLAN command. A package is not executable and cannot be specified when a DB2 program is being run. It is a must that all the packages must be bound into a plan before using it.

BIND performs many functions to create packages and plans that access the requested DB2 data, include the following: Reads the SQL statements in the DBRM and checks the syntax of those statements and reports on any errors. Converts high-level database requests into optimized internal forms.

Maples ESM Technologies Pvt. Ltd

Page 55 of 246

DB2

Checks that the DB2 tables and columns being accessed conform to the corresponding DB2 catalog information. Performs authorization validation (this is optional, though) Optimizes the SQL statements into efficient access paths. The consistency token is copied from the DBRM to the plan or package.

The application packages and plans contain the access path specifications developed by the BIND command. The BIND command invokes the DB2 optimizer to determine efficient access paths based on DB2 catalog statistics (such as the availability of indexes, the organization of data, and the table size) and other related information (such as number of processors, processor speed and bufferpool specifications). The BIND command is performed in the relational data services component of DB2.

A package can be bound for only a single DBRM. A package, hence, is the optimized SQL from a single program. Although packages are discrete entities in the DB2 catalog and directory, they cannot be executed until they are bound into a plan. Plans are either composed of one or more DBRMs or one or more packages.

Compile the program


The modified COBOL source data set produced by the DB2 compiler must then be compiled.

Link the program


The compiled source is then link edited to an executable load module. The appropriate DB2 host language interface module also must be included by the link edit step. This interface module is based on the environment (TSO, CICS, etc.) in which the program will execute.

The output of the link edit step is an executable load module, which then can be run with a plan containing the programs DBRM or package. The link edit procedure does not require the services of DB2; therefore, the DB2 subsystem can be inactive when your program is being link edited.

Maples ESM Technologies Pvt. Ltd

Page 56 of 246

DB2

Running a DB2 program


After a program has been prepared, two separate, physical components have been produced a DB2 plan and a link edited load module. Neither is executable without the other. The plan contains the access path specifications for the SQL statements in the program. The load module contains the executable machine instructions for the COBOL statements in the program.

If a load module is run outside the control of DB2, the program abends at the first SQL statement. Furthermore, a load module is forever tied to a specific DBRM the DBRM produced by the same precompile that produced the modified source used in the link-edit process that produced the load module.

When you run an application program containing SQL statements, you must specify the name of the plan that will be used. The plan name must include the DBRM that was produced by the precompile process in the program preparation that created the load module being run. This is enforced by a timestamp token placed into both the DBRM and the modified source by the DB2 precompiler. At execution time, DB2 checks that the tokens indicate the compatibility of the plan and the load module. If they dont match, DB2 will not allow the SQL statements in the program to be run. A 818 / -805 SQLCODE is returned for each SQL call attempted by the program based on whether the DBRM is bound to a plan or a package.

DB2 programs can be executed in one of the four ways mentioned below: Batch TSO Call attach CICS IMS

The modified source program produced by the DB2 precompiler is the input for COBOL compiler. The code is compiled and this is the input for the link editor. Link editor produces the executable load module.

The following is the JCL used to submit the DB2 COBOL program.

//TEST11A JOB ,,NOTIFY=TEST11 // JCLLIB ORDER=TEST11.DB2EX.PDS

Maples ESM Technologies Pvt. Ltd

Page 57 of 246

DB2

//STEP01 /PC.SYSIN

EXEC PROC=DSNHCOB,WSPC=500,MEM=SINGSEL DD DISP=SHR,DSN=TEST11.DB2EX.PDS(&MEM) DD DISP=SHR,DSN=TEST11.DB2DCL.PDS DD DISP=SHR,DSN=TEST11.DB2DBRM.PDS(&MEM)

//PC.SYSLIB //PC.DBRMLIB

//LKED.SYSLMOD DD DISP=SHR,DSN=TEST11.DB2LOAD2.PDS(&MEM) //* //BIND EXEC PGM=IKJEFT01,DYNAMNBR=20,COND=(4,LT)

//STEPLIB DD DISP=SHR,DSN=SYS1.DSN810.SDSNEXIT //SYSTSPRT DD SYSOUT=(*) //SYSTSIN DD * DSN SYSTEM(DSNZ) BIND PLAN(TEST11P) MEMBER(SINGSEL)ISOLATION(CS) RELEASE(C) EXPLAIN(NO)OWNER(TEST11)LIB('TEST11.DB2DBRM.PDS') RUN PROGRAM(SINGSEL) PLAN(TEST11P)LIB('TEST11.DB2LOAD2.PDS') /* //

In this JCL we need to override the PC.SYSIN DD statement to give the source code path, PC.SYSLIB DD statement give DCLGEN path, PC.DBRMLIB DD to give DBRM path and

LKED.SYSLMOD DD to give load module path.

Preparing a DB2 program


DB2 program can be prepared in many ways. Using the DB2I panels, Using a standard DB2 program preparation procedure, Using a DB2 program preparation CLIST or REXX EXEC, Any combination of the preceding methods.

Maples ESM Technologies Pvt. Ltd

Page 58 of 246

DB2

Program preparation using DB2I


DB2I or DB2 Interactive, is an online, TSO/ISPF based interface to DB2 commands, DB2 administrative functions, and CLISTs provided with DB2. It is a panel driven application that enables a user to prepare a DB2 program.

Eight panels can be used to assist with DB2 program preparation.

The DB2I main menu appears when you select the DB2I option from the main menu.

Before proceeding to the program preparation, ensure that the DB2I defaults have been properly set. Option D from the main menu displays the DB2I defaults panel. Some of them to be checked are DB2 subsystem name, application language and delimiters. After checking the DB2I defaults panel, you need to create DCLGEN members for all tables that will be accessed in an application programs.

Option 2 from the DB2I main menu displays the DCLGEN panel. Specify the name of the table in Option 1 and the name of the data set in which the DBRM will be placed in Option 2. DB2 automatically creates the DCLGEN member, including WORKING-STORAGE fields and the DECLARE TABLE statement. DCLGEN will not allocate a new data set, so you must preallocate the date set specified in Option 2 as a sequential data set with an LRECL of 80.

Option 4 of DB2I panel is to precompile DB2 application programs. To precompile a program, the following information must be entered in the specified locations on the precompile panel. The name of the input data set containing the source code for the program you want to precompile, The name of the DCLGEN library that contains the table declarations to be used by this program, A DSNAME qualifier to be used by DB2I to build data set names for temporary work files required by the precompiler, The name of the DBRM library that the precompiler will write to (this must be a partitioned data set with 80 byte records).

Using option 5, we can bind, rebind and free DB2 plans and packages. DB2I option 3 takes you step by step through the DB2 program preparation procedure, displaying the previous panels.

Maples ESM Technologies Pvt. Ltd

Page 59 of 246

DB2

Execution
DB2 checks for the consistency token in both the load module and the plan.

COBOL load module is loaded into memory. It starts to execute. Sooner, it reaches the first call to the DB2 language interface module. This module passes the control to the RTS (Run Time Supervisor). The RTS then retrieves the application plan from the DB2 directory, loads them into memory and the data manager in turn performs the necessary operation on the actual stored data and passes results back to the program.

RUN

PROGRAM (PROG1) PLAN (PLAN1) LIBRARY (MTRG001.LOADLIB) PARMS (01-01-2001)

If the PLAN name is not specified, the plan name defaults to the program name.

Program Preparation Objects


The program preparation process is composed of many objects. Source - Every program starts as a series of host language statements, known as the application source. The source gets run through the DB2 precompiler to have its SQL statements removed and placed in a DBRM. Modified source - The DB2 precompiler creates the modified source module by stripping the source module of all its SQL statements. The modified source is passed to the host language compiler. Load module - The linkage editor creates a load module using the output of the host language compiler. The load module contains the executable form of the host language statements and is executable in conjunction with an application plan. DBRM - The DBRM is created by the DB2 precompiler from the SQL statements stripped from the program source code. Plan- A plan is created by the BIND statement. It consists of the access paths required to execute the SQL statements for all DBRMs bound into the plan. The plan is executable in conjunction with the corresponding program load module.

Maples ESM Technologies Pvt. Ltd

Page 60 of 246

DB2

Package-

A package is also created by the BIND statement. It contains the access paths

for a single DBRM.

Embedded SQL Embedded SQL Guidelines


Explicitly declare all DB2 tables

Although you are not required to declare DB2 tables in your application program, doing so is good programming practice. Therefore, explicitly DECLARE all tables to be used by your application program. You should place the DECLARE TABLE statements in the WORKING-STORAGE section of your program, and they should be the first DB2-related variables defined in WORKINGSTORAGE . This way, you can reduce the precompiler's work and make the table definitions easier to find in the program source code. Additionally, standard DECLARE TABLE statements should be generated for every DB2 table. Create them with the DCLGEN command , and then include them in your application program.

Comment Each SQL Statement Make liberal use of comments to document the nature and purpose of each SQL statement embedded in your program. You should code all comments pertaining to embedded SQL in the comment syntax of the program's host language. Code COBOL comments as shown in the following example: Column Numbers 111 123456789012 ** ** Retrieve department name and manager from the ** DEPT table for a particular department number. ** EXEC SQL SELECT DEPTNAME, MGRNO INTO :HOSTVAR-DEPTNAME, :HOSTVAR-MGRNO FROM DEPT WHERE DEPTNO = :HOSTVAR-DEPTNO END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 61 of 246

DB2

Include the SQLCA

You must include a structure called the SQLCA (SQL Communication Area) in each DB2 application program.

DB2 describes the results of execution is SQLCA. It returns SQL codes.

EXEC SQL INCLUDE SQLCA END-EXEC.

This statement causes the precompiler to insert a declaration into the program for a structure called the SQLCA. This declaration in turn contains declarations for both SQLCODE and SQLSTATE together with a number of feedback variables that will also be set after the execution of each SQL statement.

The SQLCA is used to communicate information describing the success or failure of the execution of an embedded SQL statement.

Check SQLCODE or SQLSTATE

SQLCODE SQLSTATE

PIC S9 (09) COMP. PIC X (05).

SQLCODE contains the SQL return code, which indicates the success or failure of the last SQL statement executed. SQLSTATE is similar to SQLCODE but is consistent across DB2 platforms.

Code a Cobol IF statement immediately after every SQL statement to check the value of the SQLCODE.

If the SQLCODE returned by the SQLCA is less than zero, an SQL error was encountered. For example, if you try to insert a row into a table and receive an SQL code of 803, indicating a duplicate key value.

Maples ESM Technologies Pvt. Ltd

Page 62 of 246

DB2

Also, SQLSTATE is a value, which consist of 5 characters; a two-character class code and a three-character subclass code. The class code indicates the type of error, and the subclass code details the explicit error within that error type. Class code 00 and subclass code 000 means that the statement is executed successfully. Class code 01 means that the statement is executed with some warning. Class code 02 implies that no data was found. Here, subclass code will be 000.

Standardize Your Shop's Error Routine

Consider using a standardized error handling paragraph, one that can be used by all DB2 programs in your shop. The programs should load values to an error record that can be interpreted by the error handling paragraph. When a severe error is encountered, the programs invok the error handling paragraph.

The error handling paragraph should do the following: 1. Call the DSNTIAR module, a program provided with DB2 that returns standard, textual error messages for SQLCODE s. 2. Display, print, or record the following information: the error record identifying the involved table, the paragraph, and pertinent host variables; the error text returned by DSNTIAR; and the current values in the SQLCA. 3. Issue a ROLLBACK. (This action is not absolutely required because an implicit rollback occurs if one is not requested.) 4. Call an ABEND module to generate a dump. Your error handling paragraph can be as complex and precise as you want. Depending on the SQL code, different processing can occur; for example, you might not want to abend the program for every SQLCODE.

Avoid Using WHENEVER

SQL has an error trapping statement called WHENEVER that you can embed in an application program. When the WHENEVER statement is processed, it applies to all subsequent SQL statements issued by the application program in which it is embedded. WHENEVER directs

Maples ESM Technologies Pvt. Ltd

Page 63 of 246

DB2

processing to continue or to branch to an error handling routine based on the SQLCODE returned for the statement. Several examples follow.

The following example indicates that processing will continue when an SQLCODE of +100 is encountered: EXEC SQL WHENEVER NOT FOUND CONTINUE END-EXEC. When a warning is encountered, the second example of the WHENEVER statement causes the program to branch to a paragraph (in this case, ERROR-PARAGRAPH) to handle the warning: EXEC SQL WHENEVER SQLWARNING GO TO ERROR-PARAGRAPH END-EXEC. When any negative SQLCODE is encountered, the next WHENEVER statement branches to a paragraph (once again, ERROR-PARAGRAPH) to handle errors: EXEC SQL WHENEVER SQLERROR GO TO ERROR-PARAGRAPH END-EXEC. Each of the three types of the WHENEVER statement can use the GO TO or CONTINUE option, at the discretion of the programmer. These types of the WHENEVER statements trap three "error" conditions: NOT FOUND The SQLCODE is equal to +100

SQLWARNING

The SQLCODE is positive but not +100 or SQLWARN0 equal to W

SQLERROR

The SQLCODE is negative

Avoid using the WHENEVER statement. It is almost always safer to code specific SQLCODE checks after each SQL statement and process accordingly. Additionally, you should avoid coding the GO TO verb as used by the WHENEVER statement. The GO TO construct is generally avoided in structured application programming methodologies.

Maples ESM Technologies Pvt. Ltd

Page 64 of 246

DB2

Embedded SELECT statements

The two types of embedded SQL SELECT statements are singlet row SELECT and cursor SELECTs.

We know, SQL statements operate on a set of data and return a set of data. Host language programs operate on a data, a row at a time. A single row SELECT is simply an SQL SELECT statement that returns only one row. As such, it can be coded and embedded in a host language program with little effort. The singleton SELECT returns one row and the application program processes one row.

Coding a singleton SELECT is as follows:

EXEC SQL SELECT DEPTNAME, LOCATION INTO :DEPTNAME, :LOCATION FROM DEPT1 WHERE DEPTNO=:DEPTNO EXEC SQL

The singleton SELECT statement differs from a normal SQL SELECT statement in that it must contain the INTO clause. In the INTO clause, you code the host variables that accept the data returned from the DB2 table by the SELECT statement.

Singleton SELECTs are usually quite efficient. The singleton SELECT returns only one row. If more than one row is retrieved, the first one is placed in the host variables defined by the INTO clause, and the SQLCODE is set to 811.

Sample program to retrieve one row from table as follows:

IDENTIFICATION DIVISION. PROGRAM-ID. EMBSQL. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE EMPDCL END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 65 of 246

DB2

EXEC SQL INCLUDE SQLCA END-EXEC. 77 SCODE PIC S9(3). 01 ERR-MSG. 02 ERR-LEN PIC S9(4) COMP. 02 ERR-CONT PIC X(80). 01 ERR-LRECL PIC S9(9) COMP VALUE 80. PROCEDURE DIVISION. ACCEPT EMPNO. MOVE 2323 TO ENO. EXEC SQL SELECT ENO,ENAME INTO :ENO,:ENAME FROM EMP123 WHERE ENO = :ENO END-EXEC. IF SQLCODE = 0 DISPLAY 'EMP NUMBER: ', ENO DISPLAY 'EMP NAME : ', ENAME ELSE MOVE SQLCODE TO SCODE DISPLAY 'SQL CODE' , SCODE CALL 'DSNTIAR' USING SQLCA, ERR-MSG, ERR-LRECL DISPLAY ERR-MSG END-IF. STOP RUN.

If your application program must process a SELECT statement that returns multiple rows, you must use a cursor, which is an object designed to handle multiple row results tables.

Modifying Data with Embedded SQL


You can also embed pure set-level processing UPDATE, DELETE, and INSERT SQL statements into a host language program. Simply code the appropriate SQL statement, and delimit it with EXEC SQL and END-EXEC. The statement can contain host variables. When issued in the program, the statement is processed as though it were issued interactively. Consider the following example:

Maples ESM Technologies Pvt. Ltd

Page 66 of 246

DB2

EXEC SQL UPDATE EMP SET SALARY = SALARY * 1.05 WHERE EMPNO = :EMPNO END-EXEC. EXEC SQL DELETE FROM PROJACT WHERE ACENDATE < CURRENT DATE END-EXEC. EXEC SQL INSERT INTO DEPT (DEPTNO, DEPTNAME,MGRNO, ADMRDEPT) VALUES (:DEPTNO, :DEPTNAME, :MGRNO, :ADMRDEPT) END-EXEC. These three SQL statements are examples of coding embedded data modification statements (UPDATE, DELETE, and INSERT) using host variables.

Embedded Modification SQL Guidelines


Use FOR UPDATE OF to ensure data integrity If a program is coded to SELECT or FETCH a row and then, based on the rows contents, issue an UPDATE or DELETE, use a cursor with FOR UPDATE OF to ensure data integrity. The FOR UPDATE OF clause locks the data page when it is fetched, ensuring that no other process can modify the date before your program processes it.

When programming a pseudo-conversation CICS transaction, FOR UPDATE OF is not sufficient to ensure integrity. A save and compare must be done prior to any update activity.

Specify a primary key in the WHERE clause of UPDATE and DELETE statements

Never issue UPDATE and DELETE statements without specifying a primary key value unless you want to affect multiple rows. Without the unique WHERE clause specification, you might be unable to determine whether you have specified the correct row for modification. Moreover, you could mistakenly update or delete multiple rows.

Maples ESM Technologies Pvt. Ltd

Page 67 of 246

DB2

Host variables
A host variable is an area of storage allocated by the host language and referenced in an SQL statement. You define and name host variables using the syntax of the host language. For COBOL, you must define host variables in the DATA DIVISION of your program in the WORKING-STORAGE SECTION or the LINKAGE SECTION.

When you use the host variables in SQL statements, prefix them with a colon (:).

For example, a COBOL variable defined in the DATA DIVISION as

EXAMPLE-VARIABLE PIC X (5)

should be referenced as follows when used in an embedded SQL statement :

: EXAMPLE-VARIABLE

When the COBOL program outside the context of SQL references the same variable, however, do not prefix the variable with a colon.

Host variables are the means of moving data from the program to DB2 and from DB2 to the program. Data can be read from a file, placed into host variables, and used to modify a DB2 table (through embedded SQL).

For data retrieval, host variables are used to house the selected DB2 data. Host variables can be used in the following ways: As output data areas in the INTO clause of the SELECT and FETCH statements. As input data areas for the SET clause of the UPDATE statement. As input data areas for the VALUES clause of the INSERT statement As search fields in the WHERE clause for SELECT, INSERT, UPDATE and DELETE statements. As literals in the SELECT list of a SELECT statement.

In the first example, host variables are used in the SQL SELECT statement as literals in the SELECT list and as output data areas in the INTO clause:

Maples ESM Technologies Pvt. Ltd

Page 68 of 246

DB2

EXEC SQL SELECT INTO : EMPNO,: INCREASE-PCT, SALARY * :INCREASE-PCT : HOSTVAR-EMPNO, : HOSTVAR-INCRPCT, : HOSTVAR-SALARY FROM WHERE END-EXEC. EMP EMPNO = 12345;

In the second example, host variables are used in the SET clause of the UPDATE statement and as a search field in the WHERE clause:

EXEC SQL UPDATE EMP SET SALARY =: HOSTVAR-SALARY WHERE EMPNO =: HOSTVAR-EMPNO END-EXEC.

In the last example, we shall see how host variables are used in the VALUES clause of an SQL INSERT statement.

EXEC SQL INSERT VALUES INTO DEP

(: HOSTVAR-DEPNO, : HOSTVAR-DEPNAME, : HOSTVAR-MGRNO, : HOSTVAR-ADMRDEP)

END-EXEC.

Host Structures
Also, SQL statements can use host structures. Host structures enable SQL statements to specify a single structure for storing all retrieved columns.

The following is a host structure for the DEP table:

Maples ESM Technologies Pvt. Ltd

Page 69 of 246

DB2

01

DCLDEP. 10 10 DEPNO PIC X (3). DEPNAME. 49 49 10 10 10 DEPNAME-LEN PIC S9 (4) USAGE COMP.

DEPNAME-TXT PIC X (36). PIC X (6). PIC X (3). PIC X (16).

MGRNO ADMRDEP LOCATION

DCLDEP is the host structure name. You could write the following statement using this host structure.

EXEC SQL SELECT INTO WHERE END-EXEC. DEPNO, DEPNAME, MGRNO, ADMRDEP, LOCATION : DCLDEP FROM EMP DEPNO = A00

This statement populates the host variables for all columns defined under the DCLDEP grouplevel data area.

Null Indicator Variables and Structures


Before you select or insert a column that can be set to null, it must have an indicator variable defined for it. You can use indicator variables also with the UPDATE statement to set columns to null. A third use for null indicators occurs when any column (defined as either nullable or not nullable) is retrieved using the built-in column functions AVG, MAX, MIN and SUM. Finally, null indicators should be used in outer join statements for each column that can return a null result (even if the column is defined as not null). If you fail to use an indicator variable, a 305 SQLCODE is returned when no rows meet the requirements of the predicates for the SQL statement containing the column function.

For example, consider the following statement: SELECT MAX (SALARY) FROM EMP WHERE WORKDEP = ABC;

Maples ESM Technologies Pvt. Ltd

Page 70 of 246

DB2

If there is no department by the name ABC, then the value of the maximum salary that is returned is null.

You should define null indicators in the WORKING-STORAGE section of your COBOL program as computational variables, with a picture clause specification of PIC S9 (4).

The null indicator variables for the EMP table look like this:

01

EMP-INDICATORS. 10 10 10 10 10 10 10 10 10 10 WORKDEP-IND PHONENO-IND HIREDATE-IND JOB-IND EDLEVEL-IND SEX-IND BIRTHDATE-IND SALARY-IND BONUS-IND COMM-IND PIC S9 (4) USAGE COMP. PIC S9 (4) USAGE COMP. PIC S9 (4) USAGE COMP. PIC S9 (4) USAGE COMP. PIC S9 (4) USAGE COMP. PIC S9 (4) USAGE COMP. PIC S9 (4) USAGE COMP. PIC S9 (4) USAGE COMP. PIC S9 (4) USAGE COMP. PIC S9 (4) USAGE COMP.

This structure contains the null indicators for all the nullable columns of the EMP table.

To associate null indicator variables with a particular host variable for a column, code the indicator variable immediately after the host variable, preceded by a colon. For example, to retrieve information regarding SALARY (a nullable column) from the EMP table, you can code the following embedded SQL statement:

EXEC SQL SELECT INTO EMPNO, SALARY : EMPNO, : SALARY :SALARY-IND FROM WHERE END-EXEC. EMP EMPNO = 12345

Maples ESM Technologies Pvt. Ltd

Page 71 of 246

DB2

The null indicator variable is separate from both the columns to which it pertains and the host variable for that column. To determine the value of any nullable column, a host variable and an indicator variable are required. The host variable contains the value of the column when it is not null.

You can use null indicator variables with corresponding host variables in the following situations:

Set clause of the UPDATE statement. VALUES clause of the INSERT statement. INTO clause of the SELECT or FETCH statement.

You can use the host structure and null indicator structure together as follows: EXEC SQL SELECT INTO WHERE END-EXEC. DEPNO, DEPNAME, MGRNO, ADMRDEP, LOCATION :DCL-DEP :DEP-IND FROM EMP DEPNO = 999

Based on the position in the null indicator structure, you can determine the null status of each column in the retrieved row. If the nth null indicator contains a negative value, the nth column is null. So, in this example, if DEP-IND (3) is negative, MGRNO is null.

IDENTIFICATION DIVISION. PROGRAM-ID. SELIND. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 DCLEMP. 10 EMPNO 10 EMPNAME 10 DEPTNO 10 SALARY 10 DIND PIC X(4). PIC X(10). PIC X(4). PIC S9(5)V9(2) USAGE COMP-3. PIC S9(4) COMP.

EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL DECLARE CUR1 CURSOR FOR SELECT EMPNO,EMPNAME,DEPTNO,SALARY

Maples ESM Technologies Pvt. Ltd

Page 72 of 246

DB2

FROM EMP END-EXEC. PROCEDURE DIVISION. EXEC SQL OPEN CUR1 END-EXEC. PERFORM PARA1 UNTIL SQLCODE NOT EQUAL TO 0. CPARA. EXEC SQL CLOSE CUR1 END-EXEC. DISPLAY SQLCODE. STOP RUN. PARA1. EXEC SQL FETCH CUR1 INTO :EMPNO,:EMPNAME, :DEPTNO:DIND,:SALARY END-EXEC. IF SQLCODE = 100 GO TO CPARA. IF DIND = -1 MOVE SPACES TO DEPTNO. DISPLAY "EMPNO" EMPNO. DISPLAY "EMPNAME" EMPNAME. DISPLAY "DEPTNO" DEPTNO. DISPLAY "SALARY" SALARY. DISPLAY "---------------------------".

Host Variable Guidelines


Use Syntactically Valid Variable Names

Host variables can use any naming scheme that is valid for the definition of variables in the host language being used. For host variables defined using COBOL, underscores are not permitted. As a general rule, use hyphens instead of underscores.

Maples ESM Technologies Pvt. Ltd

Page 73 of 246

DB2

Avoid Certain COBOL Clauses

COBOL host variable definitions cannot specify the JUSTIFIED or BLANK WHEN ZERO clauses. You can specify the OCCURS clause only when you're defining a null indicator structure. Otherwise, you cannot use OCCURS for host variables.

Using Host Structures

In general, favor individual host variables over host structures. Individual host variables are easier to understand, easier to support, and less likely to cause errors as a result of changes to tables. Additionally, using individual host variables promotes proper SQL usage. When using host structures, too often developers try to fit every SQL SELECT to the host structure. Instead of limiting each SQL SELECT statement to retrieve only the columns required, developers sometimes will force every SELECT statement in a program to fit a single host structure. To optimize performance, this must be avoided.

However, when it is necessary to squeeze every last bit of performance out of an application, consider using host structures. When a host structure is used, a minimal number of instructions are saved because DB2 does not have to move each column separately to an individual host variable. Instead, one move is required to move the columns into the host structure.

Caution - When host structures are used, be sure not to fall into the trap of making every SELECT statement use a single host structure, or performance will suffer.

Avoid Null Indicator Structures

Favor individual null indicator variables over null indicator structures. Individual null indicator variables can be named appropriately for each column to which they apply. Null indicator structures have a single common name and a subscript. Tying a subscripted variable name to a specific column can be tedious and error-prone.

For example, consider the host structure and its corresponding null indicator structure shown previously. The fact that IDEPT(2) is the null indicator variable for the DEPTNAME host variable is not obvious. If you had used separate null indicators for each nullable column, the null indicator for DEPTNAME could be called DEPTNAME-IND. With this naming convention, you can easily see that DEPTNAME-IND is the null indicator variable for DEPTNAME.

Maples ESM Technologies Pvt. Ltd

Page 74 of 246

DB2

Be forewarned that null indicator structures can be generated by DCLGEN (as of DB2 V4), whereas individual indicator variables must be explicitly coded by hand. Even so, individual null indicator variables are easier to use and therefore recommended over null indicator structures.

Define Host Variables Precisely

Define all your host variables correctly. Failure to define host variables correctly results in precompiler errors or poor performance due to access path selection based on non-equivalent data types, data conversions, and data truncation.

Use DCLGEN for Host Variable Generation

Use DCLGEN to generate host variables automatically for each column of each table to be accessed. DCLGEN ensures that the host variables are defined correctly.

Avoid DCLGEN for Null Indicator Generation

DCLGEN can optionally generate null indicator host structures. However, host structures are more difficult to use than individual null indicator variables and generally should be avoided.

Cursor Processing Programming with CURSORS


As we saw earlier, an impedance mismatch occurs between SQL and the host language, such as COBOL. COBOL operates on data, a row at a time; SQL operates on data, a set at a time. The solution for handling this impedance mismatch is the structure known as symbolic cursor or simple, cursor. DB2 application programs use cursors to navigate through a set of rows returned by an embedded SQL SELECT statement. A cursor is similar to a pointer. As a programmer, we declare the cursor and define an SQL statement for that cursor. After that, you can use the cursor. The cursor is opened, rows are fetched from the cursor, one row at a time, and then the cursor is closed.

Maples ESM Technologies Pvt. Ltd

Page 75 of 246

DB2

Four different operations are allowed on cursors: DECLARE - Defined the cursor, gives it a name unique to the program in which it is embedded, and assigns an SQL statement to the cursor name. The DECLARE statement does not execute the SQL statement; it merely defines the SQL statement. Declare cursor can either be in data division or in procedure division. This is to view the rows in the result table. SELECT is executed only when a cursor is opened. OPEN - Prepares the cursor for row retrieval. OPEN is an executable statement. It reads the SQL search fields, executes the SQL statement, and sometimes builds the results table. It does not assign values to host variables, though. FETCH - Returns data from the results table one row at a time and assigns the value to specified host variables. If the results table is not built at cursor OPEN time, it is built FETCH by FETCH. CLOSE - Releases all resources used by the cursor.

Whether the result table for the SQL statement is built at cursor OPEN time or as rows are fetched depends on the type of SQL statement and the access path.

When you are processing with cursors, an SQL statement can return zero, one or many rows. The following list describes the cursor processing that occurs for the different number of retrieved rows: One row - Use of the cursor is optional. Many rows - Cursor usage is mandatory. When multiple rows are retrieved by an SQL statement, a cursor must be coded. If multiple rows are returned by a SELECT statement not coded using a CURSOR, DB2 returns a -811 SQLCODE (the SQLSTATE is 21000) Zero rows - No rows exist for the specified conditions. When no rows are returned, the SQL return code is set to +100. When cursors are used to process multiple rows, a FETCH statement is typically coded in a loop that reads and processes each row in succession. When no more rows are available to be fetched, the FETCH statement returns an SQLCODE of +100, indicating no more rows.

Maples ESM Technologies Pvt. Ltd

Page 76 of 246

DB2

A cursor is declared for an SQL SELECT statement in WORKING-STORAGE. Values are moved to the host variables, and the cursor is opened. A loop fetches and processes information until no more rows are available; then the cursor is closed.

IDENTIFICATION DIVISION. PROGRAM-ID. SELPGM1. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. ****************************************************************** * DCLGEN TABLE(MAPLE04.DEPT) * * * LIBRARY(MAPLE04.SMS.DCLGEN) LANGUAGE(COBOL) QUOTE * * * *

* ... IS THE DCLGEN COMMAND THAT MADE THE FOLLOWING STATEMENTS ****************************************************************** EXEC SQL DECLARE MAPLE04.DEPT TABLE ( DEPTNO DEPTNAME ) END-EXEC. ****************************************************************** * COBOL DECLARATION FOR TABLE MAPLE04.DEPT ****************************************************************** 01 DCLDEPT. 10 DEPTNO 10 DEPTNAME PIC X(3). PIC X(10). * CHAR(3) NOT NULL, CHAR(10) NOT NULL

****************************************************************** * THE NUMBER OF COLUMNS DESCRIBED BY THIS DECLARATION IS 2 * ***************************************************************** EXEC SQL DECLARE CUR1 CURSOR FOR SELECT DEPTNO,DEPTNAME FROM DEPT1 END-EXEC. PROCEDURE DIVISION. EXEC SQL OPEN CUR1

Maples ESM Technologies Pvt. Ltd

Page 77 of 246

DB2

END-EXEC. PERFORM PARA1 UNTIL SQLCODE NOT EQUAL TO 0. CPARA. EXEC SQL CLOSE CUR1 END-EXEC. DISPLAY SQLCODE. STOP RUN. PARA1. EXEC SQL FETCH CUR1 INTO :DEPTNO,:DEPTNAME END-EXEC. IF SQLCODE = 100 GO TO CPARA. DISPLAY DEPTNO. DISPLAY DEPTNAME.

Using a Cursor for Data Modification


Usually an application program reads data and then based on its values, either update or delete the data. You use the UPDATE and DELETE SQL statements to modify and delete rows from DB2 tables. These statements, like the SELECT statement, operate on data a set at a time.

To read the data first before modifying it or deleting or is accomplished by using a cursor. In addition, a special clause of the UPDATE and DELETE statements that can be used only by embedded SQL; WHERE CURRENT OF. We declare the cursor with a special FOR UPDATE OF clause.

The following code shows how a cursor is opened and a row is fetched. After examining the contents of the retrieved data, the program updates or deletes the row using the WHERE CURRENT OF C1 clause.

IDENTIFICATION DIVISION. PROGRAM-ID. UPDCUR. ENVIRONMENT DIVISION. DATA DIVISION.

Maples ESM Technologies Pvt. Ltd

Page 78 of 246

DB2

WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL DECLARE C1 CURSOR FOR SELECT EMPNO, EMPNAME, SALARY FROM EMP FOR UPDATE OF SALARY END-EXEC. PROCEDURE DIVISION. EXEC SQL OPEN C1 END-EXEC. PERFORM 200-MODIFY-SAL UNTIL SQLCODE NOT = 0. EXEC SQL CLOSE C1 END-EXEC. 200-MODIFY-SAL. EXEC SQL FETCH C1 INTO :EMPPNO, :EMPNAME, :SALARY END-EXEC. IF SQL-CODE = 0 EXEC SQL UPDATE EMP SET SALARY=SALARY +1000 WHERE CURRENT OF C1 END-EXEC.

These features enable you to perform row by row operations on DB2 tables.

Maples ESM Technologies Pvt. Ltd

Page 79 of 246

DB2

Embedded SELECT and CURSOR coding guidelines

Use Singleton SELECTs to reduce overhead

It is always advisable to use singleton SELECTs rather than cursors because the definition and processing of cursors add overhead to a DB2 application program. But, make sure that the singleton SELECTs retrieve only one row. This can be done by selecting data, only by the primary key.

Only if the program requires a SELECT statement that returns more than one row, go for the cursors.

If a program employs a SELECT statement that returns more than one row but needs to process only the first row returned, consider coding a singleton SELECT instead of a cursor.

Declare as many cursors as needed

You can declare and open more than one cursor in any given program at any time.

Avoid using certain cursors for modification

Usage of cursor for updates and deletes is not possible if the DECLARE CURSOR statement includes any of the following.

UNION clause DISTINCT clause GROUP BY clause ORDER BY clause Joins Subqueries Correlated subqueries

Place the DECLARE CURSOR statement first

The DECLARE CURSOR statement must precede any other commands (such as OPEN, FETCH and CLOSE).

Maples ESM Technologies Pvt. Ltd

Page 80 of 246

DB2

The DECLARE CURSOR statement is not an executable statement and hence, cannot be coded in the procedure division of an application program. Still, it does not cause a problem.

You should place all CURSOR declarations in the WORKING-STORAGE section of the application program. All host variable declarations must precede the DECLARE CURSOR statement in the application program.

Include only the columns being updated

While coding a FOR UPDATE OF clause of the DECLARE CURSOR statement, you should specify only the columns that are to be updated. Coding more columns than necessary can degrade the performance. Also, in the FOR UPDATE OF clause of the DECLARE CURSOR statement, you must include all columns to be modified. Otherwise, subsequent UPDATE.WHERE CURRENT OF statements will not be allowed for those columns.

Use WHERE CURRENT OF to delete single rows using a cursor

Use the WHERE CURRENT OF clause on UPDATE and DELETE statement that are meant to modify only a single row. Failure to code WHERE CURRENT OF will result in the updation or deletion of all the rows in the concerned table.

Open cursors before fetching

A cursor must be opened before it can be fetched from or closed. Also, cannot open a cursor twice before closing it.

Initialize host variables

Initialize all host variables used by the cursor before opening the cursor. All host variables used in a cursor SELECT are evaluated when the cursor is opened, not when the cursor if declared or fetched from.

Careful while using specifying host variables used with FETCH If the data type does not match the host variable, and the data cannot be converted, a compilation error results. This error can occur even if host variables are transposed as shown below:

Maples ESM Technologies Pvt. Ltd

Page 81 of 246

DB2

EXEC SQL DECLARE C1 CURSOR SELECT FROM END-EXEC. EXEC SQL FETCH C1 INTO END-EXEC. Here, it gives out a compilation error just because the variables DEPNO and MGRNO are switched while retrieving through FETCH statement. If there happens to be a switch between two variables of same datatype and length, it does cause data integrity problems. Explicitly close cursors When a DB2 program is finished, DB2 implicitly closes all cursors opened by the program. To increase performance, you should explicitly code the CLOSE statement for each cursor. The CLOSE statement can be executed only against previously OPENed cursors. Use the WITH HOLD clause to retain cursor position When a COMMIT is issued by the program, open cursors are closed unless the WITH HOLD option is coded for the cursor. EXEC SQL DECLARE CSR1 CURSOR WITH HOLD FOR SELECT EMPNO, LASTNAME FROM EMP WHERE SALARY > 30000 END-EXEC. WITH HOLD prevents subsequent COMMITs from destroying the intermediate result table for the SELECT statement, thereby saving positioning within the cursor. Open cursors only when needed Do not open a cursor until just before you need it. Close the cursor immediately after your program receives an SQLCODE of +100, which means that the program has finished processing the cursor. :MGR-NO, :DEPNO DEPNO, MGRNO DEP

Maples ESM Technologies Pvt. Ltd

Page 82 of 246

DB2

Chapter 7 : SQL Execution Validation


SQLCA
A program that includes SQL statements needs to have an area set apart for communication with DB2 an SQL Communication Area (SQLCA). When DB2 processes a SQL statement in a program, it places return codes in the SQLCODE and SQLSTATE host variables or corresponding fields of the SQLCA.

Signal to DB2 that the transaction has completed successfully and any changes to the database can be completed.

SQLCA is a valuable problem-diagnosis tool for an Embedded SQL program. It contains the following messages like SQLCAID, SQLCODE, SQLERROR, SQLWARNING, SQLSTATE etc

SQL Codes:
The SQL return code indicates whether the statement executed successfully or with warning message.

Greater than zero Less than zero +100 - 803 - 811 - 911, - 913

success with a warning. not successful. no rows found. duplicate insert. multiple rows retrieved. time out.

DB2 returns the following codes in SQLCODE If SQLCODE = 0, execution was successful If SQLCODE > 0, execution was successful with a warning If SQLCODE < 0, execution was not successful SQLCODE 100 indicates no data was found.

Maples ESM Technologies Pvt. Ltd

Page 83 of 246

DB2

SQL State:
Allows an application program to check for errors in the same way for different IBM database management systems. An advantage to using the SQLCODE field is that it can provide more specific information than the SQL STATE.

Error Handling
WHENEVER statement is used to enable automatic testing of DB2 return codes and error handling for subsequent SQL statements until the next WHENEVER statement.

General format

EXEC SQL WHENEVER SQLERROR GOTO <ERROR PARA> END-EXEC

EXEC SQL WHENEVER WARNING GOTO <WARNING PARA> END-EXEC

EXEC SQL WHENEVER NOT FOUND CONTINUE END-EXEC

Maples ESM Technologies Pvt. Ltd

Page 84 of 246

DB2

Error Messages can be viewed by using DSNTIAR module

IDENTIFICATION DIVISION. PROGRAM-ID. INSPGM. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. 01 ERROR-MESSAGE. 02 ERROR-MESSAGE-LENGTH 02 ERROR-MESSAGE-LINE PIC S9(4) COMP VALUE +800.

PIC X(80) OCCURS 10 TIMES

INDEXED BY EML-INDEX. 01 ERROR-LINE-LENGTH PROCEDURE DIVISION. EXEC SQL INSERT INTO DEPT VALUES("D001","FIN") END-EXEC. CALL 'DSNTIAR' USING SQLCA ERROR-MESSAGE ERROR-LINE-LENGTH. DISPLAY ERROR-MESSAGE. STOP RUN. PIC S9(9) COMP VALUE +80.

Maples ESM Technologies Pvt. Ltd

Page 85 of 246

DB2

Chapter 8 : Advanced SQL

Static SQL Vs Dynamic SQL


Most DB2 application programs use static SQL to access DB2 tables. A static SQL statement is a complete, unchanging statement hard-coded into an application program. It cannot be modified during the programs execution except for changes to the value assigned to host variables.

Static SQL is powerful. Any SQL statement can be embedded in a program and executed as static SQL.

Dynamic SQL
Dynamic SQL are prepared and executed while the program is running. Dynamic SQL is embedded in an application program and can change during the programs execution. Dynamic SQL statements are coded explicitly in host-language variables, prepared by the application program, and then executed.

SPUFI and QMF are two examples of programs that execute dynamic SQL statements.

DB2 supports two types of SQL statements in an application program Static SQL Dynamic SQL Static SQL are SQL statements o o o o o o

Embedded in a host language and bound before the program runs. Provides straight forward, efficient path to DB2 data. The objects are known during pre-compilation time Faster in execution Plan prepared is permanent Access path is based on old statistics.

Maples ESM Technologies Pvt. Ltd

Page 86 of 246

DB2

Dynamic SQL are SQL statements o o o o o o

Prepared and executed, while the program is running. Unplanned Query Objects are known at run time Slow in execution Plan is transient Access path generated on current statistics

Dynamic SQL and Performance


Compared to Static SQL, even though Dynamic SQLs offer a great deal of flexibility, it always requires more overheads to process. Dynamic SQLs incurs overheads because the cost of dynamic bind or PREPARE must be added to the processing time of all dynamic SQL programs. However, dynamic SQLs generally reduce the number of SQL statements to be coded, they use the most recent RUNSTATS statistics, they can use new indexes without a REBIND, etc. So even though it is always better to use a static SQL, do not rule out the possibility of using a dynamic SQL. With the improvements in the recent versions of DB2, the dynamic SQLs, if coded properly, can be used without much reduction in performance.

Applications using Dynamic SQL use three types of SQL Statements

Dynamic SQL for non-SELECT statement

Those statements include DELETE, INSERT and UPDATE. For execution, use either of the following SQL Statements: EXECUTE IMMEDIATE PREPARE and then EXECUTE

Dynamic SQL for fixed-list SELECT statements

A SELECT statement is fixed-list if you know in advance the number and type of data items in each row of the result. For execution, use the following SQL statements.

Maples ESM Technologies Pvt. Ltd

Page 87 of 246

DB2

PREPARE (a SQL cursor definition) OPEN the cursor FETCH from the cursor CLOSE the cursor

Dynamic SQL for varying-list SELECT statements

A SELECT statement is varying-list if you cannot know in advance how many data items to allow for or what their data types are. DECLARE CURSOR for the statement PREPARE the statement DESCRIBE the statement OPEN cursor FETCH using DESCRIPTOR CLOSE cursor.

Example for PREPARE & EXECUTE (Non-SELECT) Statement: IDENTIFICATION DIVISION. PROGRAM-ID. DYNSAMP. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. 01 WS-HOST-VARIABLE. 49 WS-LEN 49 WS-TXT PIC S9 (4) COMP. PIC X (100).

PROCEDURE DIVISION. MOVE +42 TO WS-LEN MOVE DELETE FROM EMP WHERE DEPTNO = D001 TO WS-TXT EXEC SQL PREPARE STMT1 FROM :WS-HOST-VARIABLE END-EXEC. EXEC SQL EXECUTE STMT1 END-EXEC. STOP RUN.

Maples ESM Technologies Pvt. Ltd

Page 88 of 246

DB2

The SQL statement is stored as a string. Can be used for insert, update or delete. The SQL statement is prepared and assigned a unique label. A prepared statement can be executed several times in a program.

Example for EXECUTE IMMEDIATE

IDENTIFICATION DIVISION. PROGRAM-ID. DYNSAMP. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. 01 WS-HOST-VARIABLE. 49 WS-LEN 49 WS-TXT PROCEDURE DIVISION. MOVE DELETE FROM EMP WHERE DEPTNO = D001 TO WS-TXT MOVE LENGTH OF WS-TXT TO WS-LEN. EXEC SQL EXECUTE IMMEDIATE :WS-HOST-VARIABLE END-EXEC. STOP RUN. PIC S9 (4) COMP. PIC X (100).

Prepares and execute the SQL statements in one shot. It is more efficient and faster than the PREPARE statement.

EXECUTE IMMEDIATE implicitly prepares and executes complete SQL statements coded in host variables. Only a sub-set of SQL statement is available when you use this command, the most prominent being SELECT and so this call of dynamic SQLs cannot be used for data retrieval.

Fixed-List Select Statements


Fixed-list implies that the number of columns and the data types of those columns are known in advance. Number of rows that are returned need not to be known

Maples ESM Technologies Pvt. Ltd

Page 89 of 246

DB2

Steps Declare a cursor for the statement name Prepare the statement Open the cursor Fetch rows from result table Close the cursor

Example for FIXED LIST SELECT

IDENTIFICATION DIVISION. PROGRAM-ID. FXEDSEL. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. EXEC SQL INCLUDE SQLCA END-EXEC. END-EXEC.

EXEC SQL DECLARE C1 CURSOR FOR PL 01 REC. 49 REC-LEN PIC S9(4) COMP. 49 REC-TEXT PIC X(70). 01 DCLEMP. 10 EMPNO 10 EMPNAME 10 DEPTNO 10 SALARY PIC X(4). PIC X(10). PIC X(4).

PIC S9(5)V99 COMP-3.

PROCEDURE DIVISION. MOVE 'SELECT EMPNO,EMPNAME,SALARY FROM TAB1 WHERE DEPTNO = ? TO REC-TEXT. . MOVE LENGTH OF REC-TEXT TO REC-LEN. ACCEPT DEPTNO. EXEC SQL PREPARE PL1 FROM :REC END-EXEC. EXEC SQL OPEN C1 USING :DEPTNO END-EXEC. PERFORM PARA1 UNTIL SQLCODE NOT EQUAL TO 0.

Maples ESM Technologies Pvt. Ltd

Page 90 of 246

DB2

CPARA. EXEC SQL CLOSE C1 STOP RUN. PARA1. EXEC SQL FETCH C1 INTO :EMPNO,:EMPNAME, :SALARY END-EXEC. IF SQLCODE=100 GO TO CPARA. DISPLAY EMPNO EMPNAME SALARY. END-EXEC.

Triggers
A trigger is a set of actions that will be executed when a defined event occurs. The triggering events can be the following SQL statements: INSERT UPDATE DELETE

Triggers are defined for a specific table and once defined, a trigger is automatically active. A table can have multiple triggers defined for it, and if multiple triggers are defined for a given table, the order of trigger activation is based on the trigger creation timestamp (the order in which the triggers were created). Trigger definitions are stored in the DB2 catalog tables. SYSIBM.SYSTRIGGERS SYSIBM.SYSPACKAGE

Trigger Usage
Some of the uses of a trigger include:

Data Validation: Ensures that a new data value is within the proper range. This is similar to table check constraints, but it is a more flexible data validation mechanism.

Data Conditioning: Implemented using triggers that fire before data record modification. This allows the new data value to be modified or conditioned to a predefined value.

Maples ESM Technologies Pvt. Ltd

Page 91 of 246

DB2

Data Integrity: Can be used to ensure that cross-table dependencies are maintained.

The triggered action could involve updating data records in related tables. This is similar to referential integrity, but it is a more flexible alternative.

Trigger Activation
A trigger can be defined to be activated in one of two ways.

A before trigger: Will activate for each row in the set of affected rows before the triggering SQL statement executes. Therefore, the trigger body is seeing the new data values prior to its being inserted or updated into the table.

An after trigger: Will activate for each row in the set of affected rows or after the statement has successfully completed (depending on the defined granularity). Therefore, the trigger body is seeing the table as being in a consistent state. (All transactions have been completed).

By using the triggers we can Reduce the amount of application development and make development faster Provide a global environment for your business rules Reduce the maintenance of your application.

Trigger Example

CREATE TRIGGER TRGBIEMP NO CASCADE BEFORE INSERT ON EMP REFERENCING NEW AS n FOR EACH ROW MODE DB2SQL WHEN (N.SALARY < 5000) SIGNAL SQLSTATE 70003 (Salary should be >= 5000)

Maples ESM Technologies Pvt. Ltd

Page 92 of 246

DB2

Let us take the following example: Insert into emp values(E010,E,D001,4500) Before the above statement is executed the before trigger is fired and since the salary is not equal to or greater than 5000 it generates the following error

DSNT4081 SQLCODE =-438 ERROR: APPLICATION RAISED ERROR WITH DIAGNOSTIC TEXT: SQLSTATE = 70003 and the error message Salary should be >= 5000

In case the salary is equal or greater than 5000 the error would not be generated and the SQL statement would get executed.

CREATING AFTER TRIGGERS

Assume that as and when a row is inserted on the employee table the no of employees column in the DEPT table should be incremented by one.

(Structure of DEPT table: DEPTNO CHAR(4) NOT NULL PRIMARY KEY, DEPTNAME CHAR(10) NOT NULL, NOOFEMP INTEGER

Structure of EMP table : EMPNO CHAR(4) NOT NULL PRIMARY KEY, EMPNAME CHAR(10) NOT NULL, DEPTNO CHAR(4), SALARY DECIMAL(7,2) NOT NULL, FOREIGN KEY(DEPTNO) REFERENCES DEPT)

CREATE TRIGGER TRGAIEMP AFTER INSERT ON EMP REFERENCING NEW AS N1 FOR EACH ROW MODE DB2SQL UPDATE DEPT SET NOOFEMP=NOOFEMP + 1 WHERE DEPTNO=N1.DEPTNO

Maples ESM Technologies Pvt. Ltd

Page 93 of 246

DB2

Assume that as and when a row is deleted from the employee table the no of employees column in the DEPT table should be decremented by one.

CREATE TRIGGER TRGADEMP AFTER DELETE ON EMP REFERENCING OLD AS O1 FOR EACH ROW MODE DB2SQL UPDATE DEPT SET NOOFEMP=NOOFEMP - 1 WHERE DEPTNO=O1.DEPTNO

Maples ESM Technologies Pvt. Ltd

Page 94 of 246

DB2

Chapter 9 : Performance Monitoring/Tuning


Understanding the performance of the DB2 database management system, its databases, and active applications in a dynamic environment requires monitoring. The database administrator should gather information regarding the usage of database. An application programmer may also require SQL statement execution information regarding SQL statement.

The various DB2 facilities provide monitoring and gathering information for tuning process.

Performance tuning should be undertaken to improve the cost benefit ratio of the system and resource utilization.

Performance Tuning
The performance of an application can be monitored and enhanced in the application, as well as at the database level In application side the SQLs can be tuned to make them more efficient, and avoid redundancy It is better to structure the SQLs so that they perform only the necessary operations On the database side, the major enhancements can be done to the definitions of tables, indexes & the distribution of tablespace and indexspace The application run statistics are obtained from EXPLAIN or DB2PM (DB2 Performance Monitor) report

DB2 Optimizer
Analyzes the SQL statements and determines the most efficient way to access data - gives Physical data independence It evaluates the following factors : CPU cost, I/O cost, DB2 catalog statistics & the SQL statement It estimates CPU time, cost involved in applying predicates, traversing pages and sorting It estimates the cost of physically retrieving and writing the data The information pertaining to the state of the tables that will be accessed by the SQL statements are provided by the Catalog

Maples ESM Technologies Pvt. Ltd

Page 95 of 246

DB2

SQL Performance Factors

Introduction to the Optimizer


Optimizer, as its name implies, determines optimal method of satisfying a SQL request.

For example, SELECT EMPNO, WORKDEP, DEPNAME FROM EMP, DEP WHERE DEPNO = WORKDEP;

This statement, whether embedded statically in an application program or executed dynamically, must be passed through the DB2 optimizer before execution.

The optimizer parses the statement and determines the following: Which tables must be accessed, Whether the tables are in partitioned tablespaces, Which columns from those tables need to be returned, Which columns participate in the SQL statements predicates, Whether there are any indexes for this combination of tables and columns

Based on this information, the optimizer analyses the possible access paths and chooses the best one for the given query. An access path is the navigation logic used by DB2 to access the requisite data. The optimizer usually produces a better access path than a programmer could develop manually.

Influencing the Access path


The first option is to change the SQL statement. The drawback of this option is DB2 gets frequently enhanced and upgraded. If a future DB2 release changes the performance feature you took advantage of, your SQL statement may degrade.

Maples ESM Technologies Pvt. Ltd

Page 96 of 246

DB2

The second method of influencing DB2s choice of access path is to update the statistics in the DB2 catalog on which the optimizer relies. In order to update DB2 catalog statistics, you must have been given the authority to update the specific DB2 catalog tables (or columns) or have SYSADM authority.

Complex SQL Guidelines


The four categories of complex SQL statements are Joins Subqueries Unions Grouping.

UNION versus UNION ALL

The UNION operator always results in a sort. When the UNION operator connects two SELECT statements, both SELECT statements are issued, the rows are sorted and all duplicates are eliminated. To avoid duplicates, use the UNION operator.

The UNION ALL operator does not invoke a sort. The SELECT statements connected by UNION ALL are executed, and all rows from the first SELECT statement are appended to all rows from the second SELECT statement. Duplicate rows here still exist.

Use Joins instead of Subqueries

A join can be more efficient than a correlated subquery or a subquery using IN.

For example, this query joins two tables.

SELECT EMPNO, LASTNAME FROM

EMP, PROJ

WHERE WORKDEP = DEPNO AND EMPNO = RESPEMP;

The preceding example is usually more efficient than the following query.

SELECT EMPNO, LASTNAME FROM

EMP X

Maples ESM Technologies Pvt. Ltd

Page 97 of 246

DB2

WHERE WORKDEP = (SELECT DEPNO FROM PROJ WHERE RESPEMP = X.EMPNO);

The preceding two queries demonstrate how to turn a correlated subquery into a join.

Similarly, you can also translate non-correlated subqueries into joins.

For example, the join

SELECT

EMPNO, LASTNAME FROM

EMP, DEP

WHERE WORKDEP = DEPNO AND DEPNAME = PLANNING;

is usually more efficient than the subquery

SELECT EMPNO, LASTNAME FROM EMP WHERE WORKDEP IN (SELECT DEPNO FROM DEP WHERE DEPNAME = PLANNING);

Access Path & Optimization:

To know how a query will be executed by DB2, we must analyze its access path, which is the method for retrieving data from the specific table. The EXPLAIN facility will provide information about how DB2 access the data to resolve the SQL statements.

The optimization is done at the time of execution of SQL statements and at the time of binding process. The method used to retrieve data from table is called Access Plan. The access plan for dynamic SQL statements is not stored in the system catalog. Index Usage: Index is an ordered set of points to the data in a DB2 table In DB2, it is used when we use keywords like IN, BETWEEN, ORDER BY, GROUP BY, DISTINCT

Maples ESM Technologies Pvt. Ltd

Page 98 of 246

DB2

Explain Function
A plan, package, or SQL statement when it is bound. The output appears in a table you create called PLAN_TABLE, which is also called a plan table.

Obtains information on how current and projected SQL statement will be executed Access Path(INDEX vs Tablespace scan) Names of indexes used DB2 sort requirements Sequence of steps for subquery processing Tablespace locking requirements

Can be applied to: An individual SQL statement SELECT, UPDATE, INSERT, DELETE All explainable statements in a plan (or) package

Syntax for EXPLAIN is:

EXPLAIN ALL SET QUERY NO = n FOR SQL Statement

Invokes the DB2 optimizer Rows get inserted into user created table

Gathering EXPLAIN Data

There are two different ways to populate the PLAN_TABLE.

Maples ESM Technologies Pvt. Ltd

Page 99 of 246

DB2

Executing the SQL Statement EXPLAIN

You can populate PLAN_TABLE by executing the SQL statement, EXPLAIN. In the statement, specify a single explainable SQL statement in the FOR clause. You can execute EXPLAIN either statically from an application program, or dynamically, using QMF or SPUFI.

Binding with the option EXPLAIN (YES)

You can populate PLAN_TABLE by executing the SQL statement, EXPLAIN. In the statement, specify a single explainable SQL statement in the FOR clause. You can execute EXPLAIN either statically from an application program, or dynamically, using QMF or SPUFI.

Before you can use EXPLAIN, you must create the PLAN_TABLE to hold the results of EXPLAIN. A copy of the statements needed, to create the table are in the DB2 sample library, under the member name DSNTESC.

Note: DB2 does not automatically delete rows from the PLAN_TABLE. To clear the table of obsolete rows, use DELETE, just as you would for deleting rows from any table.

Maples ESM Technologies Pvt. Ltd

Page 100 of 246

DB2

Chapter 10 : Locking and Concurrency

Locking Data
Data that is defined as sharable can be accessed by any DB2 in the group. Several subsystems can read and write simultaneously against the same data, this is controlled by locking mechanism of DB2. IRLMPROC will take care of the locking services of DB2 to maintain the concurrency control and consistency of data.

DB2 allow more than one application to access the same data at essentially same time. This is known as concurrency. To control such undesirable results such as lost updates, access to uncommitted data and unrepeatable reads, concurrency must be controlled. DB2 uses lock to control concurrency.

DB2 locks can be compared in four basic aspects: object, size, duration, and mode.

Object of lock is the resource being locked.

Size of lock can be page, table or tablespace

Duration of lock is the length of time the lock is held. It varies according to when the lock is acquired and released. This is controlled by bind options ACQUIRE, RELEASE and ISOLATION.

Mode of lock tells what access to the locked object is permitted to the lock owner and to any concurrent application processes.

Each plays a role in the acquisition and release of a lock. More than one type of lock can exist for a specific user for a particular table space. This will depend on the mode of the lock. For example, locks might be held on the table space, table, page, and row simultaneously for a particular table space. Each lock size will have a mode during its existence.

Maples ESM Technologies Pvt. Ltd

Page 101 of 246

DB2

Page Lock Modes:


S (SHARE) The lock owner and any concurrent processes can read but cannot change the locked page. Concurrent processes can acquire S or U locks on the page. Want to read-only Allow others read-only No one can update

U (UPDATE) The lock owner can read but not change the locked page; however the owner can promote the lock to an X lock and then can change the page. Want to read with possibility of update Allow others read-only No other user can update

X (EXCLUSIVE) The lock owner can read or change the locked page. Concurrent processes cannot acquire any lock on the page nor can they access the locked page. Want to update Not allow any other access User needs exclusive use of the table/table space. No other user is allowed.

Lock Duration
Duration of the lock is determined by the BIND ACQUIRE / RELEASE parameters.

These options used to specify when DB2 is to lock the table or table spaces and when to release them.

ACQUIRE (ALLOCATE) / RELEASE (DEALLOCATE)

This option avoids deadlocks by locking your resource at the beginning. Use this option if processing efficiency is more important than concurrency.

Maples ESM Technologies Pvt. Ltd

Page 102 of 246

DB2

All tables or table spaces are locked when the plan is allocated and released only when the plan is terminated.

This option reduces concurrency. It can lock resources in high demand for longer than needed.

ACQUIRE (USE) / RELEASE (DE-ALLOCATE)

The table or table space is locked only when it is needed while running. All table and table spaces are unlocked only when the plan terminates.

ACQUIRE (USE) / RELEASE (COMMIT)

This is the default option and provides greater concurrency.

The table or table space is locked only when needed. The lock is released when a SQL COMMIT or ROLLBACK statement is issued or when the application process terminates.

This option can increase the frequency of deadlocks.

ISOLATION option
The isolation levels directly effect the duration that locks are held. The isolation levels that can be used either at bind time or with an individual SQL statement are: ISOLATION(CS) Or Cursor Stability o Acquires and releases page locks as pages are read and processed. CS provides the greatest level of concurrency at the expanse of potentially different data being returned by the same cursor if it is processed twice during the same unit of work. ISOLATION(RR) Or Repeatable Read (DEFAULT): o Holds page and row locks until a COMMIT point; no other program can modify the data. If data is accessed twice during the unit of work, exactly the same data will be returned ISOLATION(RS) Or Read Stability o Holds the page and row locks until a COMMIT point, but other program can insert new data. If data is accessed twice during the unit of work, new rows may be returned, but old rows will not have changed

Maples ESM Technologies Pvt. Ltd

Page 103 of 246

DB2

UR Uncommitted Read o Is also known as dirty read processing. UR avoids locking altogether, so data can read that never actually exists in the database.

Locking Issues & Problems


There are times when too much locking can be a problem. This possibly can result in suspensions, timeouts, or even deadlocks.

Timeouts & Deadlocks


While waiting for a lock, a process can exceed an allowable amount of wait-time that has been established. A system-wide option determines a maximum time a process can wait before it gets a resource unavailable error. This value is called the resource timeout value and is calculated by the following formula.

Divide RESOURCE TIMEOUT by DEADLOCK TIME. Round the result upto the next largest integer. Multiply this integer by the DEADLOCK TIME. Multiply the result by the appropriate factor.

Effects of DB2 locks:


The IMS resource lock manager (IRLM) is responsible for managing all requests for locks, and controlling access to DB2 databases.

Maples ESM Technologies Pvt. Ltd

Page 104 of 246

DB2

Suspension:
The IRLM suspends an application process if it requests a lock on an object that is already owned by another application process and cannot be shared. The suspended process is said to be Waiting for the lock. The process resumes running when the lock is available.

Timeout:
Timeout occurs when the application process is suspended for longer than a preset interval. DB2 reports a timeout by returning a SQLCODE of 911 or 913 to the process.

Deadlock: A deadlock occurs when 2 or more application processes each hold lock on resources that the others need and without which they cannot proceed further. After the end of the preset time interval, DB2 can rollback the current unit of work for one of the processes, or request the process to terminate. That frees the locks and allows the remaining processes to continue.

Maples ESM Technologies Pvt. Ltd

Page 105 of 246

DB2

Chapter 11 : DB2 Utilities


All of IBMs relational Database management products have utilities to assist in the job of maintaining the data. There are some differences in the utilities supplied with the different products but,in general,there are some major capabilities that all the products address.The

purpose of this unit is to introduce you to those major capabilities and provide an overview of the specific utilities within DB2.

Objectives.

Describe the major functions of relational database utilities List what utilities perform what function State when you should use certain utilities

Utilities are special programs that can run by submitting JCL. They run in batch and get their control information via control statements (not through SQLs). Utilities work at the object level and not at row or data items level.

DB2 receives many requests from many users to access the same data besides this request from utility. DB2 provides data security while running any utilities.

There are two types of DB2 utilities: Online utilities Stand-alone utilities

DB2 online utilities run as standard MVS batch jobs, and they require DB2 to be running. They invoke DB2 control facility services directly.

The stand-alone utilities execute as batch jobs independent of DB2. They can be invoked only by means of MVS JCL. They dont require DB2 to be up while running standalone utilities.

Maples ESM Technologies Pvt. Ltd

Page 106 of 246

DB2

DB2 Online Utilities


Commonly used Online Utilities in DB2 Application Programming RUNSTATS REORG CHECK COPY MERGECOPY LOAD UNLOAD REPORT STOSPACE QUIESCE

All online utilities fall under three categories Set up or Move Utilities(data organization) Maintenance Utilities Backup andRecovery Utilities

Set up and Move utilities


LOAD To accomplish bulk inserts into DB2 table Can replace the current data or append to it, i.e. LOAD DATA REPLACE or LOAD DATA RESUME(S) If a job terminates in any phase of LOAD REPLACE the utility has to be terminated and rerun If a job terminates in any phase other than UTILINIT(which sets up and initializes the LOAD utility), the tablespace must be first restored using the full RECOVER, if LOG NO option of the LOAD was mentioned. After the tablespace is restored, the error is to be corrected, the utility terminated and the job rerun.

Maintenance Utilities
RUNSTATS scans a table or index space to gather information about the utilization of space and the efficiency of indexes

Maples ESM Technologies Pvt. Ltd

Page 107 of 246

DB2

This information is then stored in the DB2 catalog and used by the SQL optimizer to select access paths to data

REORG Reorganizes a table space to improve access performance and reorganizes indexes so that they are more efficiently clustered.

Backup Utilities

CHECK Checks the integrity of DB2 data structures Checks the referential integrity between two tables and also checks DB2 indexes for consistency Can delete invalid rows and copies them to a exception table Use CHECK DATA when loading a table without specifying the ENFORCE CONSTRAINTS option or after the partial recovery of tablespaces in a referential set

COPY Used to create an imagecopy for the complete tablespace or a partition of the tablespace full imagecopy or incremental imagecopy Every successful execution of COPY utility places in the table SYSIBM.SYSCOPY, atleast one row that indicates the status of the imagecopy

MERGECOPY The MERGECOPY utility combines multiple incremental image copy data sets into a new full or incremental imagecopy data set

Recover Utilities
RECOVER utility A table space can be recovered either to the current state or to a previous state. Backup

copies(generated by the COPY utilility) of a table space are required for a table space recovery. RECOVER uses full image copies, incremental copies, and the DB2 log to recover a table space. REPORT utility.

Maples ESM Technologies Pvt. Ltd

Page 108 of 246

DB2

The REPORT utility provides recovery information about a table space, and the names of all table spaces and tables in a table space set(a table space set is agroup of referentially related tables). The information generated by REPORT can be used to determined what backups exists for a table space, and which table spaces to back up and recover together.

QUIESCE utility The QUIESCE utility establishes a quiesce point(the current log RBA) for a table space, and inserts it into the Catalog table SYSCOPY. This allows one to recover a table space to a known point in time by running the RECOVER utility and specifying a RBA to fall back to.

STOSPACE Utility The STOSPACE utility updates DB2 catalog columns that indicate how much space is allocated for storage group and related tablespace and indexes.

Stand Alone Utilities.


There are number of utilities that can be executed outside of DB2 environment. These are often referred to as standalone or offline utilities.

DSN1COPY With the DSN1COPY ,you can copy DB2 VSAM datasets to sequential datasets. DB2 image copy data sets to DB2 VSAM datasets. DSN1COPY sequential datasets to other sequential datasets.

These copies can be used to restore data.The restore can occur on the same DB2 or another DB2 subsystem.This is one way to be able to move data between subsystems. Using DSN1COPY, you can also print hexadecimal dumps of DB2 datasets and databases,check the validity of data or index pages,translate database objects identifiers to enable moving datasets between different systems. DSN!LOGP This utility formats the contants of the recovery log for display.

DSN1PRNT: With this utility you can print DB2 VSAM datasets that contain tablespaces or

indexspaces,imagecopy datasets,sequential dataset that contain DB2 tablespace or indexspace.

Maples ESM Technologies Pvt. Ltd

Page 109 of 246

DB2

Chapter 12 : DB2 Environment for OS/390 and Z/OS

DB2 operates as a formal subsystem of OS/390 and Z/OS.


DB2 utilities run in the batch environment, and applications that access DB2 resources can run in the batch, TSO, IMS or CICS environments.

IBM provides attachment facilities to connect DB2 to each of these environments.

The DB2 database management system operates as a formal subsystem of the OS/390 and Z/OS operating system.

DB2 processes can be executed in several different address space regions within OS/390 and Z/OS, such as IMS or CICS.

Attachments

Attachments, facilities provide the interface between DB2 other environments. These facilities include CICS, IMS, TSO, CAF, and RRS.

DB2 with CICS (Customer Information Control System)


CICS is an application server that provides online transactions management for applications. In order to connect to DB2 from this environment you can use the CICS attachment facility. This attachment facility allows access to DB2 data from the CICS environment.

A CICS application can access both DB2 and CICS data and in the event of a failure, CICS coordinates the recovery between DB2 and CICS.

Once the DB2 subsystem has been started, DB2 can be operated from a CICS terminal. DB2 and CICS can be started independently of each other. The connection can also be made to be automatic. The following figure shows the relationship between CICS and DB2.

Maples ESM Technologies Pvt. Ltd

Page 110 of 246

DB2

CICS Connections CICS Address Space

DB2 Subsystem

DSN1MSTR Address Space

Other DB2 Related Address Spaces

DB2 with TSO (Time Sharing Option)


TSO allows for interactive time sharing capabilities from remote terminals. In order to connect to DB2, you can use the TSO CAF (Call Attachment Facility) and the RRS (Resource Recovery Services).

Using TSO, you can bind application plans and packages and execute several online functions to DB2. Application programs and databases can be created, modified, and maintained via the TSO attach. You can run in either the foreground or batch when accessing DB2.

Access to two different command processors is allowed when using TSO: DSN Command Processor DB2 Interactive (DB2I) The DSN command processor runs as a TSO command processor using the attachment facility. It provides an alternative method for executing programs in a TSO environment that accesses DB2. This processor can be invoked from the foreground by issuing a TSO command or from batch by invoking the TMP (Terminal Monitor Program) from an MVS batch job passing the commands in the SYSTIN data set to TMP. When DSN is running and DB2 is up, you can issue DB2 or DSN command.

Maples ESM Technologies Pvt. Ltd

Page 111 of 246

DB2

TSO

DB2 Subsystem

DSN Command Processor Connection

DB2I

ISPF

DSN1MSTR Address Space Other DB2 Related Address Spaces

Address Space

The DB2I is comprised of ISPF panels that allow for an interactive connection to DB2 and invokes the DSN command processor. With this processor you can invoke utilities, issue commands, and run SQL statements.

The TSO attachment facilities, is used by the majority of TSO applications. The following figure shows the relationship between DB2 and TSO.

CAF (Call Attach Facility)


The call attach facility is a DB2 facility used for application programs that run under TSO or MVS batch. The CAF is an alternative to the DSN command processor and provides greater control over the execution environment.

RRSAF (Recoverable Resource Services Attachment Facility)


RRSAF is a DB2 sub-component that uses OS/390 Transaction Management and Recoverable Resource Manager Services to coordinate resource commitment between DB2 and all other resource managers that also use OS/390 RRS in an OS/390 subsystem.

Maples ESM Technologies Pvt. Ltd

Page 112 of 246

DB2

Appendix

Common SQL Codes


SQL CODES -117 -136
The number of values you are trying to INSERT

EXPLANATION

does not match the number of columns


Sort cannot be executed because the Sort Key Length is greater than 1000 bytes. -137 -138 -150 Result of Concatenation too long The second or third Argument of the SUBSTR Function is out of Range. The Object of the Insert, Delete or Update Statement is a view for which the requested operation is not permitted. -151 The Column < Column-Name > cannot be updated because it is either included in the partitioning key of a Partitioned TableSpace or derived from a SQL Function or Expression. -153 -154 The Create View Statement does not include a required Column List. The Create View Failed because the View Definition contains a union or union all. -156 Alter Table, Drop Table, Lock Table, or Create Index Statement identifies a View. -158 The Number of Columns specified for the View is not the same as the number of columns specified by the Select Clause. -159 -160 -161 The Name specified on the Drop View is a Table Name The WITH CHECK Option cannot be used for the Specified View. The Insert or Update is not allowed because a resulting row does not satisfy the new definition. -164 -170 -171 It does not have the Privilege to Create the View with Qualification. The number of arguments specified for Function-name is invalid. The Data Type, Length, Value of Argument of Function-name is Invalid

Maples ESM Technologies Pvt. Ltd

Page 113 of 246

DB2

-172 -180 -181 -182 -183

Function-Name is not a Valid Function-Name. The String Representation of a DATETIME value has an invalid Syntax. The String Representation of DATETIME value is not a valid Value. An Arithmetic Expression with a DATETIME value is Invalid. An Arithmetic Operation on a Date or Timestamp as a result that is not within the valid range of Dates.

-184

An Argument expression with a Date Time Value contains a Parameter marker.

-185

The Local format Option has been used with a Date or Time and no Local Exit has been installed.

-186

The Local date length of Local Time Length has been increased and executing Program relies on the Old Length.

-198

The Operand of the Prepare or Execute Immediate Statement is Blank or Empty.

-199 -203 -204 -205 -206

Illegal use of KEYWORD Keyword. Token Token-list was expected . A Reference to Column Column-Name is ambiguous. NAME is an undefined Name. COLUMN-NAME is not a Column of Table TABLE-NAME. COLUMN-NAME is not a Column of a Inserted Table, Update Table, or any Table identified in a FROM Clause.

-207

The ORDER BY Clause is Invalid because it includes a Column Name but it applies to the Result of a UNION or UNION ALL.

-208

ORDER BY Clause is invalid because Column Name is not part of Result Table.

-219 -220

The Required Explanation Table TABLE-NAME does not exist. The Column COLUMN-NAME in Explanation Table TABLE-NAME is not defined Properly.

-301

Value of a host variable cannot be used as specified because of its Data Type.

-302 -303

The Value of an Input Variable is too large for the target Column. A value cannot be assigned to a Host Variable because the Data types are not Compatible.

-304

The Value with Data Type DATA-TYPE1 cannot be assigned to a Host

Maples ESM Technologies Pvt. Ltd

Page 114 of 246

DB2

Variable because the Value is not within the Range of the Host Variable in Position POSITION-NUMBER with Data-type DATA-TYPE2. -305 The Null Value cannot be assigned to a Host Variable because no Indicator Variable is specified. -309 A Predicate is Invalid because a Referenced Host Variable has the Null Value. -310
DECIMAL HOST VARIABLE OR PARAMETER CONTAINS NON-DECIMAL DATA

-311 -312 -313

The indicated length of a Host Variable is negative. Undefined or Unusable Host Variable VARIABLE-NAME. The number of Host Variables specified is not equal to the number of Parameter Markers.

-401

The Operands of an Arithmetic or Comparison Operation are not Comparable.

-402

An Arithmetic Function or Operator ARITH-FOP is applied to Character or DATETIME Data.

-404

The Update or Insert Statement Specifies a string that is too long COLUMN-NAME.

-405

Numeric Literal LITERAL Cannot be used as specified because it is out of Range.

-406

A Calculated or Derived Numeric Value is not within Range or its Object Name.

-407

An Update or Insert Value is Null but the Object Column COLUMN-NAME cannot contain Null Values.

-408

An Update or Insert Value is not comparable with the Data type of its object Column COLUMN NAME.

-409 -410 -411 -412 -413 -414

Invalid Operand of a Count Function. The Floating Point Literal LITERAL Contains more than 30 Characters. The Current Date-Time or User keyword cannot be used as Specified. The Select Clause of the Sub-query Specifies Multiple Columns. Overflow Occurred during Data Type Conversion. The Numeric or DateTime Column COLUMN-NAME is specified in a Like Predicate

Maples ESM Technologies Pvt. Ltd

Page 115 of 246

DB2

-415

The corresponding Columns, COLUMN-NUMBER, of the Operands of a UNION or UNION ALL do not have Comparable Column Descriptions.

-416 -417

An Operand of a UNION contains a Long string Column. A Statement String to be Prepared includes Parameter markers as the Operands of the Same Operator.

-418

A Statement String to be prepared contains an Invalid Use of Parameter Markers.

-419

The Decimal Divide Operation is invalid because the result would have a negative Value.

-421

The Operands of a UNION or UNION ALL do not have the same number of Columns.

-501 -502 -503

The Cursor identified in a Fetch or Close Statement is not Open. The cursor Identified in an Open statement is already Open. A Column cannot be Updated because it is not identified in the Update Clause of the Select Statement of the Cursor.

-504 -507 -508

The Cursor Name CURSOR-NAME is not defined The Cursor Identified in the Update or Delete Statement is not open. Cursor identified in the update or Delete Statement is not positioned on a Row.

-509

The Table identified in the Update or Delete Statement is not the same tabledesignated by the Cursor.

-510

The Table designated by the Cursor of the Update or Delete Statement cannot be modified.

-511

The FOR UPDATE Clause cannot be specified because the Table designated by the Cursor cannot be Modified.

-514 -516 -517

The Cursor CURSOR-NAME is not in a prepared Table. The Describe Statement Does not identify a Prepared Statement. Cursor CURSOR-NAME cannot be used because its Statement name does not identify a Prepared Select Statement.

-518 -519

The execute statement does not identify a Valid Prepared Statement. The Prepare Statement identifies the Select Statement of the Opened Cursor CURSOR-NAME.

-532

Referential integrity (DELETE RESTRICT rule) prevents the DELETE

Maples ESM Technologies Pvt. Ltd

Page 116 of 246

DB2

-539 -540

TABLE DOES NOT HAVE A PRIMARY KEY THE DEFINITION OF TABLE IS INCOMPLETE BECAUSE IT LACKS A PRIMARY INDEX OR A REQUIRED UNIQUE INDEX

-551

AUTH-ID Does not have the Privilege to perform Operation OPERATION On Object OBJECT-NAME.

-552 -554 -555 -556 -557

AUTH-ID Does not have the Privilege to perform Operation OPERATION. An Authorization ID cannot grant a privilege to itself. An Authorization ID cannot revoke a privilege to itself. A privilege cannot be Revoked because it is not possessed by AUTH-ID. Inconsistent Grant/revoke Keyword, Permitted Keywords are KEYWORDLIST.

-559 -601

All Authorization Functions have been Disabled. The Name of the Object to be created is identical to the existing name NAME of the Object Type OBJ-TYPE.

-602 -603

Too many Columns specified in a Create Index. A Unique Index cannot be created because The Table contains Rows which are Duplicate with respect to the Values of the identified Columns.

-604

A Column definition Specifies an Invalid Length, precision or Scale Attribute.

-607 -612 -614

Operation OPERATION is not defined for system Tables. COLUMN-NAME is a duplicate Column Name. The Index cannot be created because the Sum of the Internal Lengths of the identified Columns is greater than the allowable Maximum

-616

OBJ-TYPE1 OBJ-NAME1 Cannot be dropped because it is referenced by OBJ-TYPE2 and OBJ-NAME2.

-618 -619 -620

Operation OPERATION is not allowed on system Databases. Operation disallowed because the WorkFile Database is not stopped. Keyword KEYWORD in STMT-TYPE Statement is not permitted for a Table Space in the WorkFile Database.

-623 -636 -637

A Clustering index already exists on the Table TABLE-NAME The Partitioning Keys are not specified in Ascending/Descending Order. Duplicate Keyword ( KEYWORD ).

Maples ESM Technologies Pvt. Ltd

Page 117 of 246

DB2

-644

Invalid Value specified for Keyword KEYWORD in STMT-TYPE Statement.

-646

Table TABLE-NAME Cannot be created in Partitioned/Default TableSpace T-SPACE-NAME because it already contains a Table.

-647

Buffer-pool BP-NAME Cannot be specified because it has not been activated

-652 -653

Violation of Installation Defined Edit or Validation Procedure PROC-NAME Table TABLE-NAME in Partitioned TableSpace T-SPACE-NAME is not available because its Partitioned Index has not been Created.

-660

Index INDEX-NAME Cannot be Created on Partitioned TableSpace TSPACE-NAME because Key Limits are not Specified.

-661

Index INDEX-NAME Cannot be created on the Partitioned TableSpace TSPACE-NAME because the Number of part Specifications is not Equal to the Number of Partitions of the TableSpace.

-662

A Partitioned Index Cannot Be Created on a Non-Partitioned TableSpace T-SPACE-NAME

-663

The Number of Key Limit Values is either zero or greater than the number of columns in the Key of Index INDEX-NAME.

-664

The Internal Length of the Limit Key Fields for the Partitioned Index INDEX-NAME exceeds the length imposed by the Index Manager.

-665 -666

The PART Clause of an ALTER Statement is omitted or Invalid. STMT-VERB Object cannot be Executed because the utility is in Progress.

-667

The Clustering Index For a Partitioned TableSpace cannot be explicitly Dropped.

-668

Column cannot be added to the Table because the table has an Edit Procedure.

-669 -670 -671

A Table in a Partitioned TableSpace cannot be Explicitly Dropped. The Record Length of the Table exceeds the Page Size Limit. The Bufferpool Attribute of the TableSpace cannot be altered as specified because it would change the Page Size of the TableSpace.

-676 -677

A 32K Page Bufferpool may not be used for BufferPool Expansion. Insufficient Virtual Storage For Bufferpool Expansion.

Maples ESM Technologies Pvt. Ltd

Page 118 of 246

DB2

-678

The Literal LITERAL Specified for the Index Limit Key must Conform to the Data Type DATA-TYPE of the Corresponding Column COLUMNNAME.

-679

The Object NAME Cannot be Created because a drop id Pending on the Object.

-680 -681

Too Many Columns specified for a Table. Column COLUMN-NAME in Violation of Installation defined field Procedure. RT: Return Code, RS : Reason Code , MSG : Message Token.

-682 -683 -684 -685 -686

Field Procedure PROCEDURE-NAME could not be loaded. Invalid Column Type for FIELDPROC Option, COLUMN-NAME. The Length of Literal List Beginning STRING is too long. Invalid Field Type, COLUMN-NAME. Column Defined with a field Procedure cannot compare with Another Column with different Field Procedure.

-687 -688

Field Types Incomparable. Incorrect Data Returned from Field Procedure, COLUMN-NAME, MSGNO.

-80N -802

Usually means that the DB2 Bind did not work or was used by others. Exception error EXCEPTION-TYPE has occurred during OPERATIONTYPE operation on DATA-TYPE Data, position POSITION-NO.

-803

One or more insert or update values are invalid because the object columns are constrained such that no two rows of the table can be duplicates with respect to the values of those columns.

-804

An error was found in application program input parameters for SQL statements.

-805 -811

Program name PROGRAM-NAME not found in plan PLAN-NAME. The result of an embedded select statement is a table of more than one row, or the result of the subquery of a basic predicate is more than one value.

-815

A GROUP BY or HAVING clause is implicitly or explicitly specified in an embedded select statement or a subquery of a basic predicate.

Maples ESM Technologies Pvt. Ltd

Page 119 of 246

DB2

-817

The INSERT, UPDATE, DELETE, DDL or AUTHORISATION statement cannot be executed because the IMS / VS transaction is inquiry only.

-818

The precompiler generated Timestamp X in the load module is different from the Bind Timestamp Y built from the DBRM. Answer: Compile and Bind must have the same Timestamp. Rebind or Recompile and then Rebind.

-819 -820

View cannot be recreated because it references a view that could not be recreated The SQL statement cannot be processed because CATALOG-TABLE contains a value that is not valid in this release. View VIEW-CREATOR. VIEW-NAME has been dropped during migration. Creator SYNONYM-CREATOR of synonym SYNONYM-NAME could not be resolved

-821

-822 -840 -901

The SQL DA contains a invalid data address or indicator variable address. Too many items returned in a select or insert list. Unsuccessful execution caused by a system error that does not preclude the successful execution of subsequent SQL statements.

-902

Unsuccessful execution caused by a System error that precludes the successful execution of subsequent SQL Statements.

-904

Unsuccessful execution caused by an unavailable Resource reason REASON-CODE, Type of Resource RESOURCE-TYPE & Resource name RESOURCE-NAME Unavailable Resource reason 00c90097, TYPE=200 means that you are trying to insert to a Table that does not have write Capability authorized for it. Contact your DB2 Authorization God. Unavailable Resource Reason 00d70024, TYPE=220 DB2 Table Migrated. Do HRECALL on the Dataset named on Error Line beginning with NW20DB2T.DSNDBC

-906 -909 -910

The SQL Statement cannot be executed because this function is disabled due to a Prior Error. The Object has been Deleted. SQL Statement Cannot access an object on which a Drop or Alter is Pending.

Maples ESM Technologies Pvt. Ltd

Page 120 of 246

DB2

-911

The current unit of work has been rolled back due to deadlock or Timeout. Reason REASON-CODE, Type of Resource RESOURCE-TYPE, and Resource Name RESOURCE-NAME.

-913

UnSuccessful execution caused by deadlock or Timeout. Reason REASON-CODE, Type of Resource RESOURCE-TYPE, and Resource Name RESOURCE-NAME.

-922

Connection Authorization Failure: ERROR-TYPE Error. Make sure your Plan in the DSN with the DDNAME DDITV02 is the same one you bound with. TSKXB 93-04-23

-923

Connection not Established : DB2 CONDITION Reason REASON_CODE, Type RESOURCE-TYPE, Name RESOURCE-NAME.

-924

DB2 Connection Error: FUNCTION-CODE, RETURN-CODE, REASONCODE

-925 -926 -927

Commit Not Valid in IMS/VS or CICS/OS/VS Environment. RollBack Not Valid in IMS/VS or CICS/OS/VS Environment. The Language Interface LI was called when the connecting environment was not established. The Program should be invoked under the DSN Command.

Error Codes
SYSTEM CODE S000 EXPLANATION Could mean that no IMS segments were selected by DLI call. Look for status code of GE and check your SSA qualifications. S001 Probably incorrect DCB information. Checking RECORDING MODE and BLOCK CONTAINS clauses in COBOL FD as compared with RECFM of JCL. Check LRECL and BLKSIZE of JCL as compared with the number of characters in the 01 level(s) under the FD in the program. Check for correct tape mounted. Current release of COBOL II takes its recording mode from the 01 items below FD in determining fixed or variable and maximum record length. Trying to open a dataset that is cataloged but never has been opened or closed.

Maples ESM Technologies Pvt. Ltd

Page 121 of 246

DB2

S002 S013 S02A

Same as S001 Same as S001 Sometimes happens in changeman for no apparent reason. It usually is no problem. Just press enter. Worst case, sign off changeman or tso and back on; problem gone. Check DCB info information must be identical when using a file in more than one place Cannot dummy a VSAM file? Forgot to prime the pump with an initial FETCH (read) before trying to insert or replace using the cursor values (DB2) If DBUTIL abends set UTPROC = RESTART when restarting job. DB2 jobs that abend with S04E usually means DB2 table was migrated and job issued recall and then abended waiting for HSM. Check reason code and DB2 sysprint for added information. Eg. Dataset Names : prod : NW40DB2P.DSNDBD.XXXXXX.YYYYYY.IXXX.AXXX test : NW20DB2T.DSNDBD.XXXXXX.YYYYYY.IXXX.AXXX test : NW20DB2T.DSNDBC.XXXXXX.YYYYYY.IXXX.AXXX XXXXXX and YYYYYY are often in the sysprint information.

S03B

S04E

S04E

This happens when a db2 job abends using a utility id and the utility id has not been cleaned up yet. Go into option n.d.7 display utility ids pending and then term the pending utilids related to your user id. =N.D.7 DISPLAY UTILIDS 1 === > - DIS UTITILITY(*) TERM UTILIDS 1 === > - TERM UTITILITY(TSTGML01.STEP20)

SOC1

Program ID not right Probably a call to an unlinked module; ABEND at location 2, 4 or 6 usually. Can be the result of a call to ABENDX Sometimes caused by a read or write to an unopened file ABEND at location 48 or 4800 or 52 or 5200 In each case, check register 14 for program error location May be caused by bad subscripting or indexing More short record from input buffer; check for BUFL option in JCL DCB field.

SOC4

More parms in called module than in calling module Directory block full will cause SOC4 in module init routines.

Maples ESM Technologies Pvt. Ltd

Page 122 of 246

DB2

In TSO dialog full profile, change call to use diff profile. SOC4 11 can be bad index on a VSAM file. Repro file to check. Can also be using incorrect PSB for database if segments are changed recently. "UNABLE TO OPEN D????X01" means you are using an update PSB and the database is allocated online. Mixed RES/NORES job can cause other abends - often SOC4. ABEND in IGZ module of link can be incompatible subroutines. Include IGZCPCO IGZENRI IGZENRT and ILBOSRV in the start of your link. Could also cause SOC6 or SOC1.

SOC5 SOC6 SOC7

Last data set of a concatenation empty. COBOL sort cannot concatenate disk and tape (JCL sort can ) NOMAD read past end of file May need to execute DBAU03P instead of DBAU03T READY TRACE used in a module that is linked to a COBOL II module. Also make sure if verbs end with end-if

Same causes as OC4 Same causes as OC1. (May be executing an old version of the program.) Check for bad data maybe defined as COMP, COMP-3 or incorrect location. Could also be bad subscripting.

SOCB S106

Divisor is zero If register 15 contains a C, not enough core was available If register 15 contains an F, look for the message FETCH FAILED FOR MODULE XXXXXXXX RETURN CODE XX. If you find this message resubmit the job if you still get a F check your input data sets. Fixed by overriding the REGION size in DBTSTQLD JCL Data set not found check spelling of dsn Check vol-ser parameter. Check if data set has been scratched. Check VSAM vs Sequential in select statement of COBOL program If 213-70 and are printing a member in a PDSE you cant be in edit mode for that member.

S122 S213

Job cancelled by operator with dump

S222 S237

Job cancelled by operator without dump Abend at end of volume. If input tape, check end of output and if ok, ignore abend

S2F3

System crashed while running your program. Also gives a Jcl error msg.

Maples ESM Technologies Pvt. Ltd

Page 123 of 246

DB2

Resubmit job S30A S322 Add DCB=nnnn, to your JCL Time out on a job. Check the class the job is running in. See TSO JOBCLASS for what types of jobs run in which classes Check for valid DSN or valid DISP USER=888, REASON=0000000 Try increasing region size, usually when IKJEFT01 utility S4EC If you have specified more than one volume in the JCL VOL=SER parm, remove all but one S497 A program called the common abend module GPXCDABN and the error message is displayed. This reusable abend module allows more detailed messages up to 300 bytes S522 S706 Interactive session timed out Program not found: Check link to see program(s) were included Check link name S722 S737 S806 OUTLIM maximum has been reached Missing or empty data set in a concatenation Program not found : Check program name being executed Check JOBLIB or STEPLIB card Check executive compiled DYNAM. Link to other modules via a link job will NOT resolve called modules. Dynamic environment : Is a module compiled as DYNAM? Is DYNAM LIB in the execute JCL? If call to other than PROGRAM-ID, you need to LINK step of translate / link of called module change the SYSLIN to add a line ALIAS calledentry. ( A space ahead of ALIAS ). Has occurred when VSAM files dummied out. S813 The tape VOL-SER number does not match the tape DSN. Either the tape VOL-SER number is wrong, the G000V00 is wrong, or the tape DSN is incorrect S913 If need access to data file, obtain RACF authority. If position 8 of a test DSN = P RACF thinks it is a production dataset S923 DB2 is up but SAS job has something locked up.

Maples ESM Technologies Pvt. Ltd

Page 124 of 246

DB2

S929 U929 9XX-12 S9EC SA78 SB37

DLI - check for missing or misspelled PSB name PSB not found. Check your PSB lib or PSB spelling BLP tapes must have USER=TSPRX7 BLP tapes must have USER=TSPRX7 Cancelled / timed-out in middle of sort. Check other message / dump Not enough space on output file increase SPACE parameter on file named in console messages section of your output

SB78

Accessing the same database another job is currently using. Rerun after the other job completes.

SC03

This is believed to be MIXRES error problem. The executable module needs to have the following modules added to the beginning of its LINKMOD set : - INCLUDE SYSLIB (ICZCPCO) *MODULES TO HELP RESOLVE - INCLUDE SYSLIB(IGZENRI) * mixres error for the 3.0 - INCLUDE SYSLIB(IGZENRT) * rel of VS COBOL II - INCLUDE SYSLIB(ILBOSRV) * these were pulled from LINKMOD GRPL206A Not enough space on output file increase SPACE parameter on file named in console messages section of your output. For file expansions, reduce the size of the parm. Not enough space on output file increase SPACE parameter on file named in console messages section of your output.

SD37

SE37

U0003

Usually a call to a non-existent program TMS volume number does not contain DSN Tried to access data set but missing - check console messages Call to abend check displays on SYSOUT data set

U0016

Usually abend on sort. Check sort message area for reason for bad sort. If insufficient core, increase REGION size, or if executing a SORTD add a DYNALLOC and FILSZ as in this example : //SYSIN DD * SORT FIELDS=(438,12,CH,A), DYNALLOC=(SWORK,6),FILSZ=E10000 If still abend, try deleting the FILSZ=Ennnn part of the above card. Sort cannot handle spanned records on sortout. See JRs memo located in NW20GRPT.EBS.GTOOLKIT.ABEND.CNTL(M901126).

U0020-08

Means that the D????P01 file has zero space available. You need to do an unload reload with more space allocated.

Maples ESM Technologies Pvt. Ltd

Page 125 of 246

DB2

U0039

If this is a batch DLI job with a return code of 20, try changing the job name and resubmitting i.e., change TSxxx80A to TSxxx80. Or run IMS backout step or on rare situation change IRLM.

U0041

If this is a batch DLI job with a return code of 20, try changing the job name and resubmitting- i.e., change TXxxx80A to TSxxx80.

U0047

Try changing from production DLI database to test and/or change to exec DBAU03T. or change IRLM=N Set //STEPLIB DD blanks with the number of lines = the number of steplib DDs in the proc.

U0048 U0403

?? Invalid parm card or pds file being brought into the program If occurs during a DATAVANTAGE load of a database correct by deleting the data portion of the database and reallocating that data portion.

U203 U0259 U295

Same as S0CB IMS compile with DATA(31) Look for unopened file that your program is trying to use or file being opened twice

U0476

Means your PSB does not match your COBOL ENTRY statement. Make sure the databases are in the same sequence in both & recompile. YOU FORGOT TO PUT Y IN THE CBLTDLI PARAMETER ON THE CHGMAN COMPILE OPTIONS FIELD! You may have the wrong linkset for ims program You may need to have procedure division using instead of entry DLITCBL.

U504 U514 U0595 U826

Check for too large of a block size. Check for missing GOBACK, especially within an entry point. IMS get core failure must call DLITCBL before call CBLTDLI Happened when the key length and record length were incorrect in the initialize database index step. Pointer problem reload from backup file. Your DBD stuff is not appropriate for the database !!\ Maybe looking for incorrect segment layouts and like that.

U850 U852

U853 U0868

Happened when the DRATEP01 DSN was different than DRATEX01 DSN. Means something is wrong with your test database. Make a new database and try again. Check for block contain 0 records missing in FD. Record length does not agree with the copy member in the FD. - If are working with a production program and you are dummy-ing out the file

U1002

Maples ESM Technologies Pvt. Ltd

Page 126 of 246

DB2

include the following in your JCL: //* //VSAMFILE DD DUMMY,AMP=AMORG //QSAMFILE DD DUMMY,DCB=BLKSIZE=18 // If are opening a dataset that has a card as output : //cardin dd * - Could possibly indicate syntax error. U1010 New COBOL calling old COBOL with DISPLAYs or READY TRACE. Job will process and put out DISPLAYs; however, upon completion or call to COBOL2 module it will abend with a 1010. U1020 User logic error see console message section for clue Call DLITCBL entry from IMS in middle of perform Check for extraneous generated SYSIN DD statements Read past end of file ? Trying to close a file that is not open The VSAM file is allocated online and must be de-allocated first (Use TZDA or TQDA to de-allocate the file online) U1033 - Look at +IGZ033I error message. Attempt to call an AMODE(24) callpgm passing 16 meg. Recompile program with DATA(24) instead of DATA(31). Rerun job. You may need to set DATA(24) in the link step. U1034 U1044 U1035 Same as SB37 Old cobol calling new cobol VSAM LRECL does not match your COBOL record layout 4 bytes. DD statement missing. Inconsistent between FD, 01, and/or JCL COBOL II treats your recording mode line as comments and sets mode based on the 01s under the FD. U2658 U3003 U3040 Happened when using IDCAMS instead of UTYPAMS DB load. VSAM return code 97 on open. DGS6421 Param exceeds max allowable length IRLM param or one of the other ims parameters may be incorrect. U3057 Check your DB2 stuff that is called from IMS. Make sure you have DDOTV02 DD and MBR=DSNMTV01. Check your DDITV02 data U4092 Build buffer error increase region size

Maples ESM Technologies Pvt. Ltd

Page 127 of 246

DB2

U4094

De-allocate file from online or make sure file is VSAM Empty VSAM file

X900

File used by GLK0G3CM in security checking received a error on read. Check for file(s) closed. VSAM abend when nnn is the feedback code in decimal-SHOWCB VSAM abend when nnn is the feedback code in decimal-MODCB VSAM abend when nnn is the feedback code in decimal-GENCB IMS needs oper VOL-SER-NO reply of input tape specified as BLP that is exactly equal to VOL=SER=. Specified in JCL.

1nnn 2nnn 3nnn IECTMS3

IEC141 013-20

Sequential dataset open. Error is either : 1. BLKSIZE is not a multiple of LRECL 2. LRECL = 0 when RECFM = FB or FBS, 3. BLKSIZE is not 4 bytes greater than LRECL when RECFM = V

IGZnnnI DFSnnnI DFHnnnn DVDnnnn DVRTnnnn ADR**** DSN****

See appl program debugging guide no. SC26-4049 See IMS/VS messages and codes no. SC26-4174. See CICS messages and codes no. SC33-0514. See SDF/CICS messages and codes no. SH19-8107. See DXT messages and codes no. SC26-4091. See --- messages and codes no. SC26-4390. See --- messages and codes no. SC26-4379.

Limits Imposed by DB2


Longest alias, synonym, collection ID, correlation name, statement name, or name of a column, cursor index, table or view Longest authorization name package name, or name of a plan database, tablespace, storage group, or referential constraint Longest host identifier Longest server name or location identifier 64 16 8 18

Maples ESM Technologies Pvt. Ltd

Page 128 of 246

DB2

Numeric Limits
Smallest INTEGER value Largest INTEGER value Smallest SMALLINT value Largest SMALLINT value Largest Decimal Precision Smallest FLOAT value Largest FLOAT value Smallest Positive FLOAT value Largest Negative FLOAT value Smallest DECIMAL value Largest DECIMAL value -2147483648 2147483647 -32768 32767 31 About -7.2 x 10 About 7.2 x 10 About 5.4 x 10 1 10
31 31 75 75 -79 -79

About -5.4 x 10

10 - 1

String Length Limits


Maximum Length of CHAR Maximum Length of GRAPHIC Maximum Length of VARCHAR or VARGRAPHIC Maximum Length of a Character Constant Maximum Length of a String Concatenation 254 127 4046, for 4K Pages 32704, for 32K Pages 254 32754 SBCS Characters 16382 DBCS Characters

Date Time Limits


Smallest DATE value (shown in ISO format) Largest DATE value (shown in ISO format) Smallest TIME value (shown in ISO format) Largest TIME value (shown in ISO format) Smallest TIMESTAMP value Largest TIMESTAMP value 0001-01-01 9999-12-31 00.00.00 24.00.00 0001-01-01-00.00.00.000000 9999-12-31-24.00.00.000000

Maples ESM Technologies Pvt. Ltd

Page 129 of 246

DB2

DB2 Limits
Maximum number of columns in a table or view (the value depends on the complexity of the CREATE VIEW statement Maximum number of base tables in a view Maximum number of volume IDs in a storage group Maximum number of partitions in a partitioned Tablespaces Maximum size of a partition, in gigabytes 4, for 1 to 16 partitions 2, for 17 to 32 partitions 1, for 33 to 64 partitions Maximum size of a DBRM entry Longest index key 65536 254 less than number of key columns that allow nulls Maximum number of bytes used in the partitioning of a partitioned index Maximum number of columns in an index key Maximum number of tables and views that can be identified in a sub select Maximum total length of host and indicator variables pointed to in an SQLDA Longest host variable used for insert or update Longest SQL statement Maximum number of elements in a select list Maximum number of predicates in a WHERE or HAVING clause Maximum number of columns in a GROUP BY Maximum total length of columns in a GROUP BY clause Maximum number of columns in an ORDER BY Maximum total length of columns in an ORDER BY clause 750 4000 750 4000 32704 32765 750 750 64 15 or fewer, depending on the complexity of the sub select 32767 40 15 133 64 750 or fewer, 749 if the table is a dependent

Maples ESM Technologies Pvt. Ltd

Page 130 of 246

DB2

Sample DB2/COBOL Application Program:


Program 1:

****************************************************************** THIS PROGRAM IS FOR DISPLAYING THE RECORDS IN A TABLE ******* * SEQUENTIALY ********************************************** IDENTIFICATION DIVISION. PROGRAM-ID. MTRG081P1. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. ************************************************************ * * * * * DCLGEN TABLE (EMP) LIBRARY (MTRG081.DB2.INPUT(THIRD)) ACTION (REPLACE) LANGUAGE (COBOL) QUOTE * * * * * *

* IS THE DCLGEN COMMAND THAT MADE FOLLOWING STATEMENTS ************************************************************* EXEC SQL DECLARE EMP TABLE (EMPNO ENAME SAL DEPTNO )END-EXEC. ***************************************************************** * COBOL DECLARATION FOR TABLE EMP ***************************************************************** 01 DCLEMP. 10 10 49 49 10 10 EMPNO ENAME ENAME-LEN ENAME-TEXT SAL DEPTNO PIC S9(4) USAGE COMP. PIC X(20). PIC S9(5) V 9(2) USAGE COMP-3. PIC S9(2) V USAGE COMP-3. PIC S9(4) V USAGE COMP-3. DECIMAL(4,0) NOT NULL, VARCHAR(20), DECIMAL(7,2), DECIMAL(2,0)

Maples ESM Technologies Pvt. Ltd

Page 131 of 246

DB2

****************************************************************** THE NUMBER OF COLUMNS DESCRIBED BY THIS DECLARATION IS 4 *

***************************************************************** EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL DECLARE C1 CURSOR FOR SELECT * FROM EMP END-EXEC. 77 EOT PIC S9(9) COMP VALUE +100.

PROCEDURE DIVISION. PARA1. EXEC SQL WHENEVER SQLERROR GOTO DBERROR END-EXEC. EXEC SQL WHENEVER SQLWARNING GOTO DBERROR END-EXEC. EXEC SQL WHENEVER NOT FOUND CONTINUE END-EXEC. PARA2. EXEC SQL OPEN C1 END-EXEC. EXEC SQL FETCH C1 INTO :DCLEMP END-EXEC. IF SQLCODE NOT=EOT PERFORM DISPLAY-PARA UNTIL SQLCODE IS NOT EQUAL TO ZERO. EXEC SQL CLOSE C1 END-EXEC. STOP RUN. DISPLAY-PARA. DISPLAY DEPTNO DISPLAY NAME DISPLAY EMPNO DEPTNO OF DCLEMP. ENAME OF DCLEMP. EMPNO OF DCLEMP.

EXEC SQL FETCH C1 INTO :DCLEMP END-EXEC. DBERROR DISPLAY SQL ERROR. STOP RUN.

Program 2:
* * * THIS PROGRAM IS FOR* 1. INSERT 2. SELECT 3. UPDATE 4. DELETE IN A TABLE THROUGH DB2 ONLY*

***************************************************************** IDENTIFICATION DIVISION. PROGRAM-ID. MTRG081P1.

Maples ESM Technologies Pvt. Ltd

Page 132 of 246

DB2

ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. ***************************************************************** * DCLGEN TABLE (EMP)* * * * LIBRARY (TRG081.DB2.INPUT(THIRD))* LANGUAGE (COBOL)* QUOTE*

* IS THE CLGEN COMMAND THAT MADE THE FOLLOWING STATEMENTS* ***************************************************************** EXEC SQL DECLARE EMP TABLE (EMPNO ENAME SAL DEPTNO )END-EXEC. ***************************************************************** * COBOL DECLARATION FOR TABLE EMP* ***************************************************************** 01 DCLEMP. 10 EMPNO 10 ENAME. 49 ENAME-LEN 49 ENAME-TEXT 10 SAL 10 DEPTNO PIC S9(4) USAGE COMP. PIC X(20). PIC S9(5) V 9(2) USAGE COMP-3. PIC S9(2) V USAGE COMP-3. PIC S9(4) V USAGE COMP-3. DECIMAL(4,0) NOT NULL, VARCHAR(20), DECIMAL(7,2), DECIMAL(2,0)

***************************************************************** 77 TNAME PIC X(15).

PROCEDURE DIVISION PARA1. EXEC SQL OPEN C1 END-EXEC MOVE RAHUL TO TNAME. EXEC SQL UPDATE EMP SET ENAME =:TNAME WHERE EMPNO=1025 END-EXEC. DISPLAY SQLCODE. STOP RUN.

Maples ESM Technologies Pvt. Ltd

Page 133 of 246

DB2

Test Yourself:
1. What is physical storage of Date and Time in DB2? A) 4 & 4 Bytes B) 4 & 3 bytes C) 3&10 bytes D)3 & 3 Bytes

2.

Declare CURSOR is an executable statement A) Yes B) No C) either a or b D) can not define

3.

The Number of bytes occupied by SQLCA is A) 128 bytes B) 136 bytes C) 142 bytes D) 138 bytes

4.

Which one of the following is not a Database services A) Bind B) Data Manager C) Locking Services D) Precompiler

5.

Give the Sql Code for Program name not found in the PLAN_NAME a) -811 b) -817 c) -805 d) -803

6.

Give the Sql Code for No Authorization to perform Operation on Object name A) -551 B) 516 C) -552 D) -556

7.

It scans a table or index space to gather information A) REORG B) RUNSTAT C) LOAD D) CHECK

8.

To refer the object at the sub system which one of the following can be used A) ALIAS B) SYNONYM C) VIEW D) None of the above

9.

Which of the following is not a program preparation step? A. Process SQL Statement B. Bind Application

C. Compile & Link Edit the application D. Table Check Constarint

10. DCLGEN supplied with DB2 produces _______________ and say whether it is must / not required. A. SQLCA in side program and it is must B. Table declaration and it is must C Table declaration and it is not required D. reads the catalog to check for table and must

Maples ESM Technologies Pvt. Ltd

Page 134 of 246

DB2

DB2 LAB EXERCISE


* * * * * * * * * * * * * CREATING A TABLE: PARTS * * * * * * * * * * * * * * * * *

CREATE TABLE PARTS 1 (PARTNO CHAR (4) PRIMARY KEY NOT NULL, DESCRIPTION CHAR (15), QONHAND INTEGER, QONORDER INTEGER) IN STAFFDB1. STAFFTS1;

CREATE UNIQUE INDEX PARTIND ON PARTS1 ( PARTNO);

* * * * * * * * * * * CREATING A TABLE: SUPPLIERS * * * * * * * * * * * * * * * *

CREATE TABLE SUPPLIER1 (SUPPNO CHAR (3) PRIMARY KEY NOT NAME CHAR (20) , ADDRESS VARCHAR (40) ) IN STAFFDB1.STAFFTS1;

CREAT UNIQUE INDEX SSSINDS ON SUPPLIER1 (SUPPNO);

* * * * * * * * * * * CREATING A TABLE: QUOTATIONS * * * * * * * * * * * * * *

CREATE TABLE QUOTATIONS (SUPPNO CHAR(3) NOT NULL, PARTNO CHAR(4) NOT NULL, PRICE INTEGER, RESPTIME SMALLINT, PRIMARY KEY (SUPPNO, PARTNO) , FOREIGN KEY (SUPPNO) REFERENCES SUPPLIER1 (SUPPNO) , FOREGIN KEY (PARTNO) REFERENCES PARTS1 (PARTNO) ) IN STAFFDB1. STAFFS1;

CREATE UNIQUE INDEX INDC ON QUOTATIONS (SUPPNO, PARTNO);

* * * * * * * * * * * CREATING A TABLE: ORDERS * * * * * * * * * * * * * * * * *

CREATE TABLE ORDEERS1 (SUPPNO CHAR(3) NOT NULL, PARTNO CHAR (4) NOT NULL , QUANTITY INTEGER, ODATE DATE, PRIMARY KEY (SUPPNO, PARTNO) , OREIGN KEY (SUPPNO) REFERENCES SUPPLIERS (SUPPNO) , OREIGN KEY (PARTNO) REFERENCES PARTS1 (PARTNO) ) IN STAFFDB1. STAFFTS1 ;

CREATE UNIQUE INDEX ORSERIND ON ORDERS (SUPPNO, PARTNO) ;

Maples ESM Technologies Pvt. Ltd

Page 135 of 246

DB2

* * * * * * * * * * *INSERTING VALUIES IN ALL TABLES * * * * * * * * * * * * * * * * INSERT INTO PARTS1 VALUES (P209, CAM DRIVE MODESTO CA. ) ; , 00 , 10) ; , 500 SCENIC

INSERT INTO SUPPLIERS VALUES (S99, PARTS IS PARTS INSERT INTO QUOTATIONS VALUES ( S61, P232, 5, 15 ) ; INSERT INTO ORDERS VALUES (S53, P207,20 , 06/15/1997) ;

SELECT * FROM PARTS1; SELECT * FROM SUPPLIERS; SELECT * FROM QUOTATIONS; SELECT * FROM ORDERS;

* * * * * * * * * * * * * * * * * * * SIMPLE QUERIES * * * * * * * * * * * * * * * * * * * *

1.1 SELECT * FROM QUOTATIONS WHERE SUPPNO= S54 AND PARTNO= P209 ; 1.2 SELECT PARTNO, DESCRIPTION FROM PARTS WHERE DESCRIPTION LIKE B%T% ; 1.3 SELECT PARTNO , DESCRIPTION FROM PARTS WHERE DESCRIPTION LIKE B__T% ; 1.4 SELECT * FROM PARTS WHERE QONORDER+QONHAND <= 10 AND (PARTNO IN (P205 , P207 , P209) OR DESCRIPTION LIKE %GEAR%) ; 1.5 SELECT A.PARTNO, B.DESCRIPTION, C.PRICE FROM ORDERS A JOIN PARTS B ON A.PARTNO=B. PARTNO JOIN QUOTATIONS B.PARTNO=C.PARTNO WHERE A.SUPPNO=C.SUPPNO; 1.7 SELECT PRICE AS PRICE_P207 FROM QUOTATIONS WHERE PARTNO=P207 C ON

AND PRICE IS NOT NULL;

Maples ESM Technologies Pvt. Ltd

Page 136 of 246

DB2

1.8 SELECT * FROM QUOTATIONS WHERE PARTNO = P231 AND RESPTIME < 30 ORDER BY PRICE; 1.9 SELECT A. * , B. SUPPNO, B.PRICE, C.NAME AS SUPPNAME, C.ADDRESS FROM PARTS A JOIN QUOTATIONS B ON A.PARTNO=B. PARTNO JOIN SUPPLIERS C ON B.SUPPNO=C.SUPPNO; 1.10 SELECT * FROM PARTS ORDER BY QONHAND DESC , QONORDER DESC; 1.11 SELECT A. * , A.QONORDER+QONHAND AS TOTALQ FROM PARTS A ORDER BY A.QONORDER+QONHAND DESC;

* * * * * * * * * * * * * * * * * * * NESTED QUERIES * * * * * * * * * * * * * * * * * * * * 2.1 SELECT A.PARTNO, A.SUPPNO, B.NAME FROM QUOTATIONS A JOIN SUPPLIERS B ON A.PARTNO = P221 WHERE A.SUPPNO = B.SUPPNO; SELECT A.PARTNO, A.SUPPNO, B.NAME FROM QUOTATIONS A JOIN SUPPLIERS B ON A.PARTNO = P221 AND A.SUPPNO = B.SUPPNO;

2.2 SELECT A.*, B.SUPPNO, B.PRICE, B.RESPTIME, C.NAME AS SUPNAME, C.ADDRESS, D.QUANTITY AS QTYORDERED, D.ODATE AS ORDERDATE FROM PARTS A JOIN QUOTATIONS B ON B.PARTNO=P221 AND A.PARTNO=B.PARTNO JOIN SUPPLIERS C ON B.SUPPNO=C. SUPPNO JOIN ORDERS D ON D. PARTNO=B.PARTNO AND SUPPNO=B.SUPPNO; SELECT A.*, B.SUPPNO, B.PRICE, B.RESPTIME, C.NAME AS SUPNAME, C.ADDRESS, D.QUANTITY AS QTYORDERED , O.ODATE AS ORDERDATE FROM PARTS A JOIN QUOTATIONS B ON B.PARTNO=P221 AND A.PARTNO=B. PARTNO JOIN SUPPLIERS C ON B.SUPPNO=C.SUPPNO JOIN ORDERS D ON D.PARTONO=B.PARTNO;

Maples ESM Technologies Pvt. Ltd

Page 137 of 246

DB2

2.3 SELECT * FROM QUOTATIONS WHERE PRICE < (SELECT MIN (PRICE) FROM QUOTATIONS WHERE PARTNO = 207 )

2.4 SELECT A. * , B.RESPTIME FROM ORDERS A JOIN QUOTATIONS B ON A.PARTNO=B.PARTNO.PARTNO AND A.SUPPNO=B.SUPPNO WHERE B.RESPTIME > 20 ; 2.5 SELECT A.NAME, A.ADDRESS FROM SUPPLIERS A, QUOTATIONS WHERE QUOTATIONS.PARTNO= P207 AND QUOTATIONS. PRICE < 1000;

SELECT A.* FROM SUPPLIETS A, QUOTATIONS B WHERE B.PARTNO= P207 AND B.PRICE < 1000;

* * * * * * * * * * * * * * * QUERIES WITH BUILT-IN-FUNCTIONS * * * * * * * * * * * * * * * * * * * *

3.1 SELECT DESCRIPTION, QONHAND, QONORDER FROM PARTS WHERE DESCRIPTION LIKE %BOLT% ;

3.2 SELECT PARTNO, MAX(PRICE) AS MAXPRICE, MIN (PRICE) AS MINPRICE FROM QUOTATIONS WHERE PARTNO= P207 AND PARTNO IS NOT NULL GROUP BY PARTNO ; 3.3 SELECT COUNT (*) AS TOTAL_NOS FROM QUOTATIONS WHERE PARTNO=P207 ; 3.4 SELECT COUNT (*) AS TOTAL_NOS FROM QUOTATIONS WHERE PARTNO= P207 AND PRICE IS NOT NULL;

3.5 INCOMPLETE SELECT COUNT (DISTINCT (PRICE) ) AS TOTAL_NOS FROM WHERE PARTNO=P207 AND PRICE IS NOT NULL; QUOTATIONS

* * * * * * * * * * * * * * * QUERIES WITH

GROUPING * * * * * * * * * * * * * * * * * * * *

Maples ESM Technologies Pvt. Ltd

Page 138 of 246

DB2

4.1 SELECT PARTNO , MAX (PRICE) AS MAX_PRICE, MIN(PRICE) AS MIN_PRICE , AVG (PRICE ) AS AVG_PRICE FROM QUOTATIONS GROUPS BY PARTNO; 4.2 INCOMPLETE SELECT COUNT (*) FROM ORDERS WHERE DISTINCT (MONTH (DATE) ) IS NOT NULL;

SELECT CURRENT _TIMESTAMP FROM SYSIBM.SYSDUMMY1; SELECT CURRENT _TIME FROM SYSIBM.SYSDUMMY1; SELECT CURRENT _DATE FROM SYSIBM.SYSDUMMY1; SELECT * FROM SYSIBM.SYSCOLUMNS WHERE TBCREATOR MAPLE05 ,

EMBEDDED SQL PROGRAMS:

1.

Wite DB2 program to retrieve one row from parts table with Parts number in where clause and display in spool area?

2. 3.

Write a program to insert a row in Quotation table with price field as Null? Write a program for selecting all the rows in the supplier table and display them in application program with the help curser

4.

Write a program to retrieve the rows from quotation table and check whether the price field contains value are not if it contains null update with suitable price

5.

Write a Dynamic SQL program to insert value into parts table

Maples ESM Technologies Pvt. Ltd

Page 139 of 246

CICS

CICS
(CUSTOMER INFORMATION CONTROL SYSTEM)

Maples ESM Technologies Pvt. Ltd

Page 140 of 246

CICS

Objective
Before learning the details of coding CICS programs , you need to know some basic CICS concepts and terms. In this chapter you will learn about CICS and the services it provides for application programs After you are introduced to CICS and its environment, you will learn how CICS can handle hundreds of users at the same time . Then you will learn about the CICS services that you use as you develop COBOL program using CICS commands.

Introduction to CICS
Customer Information Control System -CICS developed in late 1960s as a DB/DC control system. CICS was developed by IBM to create an environment for developing and operating on-line systems. It has created an enormous impact for the ease with which on-line programs can be developed under it. The MVS operating system was basically designed to handle batch jobs. The starting point for an understanding of how CICS operates under MVS is a clear understanding of the differences between on-line and batch jobs. CICS provides an interface between the Operating System and application programs. It provides the functions required by application programs for communication with remote and local terminals and subsystems. Provides control for concurrently running programs serving many online users. It provides concurrent access to same Datasets and Databases. It has the ability to communicate with other CICS systems and data base systems both in the same computer and in connected computer systems. A complete CICS system is known as a Database / Data communication system. Macro Level CICS - initial version Assembler macro to request CICS services Command Level CICS - high level language version - commands to request CICS services Single command can replace series of macros -

Batch & Online: Differences Batch System


Input data is prepared and given in sequence (file) Processes accumulated data. No user interaction

Maples ESM Technologies Pvt. Ltd

Page 141 of 246

CICS

Processing sequence is predictable & hence restarting the process in case of failure is easy Programs and files cant be shared Only single user at a given point of time Programs are scheduled through jobs Same program handles different types of transactions Program calls for data to be read. Typically used for long running jobs. Examples: Payroll System, Monthly Sales Report.

Online System
Data is entered as needed not in sequence (terminal) Multiple users can access simultaneously, processing is done real time. Transactions are entered one at a time. Since processing sequence is unpredictable, special recovery/restart procedure is required in case of failure Typically each type of transaction is handled by a different program Data item call for program to be executed. Programs and files can be shared Transaction can be run at any time Data collection is on-line using terminals. Job schedule is instantaneous. Processing priority can be changed. File updating should be instant. CICS transactions-id triggers the start of on-line application and generally it is multitasking multithreaded. Outputs are sent as a message to terminals. Example: Airline / Railway Reservation System, Hotel Booking.

Maples ESM Technologies Pvt. Ltd

Page 142 of 246

CICS

Online Vs Batch Application


In a batch program all input/output and work areas have to be defined within the program while in CICS these are outside the program and allocated by CICS as and when needed from the dynamic storage area. A batch program reads its own input data whereas CICS reads the data using CICS application program. A batch program issues its I-O instructions directly to the operating system while CICS application programs issue such instructions to CICS and CICS handles the interface to the operating system. Recovery on error conditions is the major strength of CICS.

Features of CICS For System Programmers


Pre-generated systems to speed up and simplify the generation of the CICS system Pre-complied sample programs to help verify that the system has been correctly installed. Control tables to make the system flexible. Helps in defining the terminals, files and applications running under CICS system Security facilities to help prevent unauthorised access to information Recovery functions to assist recovery from a variety of error conditions.

System Concept
The primary objective of CICS is to provide the control and service functions of the DB/DC system as a package. CICS is not a DB/DC system unless the applications accompany it , because CICS only provides the control environment for the DB/DC system . CICS forms a layer between the application programs and the operating system and acts as an interface between the two. To achieve this CICS has five major system components each of which performs specialized services.

Maples ESM Technologies Pvt. Ltd

Page 143 of 246

CICS

CICS System Services


Data-Communication Functions Data communication functions, provides an interface between CICS terminals or other systems. The following services are offered. To interface with telecommunication access methods like VTAM To make the application programs independent of terminal hardware through Basic Mapping Support (BMS) which provides device and format independence.

Maples ESM Technologies Pvt. Ltd

Page 144 of 246

CICS

To provide Multi Region Operation (MRO) through which more than one CICS region in a system can communicate. To provide Inter System Communication (ISC) through which a CICS region in a system can communicate with CICS regions in other systems.

How an application program communicates with terminal services

Maples ESM Technologies Pvt. Ltd

Page 145 of 246

CICS

Data-Handling Functions The component of Data Handling functions provides an interface between CICS and data. The following CICS services are offered. To interface with Data Access Method such as VSAM and BDAM To interface with database access methods such as DB2, SQL/DS and DL/I To maintain data integrity by control of simultaneous record updates protection of data at abnormal termination of tasks protection of data at system (CICS or OS) failures

Application Program Services The component of application program services provides an interface between CICS and application programs. The following services are offered. To Interface with COBOL , PL/I , Assembler programs Command Level Translator Execution Diagnostic Facility (EDF) Command Interpreter (CECI) Screen Definition Facility (SDF)

Maples ESM Technologies Pvt. Ltd

Page 146 of 246

CICS

How an application program accesses CICS services

System Services The component of system services provides an interface between CICS and the Operating System. The following services are offered. Program control such as load and release of application programs Storage control such as acquiring and freeing of storage Task control such as task scheduling based on the task priority Monitoring Functions The component of monitoring functions monitors various events within CICS and provides statistics for system tuning.

Maples ESM Technologies Pvt. Ltd

Page 147 of 246

CICS

Task & Transaction


Task: A basic unit of work which is scheduled by the operating system. CICS is one of many tasks under OS like TSO, Batch Jobs, IMS etc. A unit of work scheduled within CICS region is called a CICS task. A CICS task may be accomplished by executing one or many CICS programs

Example: Read from and write to the terminal

Transaction: A transaction is a processing request initiated by a user terminal. An entity which initiates execution of a task. In CICS, transaction is identified by the transaction identifier (Trans-id ) of four characters. The transaction identifier must be registered in the Program Control Table (PCT). A transaction may consist of one or more tasks (programs). Under CICS , a CICS

application program must be registered in the Processing Program Table (PPT). CICS Components

Control Programs (or Management Modules)


Programs that interface between OS and application program Handle the general functions that are crucial to operation of CICS

Control Tables
Define the CICS environment Functionally associated with the management module

Control Blocks (or Areas)


Contain system type information. Example: Task Control Area contains information about the task

CICS Control Programs and Tables


CICS System Programs, each of which performs its specialized function is called the CICS NUCLEUS. It consists of IBM supplied CICS control programs and corresponding user defined CICS control tables.

Maples ESM Technologies Pvt. Ltd

Page 148 of 246

CICS

CICS environment consists of five management service modules. They are: a. Terminal Management Comprises of Terminal Control Program (TCP) - Polls Terminals, Handles different communication protocols. Terminal Control Table (TCT) - Describes each terminal in the network by type, priority and address. Terminal I/O Area (TIOA) - The initial 12 bytes filler in the symbolic map. Holds messages from the terminal until working storage for the application program is defined. Holds messages being sent to a terminal, until the line is free for transmission. b. Program management Program management comprises the following Program Control Program (PCP) - Keeps track of which programs are in storage and where they are located Processing Program Table (PPT) - Defines system elements such as program name, language, primary storage address and disk address c. Storage Management Storage management has only the Storage Control Program (SCP) which acquires and releases storage as necessary d. Task Management

Task management comprises the following Task Control Program (KCP) Tracks which terminal is using which program Controls Task priority Program control Table (PCT) contains information related to associated program Task Control Area (TCA) contains pointers to storage areas and control areas for programs and terminals The EXEC Interface Block (EIB) is used in CICS command level environment. It comprises the following: Each Task has an EIB associated with it EIB contains system related information such as transaction ID, Date, Time, Cursor position etc., which can be accessed by application program. the Transaction ID and its

Maples ESM Technologies Pvt. Ltd

Page 149 of 246

CICS

Given Below is a list of some commonly used EIB information EIBAID EIBCALEN EIBCPOSN EIBDATE EIBTIME EIBDS EIBFN EIBRCODE EIBRESP EIBRESP2 EIBRSRCE X(1) Attention Identifier S9(4) COMP S9(4) COMP Length of DFHCOMMAREA Most recent cursor address, given as displacement value

S9(7) COMP-3 Date when the task started S9(7) COMP-3 Time when this task started X(8) Most recent data set name X(2) Function code of the last command X(6) Response code of the last command S9(8) COMP Exceptional condition code S9(8) COMP Exceptional condition extended code X(8) Last resource ( map name for SEND MAP or RECEIVE MAP Command, program name for LINK or XCTL , file name for File control command etc. )

EIBTASKN EIBTRMID EIBTRNID e. File Management

S9(7) COMP-3 X(4) X(4) Terminal Id

Task number of this task

Transaction Id

File management comprises the following File Control Program (FCP) Interacts with system access methods to perform file I/O requests File Control Table (FCT) contains information on files related to the following: File name, buffer requirements, allowable services such as read, write, update etc. File characteristics. File I/O Area (FIOA) holds the Control Interval that contains the requested logical record.

CICS Unique Features Multi Tasking


One of the basic features of CICS is multitasking. Multitasking simply means that CICS allows more than one task to be executing at the same time. All of the operating systems that support CICS provide multitasking on their own. But CICS provides for multitasking within the single address space or partition provided by the operating system .So it ignores the multitasking capabilities of the operating system and provides its own multitasking capabilities .CICS manages multitasking of CICS tasks within its own region.

Maples ESM Technologies Pvt. Ltd

Page 150 of 246

CICS

The operating system allows more than one task to be executed concurrently. CICS controls many tasks running concurrently in a single partition using task switching mechanism. In this a task is suspended on a command that causes a wait and the next highest priority task that is waiting takes control.

Multi threading
Multi threading is a system environment where the tasks are sharing the same program under the multi tasking environment. Several terminals requiring the same program will use only one copy of the program thus saving main storage. Multithreading is a subset of multitasking since it concerns tasks which use the same program. This feature is possible because multi tasking allows each task requiring the same program to use part of the same copy of the program when the task is active.

Under the multithreading environment, a program is shared by several tasks concurrently. For each task, the program must work as if it were executing instructions exclusively for each task. As against this, under a single threading environment a program is used by a single step of a job at a time as in case of a Batch job.

Maples ESM Technologies Pvt. Ltd

Page 151 of 246

CICS

Reentrant
A reentrant program does not modify itself while executing a task. It can reenter itself and continue processing after an interruption by the operating system which during interruption executes other tasks including OS tasks of the same program. A non reentrant program cannot be used in a multithreading environment. Batch programs are typical examples of non- reentrant program. Reentrant programs are used in online system and is a term for the OS/multithreading environment.

Between two consecutive supervisor calls (SVC) an OS task1 which uses a program has exclusive use of the CPU resource at an interruption time in the program task1 is suspended and OS saves the status and executes task2, task3 etc . At the next SVC when the wait status of task1 is complete, OS restores the status of task1 (reenter to the program) and continues to execute task1 until the next SVC.

This process makes it possible for task1, task2, task3 to run concurrently. If task1 task2 and task3 use the same program, the data area has to be kept unique to each task. The reentrant program ensures uniqueness of data area and also the program logic which should not get altered.

Quasi Reentrant
A quasi-reentrant program is a reentrant program under the CICS environment. A quasi-reentrant program is a CICS program which does not modify itself. In order to make multithreading possible an application program must be REENTRANT (under OS) or QUASI - REENTRANT (under CICS) i.e. the programs should be serially reusable. Therefore a task must restore any data or instruction it altered before it is suspended so that the next task that uses the same program does not use a revised or modified version.

Under CICS a program interruption and reentry occur not at an SVC time but at the time of a CICS command which may or may not contain any SVC. The term quasi is used in order to distinguish this from the reentrant program under OS/multithreading environment.

CICS Control program and tables


The Core portion of CICS called the CICS nucleus consists of IBM supplied CICS control programs and corresponding user specified CICS control tables

Maples ESM Technologies Pvt. Ltd

Page 152 of 246

CICS

CICS Control Programs IBM Supplied Programs Terminal Control Program Storage Control Program Task Control Program Program Control Program File Control Program Temporary Storage Program Transient Data Program Journal Control Program TCP SCP KCP PCP FCP TSP TDP JCP

CICS Control Tables Associated User Specified Tables Terminal Control Table TCT

Program Control Table Processing Program Table File Control Table Temporary Storage Table Destination Control Table Journal Control Table

PCT PPT FCT TST DCT JCT

Transaction Initiation Process


By a transaction identifier entered in a terminal with Enter Key. This is the most common way of initiating a CICS transaction By a transaction identifier associated with a terminal for pseudo conversation By the start command which initiates a transaction specified in the parameter By the Automatic Task Initiation (ATI) which initiates a CICS transaction if the trigger level is reached in the TDQ By a 3270 attention identifier For the IBM 3270 type terminals any of PF keys and PA keys could be defined in PCT to initiate a CICS transaction

Transaction Initiation Process in CICS:


A transaction initiation process in a CICS region involves CICS control programs and control tables as given below.

1. Terminal Control:

A transaction identifier is entered in a terminal attached to CICS. The Terminal Control Program (TCP) monitors terminal operations with associated Terminal Control Table (TCT).

The Storage Control Program (SCP) acquires storage for the Terminal Input Output Area (TIOA). TCP places the data from the terminal into TIOA and sets the pointer into the TCT entry of the terminal. If there is no task associated with the terminal, TCP passes control to the Task Control Program (KCP) which senses the transaction identifier in the TIOA.

Maples ESM Technologies Pvt. Ltd

Page 153 of 246

CICS

2. Task Control:

KCP creates a task for the transaction and checks whether the transaction identifier is a valid entry in the PCT. If the trans-id is valid it requests the SCP to acquire storage for the Task Control Area (TCA) and a Transaction Work Area (TWA) in which KCP prepares control data for the task.

KCP assigns a priority to the task then places it in the queue of waiting tasks. KCP through PCT tries to locate the application program associated with the Trans-id. 3. Program Control If the Processing Program Table (PPT) entry of the application program does not show the resident address of the program ie when a program is to execute for the first time in a task, KCP passes control to the PCP which fetches the application program from the load library in virtual storage and places it in the main storage. KCP passes control to the application program. The application program starts its processing and the transaction has been initiated.

CICS Command Format


CICS runs under MVS / ESA operating system. This makes use of enterprise architecture of MVS which can efficiently manipulate address space. CICS / ESA programs do not use COBOL language statements like READ, WRITE, OPEN, CLOSE etc.

The general format is given below EXEC CICS command function option (argument ) option (argument) END-EXEC.

Command Option

describes the service requested READ, WRITE, RECEIVE, SEND etc. specifies many optional functions. Some options are keywords only or followed by arguments in parentheses; Eg. FROM, INTO LENGTH etc.

Argument

specifies the characteristics of the value associated. It could be a work area, a length value, a file name or a paragraph name.

Maples ESM Technologies Pvt. Ltd

Page 154 of 246

CICS

Execution of a CICS Application Program Basic procedures


In order to execute an application program under CICS, the following procedure should be followed. Translate, compile and link edit the CICS application program (command level) into the CICS application program library (Loadlib) Define the transaction identifier into PCT with the associated program name Define the program into PPT Sign on to CICS Enter the transaction identifier

CICS Program Considerations


Considerations Must eventually return control to CICS Cant modify procedure division instructions because CICS programs may be shared by many tasks Can modify working storage since a unique copy of working storage is created for each task

CICS Program Restrictions


No CONFIGURATION SECTION, I/O SECTION to be specified in the ENVIRONMENT DIVISION. FILE SECTION, OPEN, CLOSE, and non-CICS READ & WRITE statements are not permitted because file management is handled by CICS. COBOL commands such as ACCEPT, DISPLAY, EXHIBIT, TRACE, STOP RUN, GOBACK, are avoided. (STOP RUN & GOBACK are sometimes included in order to eliminate compiler diagnostic but never executed)

Maples ESM Technologies Pvt. Ltd

Page 155 of 246

CICS

Sample CICS Program


IDENTIFICATION DIVISION. PROGRAM-ID. SAMPLE. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-INPUT. 05 WS-TRANSID P IC X(4). 05 FILLER PIC X(1). 05 WS-IN-EMP-CD PIC X(4) VALUE ALL X. 01 WS-OUTPUT. 05 FILLER PIC X(16) VALUE EMP CODE : . 05 WS-OUT-EMP-CD PIC X(4). 01 WS-LENGTH PIC S9(4) COMP. LINKAGE SECTION. PROCEDURE DIVISION. 000-MAINLINE. PERFORM 100-RECV-INPUT. PERFORM 200-SEND-OUTPUT. EXEC CICS RETURN END-EXEC. STOP RUN. 100-RECV-INPUT. MOVE 9 TO WS-LENGTH. EXEC CICS RECEIVE INTO (WS-INPUT) LENGTH (WS-LENGTH) END-EXEC. MOVE WS-IN-EMP-CODE TO WS-OUT-EMP-CODE 200-SEND-OUTPUT. EXEC CICS SEND FROM (WS-OUTPUT) LENGTH (20) ERASE END-EXEC. The procedure used to execute CICS COBOL program is DFHVITVL and the corresponding JCL is as follows: Sample Program to display message in the CICS region.

//MAPLE24B JOB ,,CLASS=M, // MSGLEVEL=(1,1),NOTIFY=MAPLE24,TIME=(1) // JCLLIB ORDER=MAPLE24.CICS.PDS //STEP1 EXEC PROC=DFHEITVL,MEM=EX01 //TRN.SYSIN DD * * FIRST PROGRAM SEND MAP ************************ IDENTIFICATION DIVISION. PROGRAM-ID. EX1. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION.

Maples ESM Technologies Pvt. Ltd

Page 156 of 246

CICS

01 WS-OUTPUT. 02 FILLER PIC X(30) VALUE 'WELCOME TO CICS PROGRAM'. 77 WS-LENGTH PIC S9(4) COMP. PROCEDURE DIVISION. PERFORM PARA. EXEC CICS RETURN END-EXEC. PARA. MOVE 30 TO WS-LENGTH. EXEC CICS SEND FROM (WS-OUTPUT) LENGTH(WS-LENGTH) ERASE END-EXEC. //LKED.SYSLMOD DD DISP=SHR,DSN=CICSTS22.MAPLE.PRGLOAD(&MEM) //LKED.SYSIN DD * NAME MAPLE24P(R) /* //

JCL for Running CICS Program


//MTRG005P JOB ,,NOTIFY=&SYSUID // JCLLIB ORDER=(MTRG005.CICS.PROG) //STEP1 EXEC PROC=DFHEITVL,MEM=EXP4 //TRN.SYSIN DD DISP=SHR,DSN=MTRG005.CICS.PROG1(&MEM)

//LKED.SYSLMOD DD DISP=SHR,DSN=CICSTS13.MTRG.PRGLOAD(&MEM) //LKED.SYSIN DD * NAME MTRGP005(R) /* //

Maples ESM Technologies Pvt. Ltd

Page 157 of 246

CICS

Application Programming Concepts


In this chapter you will be introduced to programming concepts like how to have a conversation with the system using the terminal and also how to handle the exceptional conditions that might abend the task. Also covered in this chapter is the method use to call a sub program and how to pass variables to it from the main program .

Terminal Conversation
1. Conversational:

A mode of dialogue between program and terminal based on a combination of sending message and receiving message within the same task In the Conversational mode the programs being executed enter into a conversation with the user by sending a message to the terminal and waiting for the user to respond and receiving the response from the terminal The program waits until the user responds by pressing the Enter Key and then proceeds with the next executable instruction. The elapsed time is dependent upon how long it takes for the user to fill in the screen and press the ENTER key. The task is active and holding the system resources during the entire conversation and critical resources will be wasted on waiting time.

Maples ESM Technologies Pvt. Ltd

Page 158 of 246

CICS

Conversational Processing

Start

Send first map

Wait for input

End?

End

Receive map

Process data

Send map 2. Non-Conversational: The non-conversational mode does not involve any conversation with the terminal user . Usually the transaction in this mode is a one-way transaction for output only. Programs are faster and efficient Mainly used for Report printing and Message switching Initiated by Automatic Task Initiation (ATI) or the START command in another transaction 3. Pseudo-Conversational: A mode of dialogue between program and terminal which appears to the operator as a continuous conversation but which is actually carried by a series of tasks Avoids unnecessary use of CICS resources while waiting for the users response by coding programs efficiently

Maples ESM Technologies Pvt. Ltd

Page 159 of 246

CICS

From the systems point of view it is a multitasking operation but from users point of view it looks like a normal conversation In a pseudo conversational transaction when a transaction attempts a conversation by sending a message and expecting a response from the user CICS terminates the task after sending the message with a linkage for the next task. When the user completes the response and presses the Enter Key the next task is automatically initiated by CICS. This task receives the message from the terminal and processes it. Since the task is terminated and resources are freed while waiting for the users response, this approach is much more efficient than the conversational mode. Although the task ended the transaction is not complete. Before the first ends it must save necessary information for the second task A task normally ends when the first program issues a RETURN command Pseudo conversational processing

Maples ESM Technologies Pvt. Ltd

Page 160 of 246

CICS

EXEC CICS RETURN TRANSID(data-area) COMMAREA(data-area) LENGTH(data-value) END-EXEC.

TRANSID COMMAREA LENGTH

specifies the four character transid contains the data to be passed to the next task specifies length of data passed

Conversational Transaction Example PROCEDURE DIVISION. : FIRST-PROCESS. EXEC CICS RECEIVE ---- <= TSK1,12345 INTO(WS-AREA) LENGTH(MSG-LEN) END-EXEC. : process ----- <= EMP(12345) Details

EXEC CICS SEND

FROM(WS-AREA) ERASE END-EXEC. * - - - - - - Program Waits For Response - - - - SECOND PROCESS. EXEC CICS RECEIVE ----- <= INTO(WS-AREA) LENGTH(MSG-LEN) END-EXEC. : process User Enters Data

Sample program to accept message from CICS region and display the same IDENTIFICATION DIVISION. PROGRAM-ID. DEMO1. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION.

Maples ESM Technologies Pvt. Ltd

Page 161 of 246

CICS

01 WS-INPUT. 05 WS-TRANSID PIC X(4). 05 FILLER PIC X(1). 05 WS-IN-EMP PIC X(10) VALUE ALL 'X'. 01 WS-OUTPUT. 05 FILLER PIC X(16) VALUE 'RESPONSE:'. 05 WS-OUT-EMP PIC X(10). 01 WS-LENGTH PIC S9(4) COMP. LINKAGE SECTION. PROCEDURE DIVISION. MAIN. PERFORM 100-RECV-INPUT. PERFORM 200-SEND-PARA. EXEC CICS RETURN END-EXEC. STOP RUN. 100-RECV-INPUT. MOVE 15 TO WS-LENGTH. EXEC CICS RECEIVE INTO (WS-INPUT) LENGTH (WS-LENGTH) END-EXEC. MOVE WS-IN-EMP TO WS-OUT-EMP. 200-SEND-PARA. EXEC CICS SEND FROM (WS-OUTPUT) LENGTH(26) ERASE END-EXEC.

Pseudo-Conversational Example
Technique 1 Transaction TSK1 Program PROG1 PROCEDURE DIVISION. : EXEC CICS RECEIVE INTO(WS-AREA) LENGTH(MSG-LEN) END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 162 of 246

CICS

process EXEC CICS SEND FROM(WS-AREA) ERASE END-EXEC. EXEC CICS RETURN TRANSID (TSK2) END-EXEC. Transaction TSK2 Program PROG2 PROCEDURE DIVISION. : EXEC CICS RECEIVE INTO(WS-AREA) LENGTH(MSG-LEN) END-EXEC. Process : EXEC CICS SEND FROM(WS-AREA) ERASE END-EXEC. EXEC CICS RETURN END-EXEC. After the terminal user enters trans-id TSK1 the associated program PROG1 will be initiated as PCT entry will be having TSK1 = PROG1

Program PROG1 after receiving and processing the data will send some data to the terminal and the RETURN command will terminate with Trans-id TSK2 which will be moved into EIBTRNID.

As soon as user enters data and presses the ENTER key, transaction TSK2 will be initiated which in turn will activate PROG2 as PCT entry for TSK2 will be associated with PROG2. Program PROG2 will receive the data from the terminal, process it and send the message to the terminal and terminate itself by the RETURN command.

In this technique we have two PCT entries and two PPT entries. Technique 2 This technique uses multiple transaction entries (PCT) but a single program to execute these transactions (PPT). The conversation is performed as follows.

Maples ESM Technologies Pvt. Ltd

Page 163 of 246

CICS

As against two different programs having two functions, here both functions are logically divided into two functional routines. In this by capturing the trans-id which is readily available in EIBTRNID one can divert the path of the program to different routines. The same program may look like this. Transaction TSK! = Program PROG1 Transaction TSK2 = Program PROG1 Prog1. PROCEDURE DIVISION. MAIN-PARA. IF EIBTRNID = TSK1 GO TO TSK1-RTN. IF EIBTRNID = TSK2 GO TO TSK2-RTN. TSK1-RTN. EXEC CICS RECEIVE INTO(WS-AREA) LENGTH(MSG-LEN) END-EXEC. process EXEC CICS SEND FROM(WS-AREA) ERASE END-EXEC. EXEC CICS RETURN TRANSID (TSK2) END-EXEC. TSK2-RTN. EXEC CICS RECEIVE INTO(WS-AREA) LENGTH(MSG-LEN) END-EXEC. Process : EXEC CICS SEND FROM(WS-AREA) ERASE END-EXEC. EXEC CICS RETURN END-EXEC. In this case instead of activating different programs, since PCT points to the same program

PROG1, CICS activates the same program PROG1 at the first transaction initiation TSK1 as also at initiation of TSK2. To divert the path of the program to either TSK1-RTN or TSK2-RTN , the value of EIBTRNID is used which will contain TSK1 as the transaction is initiated in the beginning or TSK2 when the first iteration is over before the return command is executed.

Maples ESM Technologies Pvt. Ltd

Page 164 of 246

CICS

Here even though one PPT entry is reduced, the number of PCT entries remains the same as the number of transactions to be executed.

A better technique will be the one where only one PCT entry is provided which will have a corresponding PPT entry. In this technique with this limited facility the same terminal conversation has to be achieved which is explained below. Technique 3 One physical program consists of multiple logical programs, each of which takes care of one conversation. At every logical termination of a task, it issues the RETURN command with the TRANSID option for the transaction identifier defined in PCT and also passes data thru COMMAREA indicating which conversation it is expecting the next time control is returned. The following example will illustrate the conversation using this technique. TSK1 (Trans-d PCT ) = PROG1 ( Defined in PPT) IDENTIFICATION DIVISION. PROGRAM-ID. PROG1. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WK-AREA. 02 WK-TRANS LINKAGE SECTION. 01 DFHCOMMAREA. 02 LK-TRANS PIC X(4). PROCEDURE DIVISION. IF EIBCALEN = 0 GO TO TSK1-RT N. IF LK-TRANS = TSK2 GO TO TSK2-RTN. GO TO EXIT-PARA. TSK1-RTN. EXEC CICS RECEIVE INTO(WS-AREA) LENGTH(MSG-LEN) END-EXEC. process PIC X(4).

Maples ESM Technologies Pvt. Ltd

Page 165 of 246

CICS

EXEC CICS SEND FROM(WS-AREA) ERASE END-EXEC. MOVE TSK2 TO WK-TRANS. EXEC CICS RETURN TRANSID (TSK1) COMMAREA(WK-AREA) LENGTH(4) END-EXEC. TSK2-RTN. EXEC CICS RECEIVE INTO(WS-AREA) LENGTH(MSG-LEN) END-EXEC. Process :

EXEC CICS SEND FROM(WS-AREA) ERASE END-EXEC.

EXEC CICS RETURN END-EXEC. As the program starts executing the first statement EIBCALEN is checked. Since no data has been passed, the length of communication area COMMAREA will be 0 so the program goes to TSK1RTN which is the first iteration. At the logical break, along with the return command, the COMMAREA is filled with TSK2 so that whenever the transaction is invoked again by the receive command, the DFHCOMMAREA contains TSK2 so that the control is transferred to TSK2-RTN . The internal transaction identifier could be any piece of information only to make EIBCALEN non zero. It is mainly to distinguish between the first iteration of the program and the subsequent iterations.

Maples ESM Technologies Pvt. Ltd

Page 166 of 246

CICS

Exceptional Conditions
An abnormal situation during execution of a CICS command is called Exceptional condition. Checking exceptional conditions is similar to checking return codes after executing COBOL I/O statements. In order to check the exceptional condition and transfer the control to another path CICS provides alternative in the form of Handle Condition. Handle Condition The CICS HANDLE CONDITION command allows an application program to check for exceptions that may occur when CICS commands are executed. The HANDLE CONDITION command specifies which conditions are to be checked as well as the names of the exception routines to be executed while encountering the condition.

The Handle condition command controls program execution sequence when an exceptional error occurs in a CICS statement. The general format is EXEC CICS HANDLE CONDITION Lengerr (leng-err) Condition (label) Error ( label) END-EXEC. The condition name represents an exceptional condition If a label is specified control will be passed to the labeled paragraph of the program when a specific exceptional condition occurs Once a handle condition request has been made it remains active until another Handle condition request overrides If no error occur program control passes normally to the statements coded after the CICS command It is possible for several exceptions to occur on the same command concurrently. CICS checks for them in a fixed order and acts on the first one it finds.

Sample program for Error Handling


IDENTIFICATION DIVISION. PROGRAM-ID. EX3. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 RE-DATA. 02 TRNID PIC X(4). 02 FILLER PIC X(1). 02 INPMSG PIC X(5).

Maples ESM Technologies Pvt. Ltd

Page 167 of 246

CICS

01 SE-DATA. 02 ACK PIC X(24). 02 FILLER PIC X. 02 OUTMSG PIC X(5). 01 ERRMSG. 02 ERRTEXT PIC X(50). 77 MSGLEN PIC S9(4) COMP. PROCEDURE DIVISION. EXEC CICS HANDLE CONDITION ERROR(COMERR-PARA) LENGERR(LENGERR-PARA) END-EXEC. MOVE 10 TO MSGLEN. MOVE SPACES TO RE-DATA. EXEC CICS RECEIVE INTO(RE-DATA) LENGTH(MSGLEN) END-EXEC. MOVE 30 TO MSGLEN. MOVE SPACES TO SE-DATA. MOVE INPMSG TO OUTMSG. MOVE "ACKNOWLEDGED MESSAGE : " TO ACK. EXEC CICS SEND FROM(SE-DATA) LENGTH(MSGLEN) ERASE END-EXEC. EXEC CICS RETURN END-EXEC. LENGERR-PARA. MOVE 50 TO MSGLEN. MOVE " LENGTH DOES NOT MATCH " TO ERRTEXT. EXEC CICS SEND FROM(ERRMSG) LENGTH(MSGLEN) ERASE END-EXEC. EXEC CICS RETURN END-EXEC. COMERR-PARA. MOVE 50 TO MSGLEN. MOVE SPACES TO ERRMSG. MOVE "UNKNOWN ERROR" TO ERRMSG. EXEC CICS SEND FROM(ERRMSG) LENGTH(MSGLEN) END-EXEC. EXEC CICS RETURN END-EXEC. GOBACK. IGNORE CONDITION Using the IGNORE CONDITION command you can request CICS to ignore occurrences of specified exception conditions . When one of the specified conditions occurs, CICS returns control to the application program at the instruction following the command that caused the condition to occur.

Maples ESM Technologies Pvt. Ltd

Page 168 of 246

CICS

The general format is EXEC CICS IGNORE CONDITION Condition Name Condition Name END-EXEC. Condition name indicates an exceptional condition to be ignored Valid until subsequent Handle condition for this request is encountered

Example: EXEC CICS IGNORE CONDITION LENGERR END-EXEC. EXEC CICS RECEIVE Into ( Data-area) Length ( Length) END-EXEC. If Length error occurs in the above execution the condition will be ignored and control will be passed to the next statement There are two alternatives to Handle Condition for dealing with exceptional condition namely NOHANDLE and RESP NOHANDLE Option: The NOHANDLE option can be specified in any CICS command and it will cause no action to be taken for any exceptional condition

The general format is

EXEC CICS READ FILE ( File-name) INTO (record-area) RIDFLD ( reckey) Length (length of data) NOHANDLE END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 169 of 246

CICS

The NOHANDLE option in this command requests CICS to ignore any exception condition that occurs when the command is executed. If an exception condition occurs CICS returns control to the application program at the instruction immediately following the READ command . During execution of the above statement even if any exceptional condition occurs no action will be taken

RESP Option
Another way of doing this is to code the RESP option in the CICS command . The effect of the RESP option is similar to the NOHANDLE option. as CICS returns control to the application program . The program can determine the result of the command.

The RESP option can be specified in any CICS command. Its function is similar to the return code in the batch program. RESP is defined as a full word binary PIC S9(8) comp in the working storage. After executing the command the RESP field contains the exception code

Working-storage section 77 WS-resp pic S9(8) comp

EXEC CICS RECEIVE INTO (data area) LENGTH (length) RESP(WS-resp) END-EXEC.

WS-resp contains the return code of the command execution result If Ws-resp = DFHRESP(Normal) Go to normal-para . If WS-Resp = DFHRESP(Lengerr) Go to Len-error .

Sample program for error handling with RESP


IDENTIFICATION DIVISION. PROGRAM-ID. EX3. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 RE-DATA. 02 TRNID PIC X(4). 02 FILLER PIC X(1). 02 INPMSG PIC X(5).

Maples ESM Technologies Pvt. Ltd

Page 170 of 246

CICS

01 SE-DATA. 02 ACK PIC X(24). 02 FILLER PIC X. 02 OUTMSG PIC X(5). 01 ERRMSG. 02 ERRTEXT PIC X(50). 77 MSGLEN PIC S9(4) COMP. PROCEDURE DIVISION. MOVE 10 TO MSGLEN. MOVE SPACES TO RE-DATA. EXEC CICS RECEIVE INTO(RE-DATA) LENGTH(MSGLEN) RESP(EIBRCODE) END-EXEC. IF EIBRCODE = DFHRESP(NORMAL) GO TO SEND-PARA. IF EIBRCODE = DFHRESP(ERROR) GO TO COMERR-PARA. IF EIBRCODE = DFHRESP(LENGERR) GO TO LENGERR-PARA. SEND-PARA. MOVE 30 TO MSGLEN. MOVE SPACES TO SE-DATA. MOVE INPMSG TO OUTMSG. MOVE "ACKNOWLEDGED MESSAGE : " TO ACK. EXEC CICS SEND FROM(SE-DATA) LENGTH(MSGLEN) ERASE END-EXEC. EXEC CICS RETURN END-EXEC. LENGERR-PARA. MOVE 50 TO MSGLEN. MOVE " LENGTH DOES NOT MATCH " TO ERRTEXT. EXEC CICS SEND FROM(ERRMSG) LENGTH(MSGLEN) ERASE END-EXEC. EXEC CICS RETURN END-EXEC. COMERR-PARA. MOVE 50 TO MSGLEN. MOVE SPACES TO ERRMSG. MOVE "UNKNOWN ERROR" TO ERRMSG. EXEC CICS SEND FROM(ERRMSG) LENGTH(MSGLEN) END-EXEC. EXEC CICS RETURN END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 171 of 246

CICS

PUSH and POP Commands


The push and pop commands are used to suspend and reactivate all HANDLE CONDITION

requests which are in effect. While calling a subroutine the Handle conditions in force can be temporarily suspended using the PUSH command and restored before coming into the main program by issuing the POP command.

Also the PUSH and POP command can be used to suspend and reactivate the HANDLE AID command and HANDLE ABEND command Example EXEC CICS HANDLE CONDITION Cond(label) END-EXEC. PERFORM SUB-RTN THRU SUB-RTN-EXIT. EXEC CICS HANDLE CONDITION Cond(label) END-EXEC. SUB-RTN. EXEC CICS PUSH HANDLE END-EXEC. EXEC CICS HANDLE CONDITION Cond(label) END-EXEC. EXEC CICS POP HANDLE END-EXEC. SUB-RTN-EXIT. EXIT.

At the completion of the PUSH command in sub-rtn all HANDLE CONDITION in the main program will be suspended

In between PUSH and POP commands any other HANDLE CONDITION can be issued which is independent of the Handle Condition issued in the main program.

At the completion of the POP command, the suspended HANDLE CONDITION initiated by PUSH command will be reactivated.

Maples ESM Technologies Pvt. Ltd

Page 172 of 246

CICS

Attention Identifier Keys (Aid)


Indicates the method to initiate the transfer of information from terminal to CICS. PF keys, PA keys, ENTER & CLEAR key EIBAID contains , recently used AID code Standard AID list - is available as a copy library in DFHAID HANDLE AID establish the routines that are to be invoked when the aid is detected by a RECEIVE MAP command The HANDLE AID command is used to specify the label (paragraph) to which control is to be passed when a specified AID is received in the program After the completion of the terminal input command such as RECEIVE and RECEIVE MAP control will be passed to the specific paragraph in the program The General command format is

EXEC CICS HANDLE AID PF1 PF2 PA1 (label) (label) (label)

ENTER(label) CLEAR (label) ANYKEY(label) END-EXEC. The key ranges are PA! To PA3, PF! To PF24 ENTER and CLEAR The above keys are called Attention Identifier Keys (AID) Any key means any of the above except ENTER key Up to 16 options can be specified in the same command Alternative to Handle Aid Command The EIBAID field in the EIB contains the AID code of the most recently used AID key. Therefore EIBAID field can be tested after each terminal control or BMS input operation such as RECEIVE command CICS provides a standard AID list in the form of copy library member called DFHAID. It contains all the AID codes

The following is an example of using AID information

Maples ESM Technologies Pvt. Ltd

Page 173 of 246

CICS

IF EIBAID = DFHPF5 Perform Rtn-5 IF EIBAID = DFHCLEAR Perform Clear-screen EXEC CICS HANDLE AID PF5 (Rtn-5) CLEAR(clear-screen) PA1(Cancel-Rtn) ENTER(Normal-Rtn) ANYKEY(Wrong-key-rtn) END-EXEC.

CICS Program Control Commands


The CICS Program control Program ( PCP) governs the flow of control among the CICS application programs. The name of the application program must be registered in the PPT

The following commands are available for the program control functions. LINK - To pass control to another program at a lower level and getting the control back XCTL - To pass control to another program at the same level and not expecting the control to be returned RETURN - To return to the next higher level program or CICS LOAD To load a program RELEASE - To release a loaded program

In CICS application program it is a normal practice to pass control to another program in the course of completing a transaction. This is achieved by two CICS transactions namely LINK and XCTL.

Application programs running under CICS runs at various logical levels. The first application program within a task and receiving control directly from CICS runs at the highest logical level.

On a LINK command, the linked program is considered to be executing at one logical level lower than the program that issued the LINK command.

On a XCTL command, the called program executes at the same logical level as the calling program.

Maples ESM Technologies Pvt. Ltd

Page 174 of 246

CICS

A RETURN command always passes control back to the next higher logical level. A transaction is said to be complete, when the program at the highest logical level returns control to the next higher logical level which is CICS itself.

LINK Command
Used to link to a subroutine program, Causes a CICS application program to be loaded into main memory and passes control to it . The calling (LINKing) program expects control to be returned to it. Links to a lower level program Program is not terminated Data passed to the lower program through the commarea area option is passed by reference i.e. any modification done in the subroutine is reflected in the main program

Maples ESM Technologies Pvt. Ltd

Page 175 of 246

CICS

Handle Conditions , Attention Identifiers and abends are not transferred with the execution of the CICS command and any in effect are restored when control is returned to the calling program. EXEC CICS LINK Program ( Program name) Commarea (Data area ) Length (Data value) END-EXEC.

Exception conditions
AEIO PGMIDERR AEIV LENGERR Occurs when either program is not loaded in PPT or it is disabled Occurs when Length specified is greater than what is specified in the DFHCOMMAREA under Linkage Section.

XCTL Command
Transfers control to the next program Program passing control is terminated Transaction ID does not change Control is passed at the same logical level Program that transfers control is released When the program that is to receive control is not resident in main storage, it is loaded by CICS

EXEC CICS XCTL Program ( Program name) Commarea ( data-area) Length ( data-value) END-EXEC.

RETURN Command
Used to return control to a program executing at the next higher logical level

EXEC CICS RETURN

Maples ESM Technologies Pvt. Ltd

Page 176 of 246

CICS

TRANSID ( trans-id name) Commarea( data-name) Length ( length) END-EXEC.

TRANSID

Used to specify the transid for the next transaction to be to be associated with the terminal tasks effect only after the highest logical level has returned control to CICS

COMMAREA

Specifies a communication area that is to be made available to the next task being invoked. The data is available to the next task in DFHCOMMAREA declared in the Linkage Section.

LENGTH

Specifies a half-word binary value of the length of commarea.

LOAD Command
The LOAD command execution will fetch an application program, a table or map when no copy currently exists in storage.

EXEC CICS LOAD PROGRAM ( pgmname) SET ( ptrref) END-EXEC.

PROGRAM - Name of the 8 char program name defined in PPT SET loaded - Set the pointer reference value to the address of where the program , table or map is

RELEASE Command
This command will release one of the following which was previously loaded by issuing the LOAD command loaded program ,table or mapset.

EXEC CICS RELEASE PROGRAM ( pgmname) END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 177 of 246

CICS

Optional Addressability Available


A CICS application program can use ASSIGN commands to access information that is valid but outside the local environment of the CICS application program.

ASSIGN command is used to access the length of CICS storage areas. The general command format is EXEC CICS ASSIGN [USERID ABCODE CWALENG (data-area)] (data-area)] (data-area)]

[TCTUALENG (data-area)] [TWALENG END-EXEC. Puts the value of the option selected in the data area specified. The data area must be defined in the working-storage section as PIC S9(4) Comp. Upto 16 options can be specified in one ASSIGN command. The above option is only a partial list of options available under ASSIGN command. (data-area)]

CSA Common System Area


Major Systems Control Block. Created at System Initialization. Exists for the life of the CICS job. Used for communication between management modules. Gives full access to all fields in CICS/ESA control blocks and storage areas. Should be used with extreme caution. One CSA for one CICS system. Addressability to the CSA is optional.

CWA Common Work Area


CICS System Work Area Storage information which is unique at the system level for all CICS application programs. E.g. Clients name. One CICS system has only one CWA. Defined by the system programmer in SIT.

Maples ESM Technologies Pvt. Ltd

Page 178 of 246

CICS

TCTUA Terminal Control Table User Area


A work area associated with a terminal. TCTUA is defined as one per terminal in TCT. This user area can store information unique to a terminal.

TWA Transaction Work Area


A work area associated with a task. TWA is defined on one per transaction in PCT. TWA is released when a task is terminated. Used extensively as a work area to pass information between programs within the same task. Used to store information unique to this transaction.

CWALENG
Places the length of the Common Work Area in the data-area specified.

TCTUALENG
Places the length of Terminal Control Table User Area in the data-area specified.

TWALENG
Places the length of the Transaction Work Area in the data-area specified.

INTERVAL & TASK CONTROL ASKTIME


Used to obtain current date and time The EIBDATE and EIBTIME fields have the values at task initiation time. Upon completion of this command these fields will be updated and will have the current date and time. Syntax: EXEC CICS ASKTIME[ABSTIME(data-area)] END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 179 of 246

CICS

EIBDATE and EIBTIME updated with current date and time ABSTIME returns value of time in packed decimal format PIC S9(15) COMP-3.

Format Time
The FORMATTIME command will transform the absolute date and time into any one of a number of the optional formats listed below. Syntax: EXEC CICS FORMATTIME ABSTIME(data-ref) [YYDDD(data-area)] [YYMMDD(data-area)]... etc. [DATE(data-area) [DATEFORM[(data-area)]]] [DATESEP[(data-value)]] [DAYOFMONTH(data-area)] [MONTHOFYEAR(data-area)] [YEAR(data-area)]..... [TIME(data-area) [TIMESEP[(data-value)]]] END-EXEC. Condition: AEIP INVREQ

Sample program for Date and Time display.


IDENTIFICATION DIVISION. PROGRAM-ID. EX7. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 ASK-TIME PIC S9(15) COMP-3. 01 ASK-TIME1 PIC X(80) VALUE SPACES. 01 ASK-DATE1 PIC X(80) VALUE SPACES. 01 W-LEN PIC S9(4) COMP. PROCEDURE DIVISION. EXEC CICS ASKTIME ABSTIME(ASK-TIME) END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 180 of 246

CICS

EXEC CICS FORMATTIME ABSTIME(ASK-TIME) YYYYMMDD(ASK-DATE1) DATESEP('-') TIME(ASK-TIME1) TIMESEP END-EXEC. MOVE 72 TO W-LEN. EXEC CICS SEND TEXT FROM(ASK-TIME1) LENGTH(W-LEN) ACCUM ERASE END-EXEC. MOVE 70 TO W-LEN. EXEC CICS SEND TEXT FROM(ASK-DATE1) LENGTH(W-LEN) ACCUM ERASE END-EXEC. EXEC CICS SEND PAGE END-EXEC. EXEC CICS RETURN END-EXEC.

DELAY
Used to DELAY the processing of a task The issuing task is suspended for a specified interval or Until the specified time Syntax: EXEC CICS DELAY INTERVAL(hhmmss) | TIME(hhmmss) END-EXEC Example: EXEC CICS DELAY INTERVAL(002015) END-EXEC. The task will be suspended for 20 mins and 15 secs. EXEC CICS DELAY TIME ( 153000) END-EXEC. The task will be suspended until 15:30:00 .

Maples ESM Technologies Pvt. Ltd

Page 181 of 246

CICS

Basic Mapping Support


Before you can code a CICS program, you need a complete set of program specifications that includes a screen layout for each screen the program displays you have to define each screen using Basic Mapping Support ( BMS) . In this chapter you will learn how to use BMS to create screens that are easy to use . Even if you use a screen painter, to generate the BMS code ( using Screen Definition Facility ) you will need this knowledge to understand and modify the generated code.

Topics in BMS
Introduction to BMS Physical and Symbolic Map Map and Mapset Map Definition Macros

Introduction to BMS
Basic Mapping support (BMS) is a part of the terminal management service module of CICS. BMS is a facility that moves data streams to and from the terminal .The following services are provided by BMS Allows one program to converse with different types of terminals Inserts control characters into the message to be sent based on terminal type Maintains field location on the screen Stores all display fields in a table called MAP Assembles series of macro instructions to create a physical and a symbolic map.

Primary Functions of BMS


Removal of device dependent codes from Application Program by placing them in Maps Removal of constant information from Application program (Headers, Titles...) by placing the default constants in maps Provides text handling capability , terminal paging facility which allows accumulation of several small mapped data areas into one or more pages of output Terminal Paging & Message routing which allows sending of messages to one or more terminals

Maples ESM Technologies Pvt. Ltd

Page 182 of 246

CICS

On a command to read data from a terminal , it strips formation from the transmitted stream so that only the relevant data is placed in the storage corresponding to the symbolic map area On a command to display data on a terminal, it inserts terminal formatting information into the data being transmitted

Map & Mapset


Representation of one screen format is called Map (screen panel). One or more maps, link edited together, makes up a Mapset (load module). Mapset must have a entry in PPT Mapset name has two parts. Generic name 1- 7 chars. Suffix 1 char. Used in Application Program. To identify the device type

If the same mapset is used for different types of terminals CICS automatically inserts the suffix depending on the terminal in use thereby ensuring device independence

Types of Maps Physical Map


Physical Map is a map used by CICS (MAP) Ensure device independence in the application program Coded using BMS macros assembled separately and link edited into the CICS load library It is a program in the form of a load module stored in one of the run-time libraries and CICS loads it when executing a program using this map

Symbolic Map
Ensure device and format independence in the application program Symbolic Map is a map used by Application Program (DSECT) Coded using BMS macros assembled separately The symbolic map structure is stored in a copy library along with similar copy structures like file record layouts which is simply copied in a CICS application program at the time of program compilation

Maples ESM Technologies Pvt. Ltd

Page 183 of 246

CICS

Serves as a DSECT (COBOL data structure) for referencing the Terminal Input Output Area (TIOA). This structure defines all the variable fields which will be either read or written in a program Application program copies it by issuing a COBOL COPY statement in the Working-Storage Section. Since the primary objective is to ensure device and format independence of the application programs a layout change in the map can be done independent of the application program code as long as the field name and length remain the same. Example of Symbolic Map 01 EMPRECI. 02 FILLER 02 EMPNAL 02 EMPNAF PIC X(12). PIC S9(4) COMP. PIC X.

02 FILLER REDEFINES EMPNAF. 03 EMPNAA PIC X. 02 EMPNAI PIC X(21).

01 EMPRECO REDEFINES EMPRECI. 02 FILLER 02 FILLER 02 EMPNAO How to code a Mapset Macro DFHMSD DFHMDI Usage Coded to specify parameters that apply to the entire mapset Coded once for each map within the mapset, specifies parameters that apply to the entire map. If there is more than one map the next occurrence of a DFHMDI marks the end of one map and the beginning of next map Coded once for each variable field, constant value or an attribute byte within the map. Specifies the position length and attributes of each map field. Coded after the last map in the mapset tells BMS that the mapset TYPE=FINAL is complete Must be the last statement in the mapset definition tells the assembler that there are no more source statements PIC X(12). PIC X(03). PIC X(21).

DFHMDF DFHMSD END

Maples ESM Technologies Pvt. Ltd

Page 184 of 246

CICS

Map Definition
General Format 1 Label 10 operation 16/17 operands 72 contd.

Label: Specifies the symbolic name for the statement. Must be coded from column 1 and begins with an alphabet upto 7 characters. A * in column 1 is treated as comment line

Operation: Specifies an instruction to be executed for a BMS macro code DFHMSD, DFHMDI or DFHMDF. Must be coded from column 10

Parameters: Specifies one or more items of information required for the macro. If parameters are continued to another line , place a comma after the Last parameter and code X in column 72 and code the next parameter From column 16 onwards Label Specifies the mapset name of one to seven characters beginning with an alphabet. This name is used in the commands that receives data (Receive Map) from or sends data (Send Map) to a terminal. When a map program is assembled to generate the physical map this label is used as the load module name DFHMSD This marks the beginning of a mapset definition by specifying its characteristics using the following parameters TYPE For format 1, specifies whether a physical map ( MAP), symbolic map (DSECT), or both ( &SYSPARM) will be generated . TYPE=&SYSPARM is usually coded. For format-2 , marks the end of a mapset (TYPE=FINAL) Specifies the source language to be used for the symbolic MAP. The default is ASM (Assembler) Specifies whether mapset is used for input (IN) , output (OUT) or both.(INOUT) Also specifies how the symbolic map is generated Mapname fieldname is suffixed with I length field is suffixed with L Mapname fieldname is suffixed with O attribute byte with A Generates both the input and output symbolic map areas. Output area is only redefinition of input area. Specifies a list of device control characteristics in effect for each map in the mapset. It is used only when TYPE=MAP is specified. Valid options are FREEKB: Unlock the terminal keyboard after each output operation. Otherwise the user must press the reset key each time FRSET: Specifies that all Modified Data Tags (MDT) be turned off when the map is sent to the terminal

LANG MODE IN OUT INOUT CTRL

Maples ESM Technologies Pvt. Ltd

Page 185 of 246

CICS

STORAGE

TIOAPFX

DSATTS MAPATTS COLOUR Description

ALARM sound the audio alarm during each output operation. If storage=auto is coded, the symbolic maps for the maps in the mapset will occupy separate storage locations. Otherwise, they will occupy the same storage location. Usually coded as STORAGE=AUTO YES Generates a 12 bytes Filler item at the beginning of the symbolic map. Should always be specified for COBOL programs. Required for CICS command level programs to reserve a 12 bytes control area for BMS commands to access TIOA Specifies which extended attributes are to be supported in the symbolic map. The attribute types supported are Color, Hilight etc. Specifies which extended attributes are to be supported in the physical map Specifies a default extended colour in all fields in all maps in a mapset

You use format-1 of the DFHMSD macro at the beginning of a mapset to define the mapset. You use Format 2 just before the END command at the end of a mapset. When you specify COBOL for the LANG parameter, the symbolic map will be a 01 level group item that can be copied into a COBOL program. If the CTRL options applies to all the maps in the mapset you should code them on the DFHMSD macro. Otherwise you can code the appropriate options on the DFHMDI macro for each map. You should always code the FREEKB option of the CTRL parameter: otherwise , the keyboard is locked each time a map is sent to the terminal and the user has to press the reset key to enter the data. If you want to change a fields color or extended highlighting within your COBOL program, you must include the DSATTS parameter. And whenever you code DSATTS, you need to code MAPATTS with the same set of options

DFHMDI Defines the map within the mapset, supplies the maps name size and position The DFHMDI macro can override defaults specified in a DFHMSD macro The DFHMDI macro can be coded as often as needed within a DFHMSD The largest map in the map set should be coded first for COBOL language

LABEL

Specifies the map name of 1-7 characters beginning with alphabet. It identifies a specific map within a mapset

DFHMDI SIZE

This marks the beginning of an individual map definition Specifies the dimension of the map in lines and columns. Map size may be equal to or less than the screen size

Maples ESM Technologies Pvt. Ltd

Page 186 of 246

CICS

LINE COLUMN

Specifies the starting line number for the map Specifies the starting column number for the map

Description You use the DFHMDI macro to define a map within a mapset. The label on the DFHMDI macro is the name you will use to refer to the map in your COBOL code. If you dont code the CTRL parameter on the DFHMSD macro for the entire mapset, you can code it on the DFHMDI macro for an individual map.

DFHMDF Defines a field within a map by specifying its position length and attributes The DFHMDF macro for a field can override the defaults specified in the DFHMDI macro for that map. Code as many DFHMDF as needed for a map. For a protected field, only one DFHMDF macro is required. For an unprotected field, two DFHMDF macros are required. One to mark the beginning of the field and the other to mark the end. Label Specifies the field name of 1-7 characters beginning with an alphabet. It identifies a specific field within a map. If it is omitted application programs cannot access the field. The maximum number of named fields in a map for COBOL is 1023 Marks the beginning of an individual field definition Specifies the position of the attribute byte for a field. Every field begins with its attribute byte Specifies the length of a field excluding its attribute byte. This length is used in the symbolic map. Maximum length is 256 bytes Specifies the attribute strings for the field. Defaults to ASKIP & NORM if no attribute is specified Defaults to UNPROT & NORM if any attribute is specified Normal display intensity Bright display intensity Not displayed The field is protected and the cursor will not skip over it The field is unprotected and data may be keyed into it The field is protected and the cursor will automatically skip over it The field is numeric and minus sign are allowed. If omitted alphanumeric is assumed. Insert cursor in the first position of the field. If specified for more than one field the last one specified will take effect

DFHMDF POS LENGTH ATTRB

NORM BRT DRK PROT UNPROT ASKIP NUM IC

Maples ESM Technologies Pvt. Ltd

Page 187 of 246

CICS

FSET

INITIAL PICIN

PICOUT

GRPNAME

JUSTIFY

Turns on the MDT before the map is sent to the terminal. This causes the field to be transmitted back to the program whether or not the user keys into it. If not specified, the field is transmitted only when the user changes it Specifies a constant or default value for the output field Specifies a COBOL PIC string format of numeric data for input. The length represented by PICIN must agree with the length parameter .If omitted PIC = X(N) will be assumed where N is the length specified. Specifies a COBOL PIC string format of numeric edited data for output. The length represented by PICOUT must agree with the length value specified. specified that the field should be grouped in the symbolic map with other fields with the same GRPNAME. All fields within a group must be coded in sequence in the mapset and must have labels. Defaults are if the field is numeric right justify and zero fill. If the field is non numeric left justify and blank fill A numeric value indicating the number of occurrences for that field across on the same line

OCCURS

Symbolic MAP
BMS generated symbolic map When BMS generates a symbolic map it uses the seven character label name supplied in the mapset to form the eight character data names A one character suffix is added to the end of each label name to indicate the data names function. In the symbolic mapset these data names are coded in a specific order to match the data structure BMS requires If MODE=IN is specified only input part of the symbolic map is generated If MODE=OUT is specified only output part of the symbolic map is generated The first part corresponds to the input screen and is always labeled with the map name suffixed by I for input and the second part suffixed by O for the output The output map always redefines the input map at 01 level. For a map MENUMAP BMS generates MENUMAPI for input and MENUMAPO for output For each labeled DFHMDF macro in the map BMS generates several data names in a specific order as follows The first 12 bytes of a symbolic map are always defined as Filler because TIOAPFX =YES is specified .They are reserved for CICS control information The first two bytes for each variable field indicate the number of characters present in the input field The next byte indicates the variable field attribute The flag byte is redefined by the attribute byte The actual data field follows next

Maples ESM Technologies Pvt. Ltd

Page 188 of 246

CICS

Data Name suffixes

A binary half word [ PIC S9(4) COMP] that contains the length of the data that is returned in the input field

A single character field ( PIC X ) that contains hexadecimal 80 if the user made a change to the field, but no data was transmitted: otherwise it contains Low-Value

A single character field that contains the attribute byte for output operations. Occupies the same storage location as the F field

A single character field that contains the attribute for extended color. Generated only if DSATTS=COLOR is specified for the mapset

A single character field that contains the attribute for extended highlighting. Generated only if DSATTS=HILIGHT is specified for the mapset

The Input data field

The output data field. Occupies the same storage location as the input field

Example EMPMAP DFHMSD TYPE=MAP, MODE=INOUT, LANG=COBOL, STORAGE=AUTO, TIOAPFX=YES X X X X

* *

ANY COMMENTS

Order of Macros 1 2 3 4 5 6 7 8 9 10 DFHMSD TYPE=DSECT DFHMDI DFHMDF DFHMDF : DFHMDI DFHMDF DFHMDF DFHMSD TYPE=FINAL END Mapset Map A field A field Map A field A field Mapset

DFHMSD Macro Define a mapset and its characteristics or to end a mapset definition Only one mapset is allowed in one assembly run. Example EMPMSET

DFHMSD TYPE=&SYSPARM , MODE=INOUT, LANG=COBOL,

X X X

Maples ESM Technologies Pvt. Ltd

Page 189 of 246

CICS

STORAGE=AUTO, TIOAPFX=YES, CNTL=(FREEKB,FRSET,PRINT) DFHMDI Macro Define a map and its characteristics Example EMPMAP DFHMDI SIZE=(ll,cc), LINE=nn, COLUMN=mm, JUSTIFY=LEFT/RIGHT DFHMDF Macro for the above layout Define a field and its characteristics Example DFHMDF POS(ll,cc), INITIAL=Customer No. :, ATTRB=ASKIP, LENGTH=14 CUSTNO DFHMDF POS=(ll,cc), ATTRB=(UNPROT,NUM,FSET,IC), JUSTIFY=RIGHT, PICIN=9(8), PICOUT=z(8), LENGTH=8

X X

X X X

X X X

X X X X X

Attribute Character
Invisible one byte character Defines the characteristics of a field through ATTRB parameter of DFHMDF. There are different kinds of attributes Attributes to control the display intensity of the field Keyboard Attributes Attribute Related to the Field Modification Cursor Control Attribute

Maples ESM Technologies Pvt. Ltd

Page 190 of 246

CICS

Attribute Character Format


The attribute character is a one byte (8 bits) of data consisting of the following pattern BIT 0.1 1 3 2.3 4.5 Function Value determined by contents of bits 2 to 7 0 Unprotected 1 Protected 0 Alphanumeric 1 Numeric 11 Auto Skip 00 Normal Intensity 10 High Intensity 11 Dark 0 Must be 0 0 Not modified (MDT off) 1 Modified (MDT on)

6 7

Creation of Map using BMS Macro


MAP005 HEADER DFHMSD TYPE=&SYSPARM,MODE=INOUT,LANG=COBOL, STORAGE=AUTO,TIOAPFX=YES DFHMDI SIZE=(24,80),CTRL=(FRSET,FREEKB) DFHMDF POS=(01,01),ATTRB=(ASKIP,NORM),LENGTH=18, INITIAL='DEPARTMENT MASTER' DFHMDF POS=(01,79),ATTRB=(ASKIP,NORM),LENGTH=18, INITIAL='AX' DFHMDF POS=(08,15),ATTRB=(ASKIP,NORM),LENGTH=5, INITIAL='CODE:' DFHMDF POS=(08,21),ATTRB=(UNPROT,FSET,IC),LENGTH=4, INITIAL=' ' DFHMDF POS=(08,26),ATTRB=(PROT,NORM),LENGTH=1, INITIAL=' ' DFHMDF POS=(10,15),ATTRB=(ASKIP,NORM),LENGTH=12, INITIAL='DESCRIPTION:' DFHMDF POS=(10,30),ATTRB=(UNPROT,FSET),LENGTH=25, INITIAL=' ' DFHMDF POS=(10,56),ATTRB=(PROT,NORM),LENGTH=1, INITIAL=' ' DFHMDF POS=(22,15),ATTRB=(PROT,FSET),LENGTH=35, INITIAL=' ' DFHMDF POS=(23,15),ATTRB=(ASKIP,BRT),LENGTH=30, INITIAL='PF1=ADD,PF2=DELETE,PF3=MODIFY,' DFHMDF POS=(23,46),ATTRB=(ASKIP,BRT),LENGTH=40, INITIAL='PF4=VIEW,PF5=CLEAR,PF9=EXIT' DFHMSD TYPE=FINAL END X

X X X X X X X X X X X

CODE

DESC

MSG

Maples ESM Technologies Pvt. Ltd

Page 191 of 246

CICS

Modified Data Tag


Indicates the field has been modified or not Effective use of MDT reduces the amount of data traffic. MDT setting/resetting when the user modifies a field on the screen CNTL=FRSET, defined in map/mapset FSET in ATTRB parameter of DFHMDF

Skipper Technique
Unlabelled 1-byte field with the autoskip attribute DFHMDF POS(ll,cc),ATTRB=ASKIP,LENGTH=1 To skip the cursor to the next unprotected field after one unprotected field. Screen Layout : &xxxxx&$ where $ - Skipper field, & - Attribute byte, X - Unprotected field &xx

Stopper Technique
Unlabelled 1-byte field with the protect attribute DFHMDF POS(ll,cc),ATTRB=PROT,LENGTH=1 To stop the cursor in order to prevent erroneous field overflow by terminal user. Screen Layout : &xxxxx&$#&$ where, # Stopper field

RECEIVE MAP (Input)


Used to receive the contents of a map from the terminal, after the completion of the command the relevant symbolic map area will contain data received from the terminal in the following three fields for each variable field defined by the DFHMDF macro

Fieldname + L

the length field contains actual number of characters keyed in screen field in binary form.

Maples ESM Technologies Pvt. Ltd

Page 192 of 246

CICS

Field name + F

the flag byte field contains normally X00 (low-value) It will be X80 if the screen field has been modified.

Field name + I

the actual input data field, If no data were keyed in the field low-value will be filled.

The General Format is EXEC CICS RECEIVE MAP (map name) MAPSET (mapset name) INTO (data area ) END-EXEC.

SEND MAP (Output)


Used to send information to the terminal, before issuing this command the application program must prepare the data in the following three fields for each field defined by the DFHMDF macro in the symbolic map area

Field name + L Field name + A

the length field the attribute byte field which can be sent to any required attribute feature for output display

Field name + O

the actual output data field to which the application program must move required data

Manipulating Cursor position and Attribute Dynamically at run time The cursor position can be dynamically placed at the beginning of any field by moving 1 to the length component of the field in the symbolic map Similarly the attribute of any field can be changed at run time by moving the corresponding DFHBMSCA macro to the respective attribute byte of the field concerned. Move 1 to Field L to change the cursor position dynamically Move DFHBMASK to Field A to change the attribute at run time DFHBMSCA is available as a copy library which can be copied in the working-storage by issuing the command COPY DFHBMSCA Example DFHBMASK DFHBMFSE DFHUNNUM The general format is Autoskip Unprotected, MDT on Unprotected, MDT on, Numeric

Maples ESM Technologies Pvt. Ltd

Page 193 of 246

CICS

EXEC CICS SEND MAP (map name) MAPSET (mapset name) FROM (data area) [DATA ONLY/MAP ONLY] [ERASE/ERASEUP] [ACCUM] [CURSOR] END-EXEC. CURSOR Specifies a half word binary field of PIC S9(4) Comp or a literal value that indicates the relative position at which the cursor is to be positioned. Column 1 of row 1 is position zero and so on. The data value is relative to zero. DATA ONLY Specifies that only data and attribute byte from symbolic map area are to be sent to the terminal. The constants in the physical map are not sent MAP ONLY Specifies that only the constants in the physical map are to be sent. No symbolic map area is to be sent ERASE Specifies that the previous display on the screen will be erased before the new screen is displayed. When used with ACCUM option this causes the display to be erased as each page is mapped, not as each map is accumulated ERASEUP Causes all the unprotected fields on the screen to be erased before the output is mapped. ACCUM Specifies that several SEND MAP commands may be issued to accumulate a single logical message of one or more pages which must be displayed by a SEND PAGE command

TEXT Building commands Send Text


Used to send text data to a terminal without mapping support BMS automatically formats the data breaking lines between words where possible The general format is

EXEC CICS SEND TEXT FROM(Data area) HEADER(data-area)

Maples ESM Technologies Pvt. Ltd

Page 194 of 246

CICS

TRAILER(data-area) ERASE ACCUM END-EXEC.

HEADER

Specifies a data area that contains the text to be placed at the beginning of each page of text data

TRAILER

Specifies a data area that contains the text to be placed at the bottom of each page of text data

ACCUM

Several SEND TEXT commands may be issued to accumulate a single logical message which must be displayed by a SEND PAGE command

Sample program with Send Text with ACCUM and Page Option
IDENTIFICATION DIVISION. PROGRAM-ID. EX5. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-1. 02 TRID PIC X(4). 02 FILLER PIC X(1). 02 A PIC X(5). 02 B PIC X(5). 02 C PIC X(5). 01 WS-2. 02 A1 PIC X(80). 02 B1 PIC X(80). 02 C1 PIC X(80). 77 MSGLEN PIC S9(4) COMP. PROCEDURE DIVISION. MOVE 20 TO MSGLEN. EXEC CICS RECEIVE INTO (WS-1) LENGTH(MSGLEN) END-EXEC. MOVE A TO A1. MOVE 70 TO MSGLEN. EXEC CICS SEND TEXT FROM (A1) LENGTH(MSGLEN) ACCUM END-EXEC. MOVE B TO B1. MOVE 75 TO MSGLEN. EXEC CICS SEND TEXT FROM (B1) LENGTH(MSGLEN) ACCUM END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 195 of 246

CICS

MOVE C TO C1. MOVE 75 TO MSGLEN. EXEC CICS SEND TEXT FROM (C1) LENGTH(MSGLEN) ACCUM ERASE END-EXEC. EXEC CICS SEND PAGE END-EXEC. EXEC CICS RETURN END-EXEC. GOBACK.

Text Header & Trailer


A text header and trailer can be attached to the text body during command execution The text header and trailer must be constructed in a particular format as given below LL P LL P C data ppp data

the half word binary field S9(4) comp containing the length of the data. a character denoting the position of the page number contained in the data if automatic page numbering is requested. Otherwise this byte should be a space.

C Data Ppp

a one byte control field used by BMS the actual data of the Header or Trailer the position of the page number

01 02 02 02 02

TEXT-HDR. Filler Filler Filler Filler pic S9(4) Comp value 40. pic X value & pic X. pic X(40) value Sales Report For Jan 2003 Page &&

Cursor Positioning Techniques


Static positioning (map definition) Dynamic/Symbolic Positioning (app.pgm) Dynamic/Relative Positioning (app. pgm) Checking Cursor Position by EIBCPOSN.

Maples ESM Technologies Pvt. Ltd

Page 196 of 246

CICS

Numeric Sign / Decimal Point Handling


Numeric Sign: For input operations, Separate fields or CR/DR field approach can be used and for output operations, PICOUT parameter can be given in macro. Decimal Point: For input operations, Virtual decimal point or Separate fields approach can be used and for output operations, PICOUT parameter has to be given in the field definition macro.

Send Map
Writes formatted output to a terminal. Syntax : EXEC CICS SEND MAP(mapname) [[ FROM(dataname) ] [DATAONLY] | MAPONLY] [ MAPSET(mapsetname) ] [ CURSOR(VALUE) ] [ FREEKB ][ ERASE ][ FRSET ] [ HANDLE | NOHANDLE [ RESP (dataname) ] ]

END-EXEC Conditions: AEIP INVREQ AEIV LENGERR

Receive Map
To receive input from a terminal Syntax : EXEC CICS RECEIVE MAP (mapname) [ SET(pointer) | INTO(dataname) ] [LENGTH(msg-len)] [ MAPSET(mapsetname) ] [ HANDLE | NOHANDLE [ RESP() ] ]

END-EXEC Conditions: AEIP INVREQ AEI9 MAPFAIL

Maples ESM Technologies Pvt. Ltd

Page 197 of 246

CICS

Sample conversation program send map accum receive data from screen using pseudo conversation

IDENTIFICATION DIVISION. PROGRAM-ID. TRG014P1. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. COPY FIRSTP. 01 COMMAREA. 02 VARS PIC X(4). 01 REC1. 10 KEYR PIC X(4). 10 NAMER PIC X(20). 10 ADDRR PIC X(20). 10 PHR PIC X(10). 10 DOBR PIC X(10). 10 FILLER1 PIC X(15). LINKAGE SECTION. 01 DFHCOMMAREA. 02 VARS PIC X(4). PROCEDURE DIVISION. MAIN-PROC. IF EIBCALEN = 0 PERFORM SEND-MAP PERFORM RETURN-TRANS. IF VARS OF DFHCOMMAREA = "COMM" PERFORM RECEIVE-MAP PERFORM TRANS-END. SEND-MAP. MOVE LOW-VALUES TO HEADERO. MOVE LOW-VALUES TO HEADO. EXEC CICS END-EXEC. EXEC CICS SEND MAPSET('MAP011') MAP('HEADER') ACCUM PAGING END-EXEC. EXEC CICS SEND PAGE END-EXEC. RECEIVE-MAP. EXEC CICS RECEIVE MAPSET('MAP011') MAP('HEADER') END-EXEC. MOVE SPACES TO REC1. MOVE CODEI TO KEYR. MOVE NAMEI TO NAMER MOVE ADDRI TO ADDRR MOVE PHI TO PHR MOVE DOBI TO DOBR * EXEC CICS SEND TEXT FROM(REC1) END-EXEC. EXEC CICS XCTL PROGRAM ( 'MTRGP005') END-EXEC. RETURN-TRANS.

Maples ESM Technologies Pvt. Ltd

Page 198 of 246

CICS

MOVE "COMM" TO VARS OF COMMAREA. EXEC CICS RETURN TRANSID(EIBTRNID) COMMAREA(COMMAREA) LENGTH(LENGTH OF COMMAREA) END-EXEC. TRANS-END. EXEC CICS RETURN END-EXEC. GOBACK.

File Control
This chapter briefly explains handling of VSAM files in CICS environment or how CICS manages VSAM In its region. Unlike a batch environment where files are described in the File Section under Data Division., here there is no concept of a File Section and the record is described in WorkingStorage Section. You will also understand how files are opened or closed and the accessing mode used in application.

VSAM
Different types of VSAM Datasets used in CICS are: ESDS KSDS RRDS Entry Sequenced Dataset Key Sequenced Dataset Relative Record Dataset

Services provided by CICS


Basic Operations required for a file are Adding a Record. Modifying an Existing Record. Deleting an Existing Record. Browsing One or Selected or All Records.

In Addition, CICS Provides Exclusive Control. (Record Level Locking). Data Independence. Journaling. Opening and closing Files.

Maples ESM Technologies Pvt. Ltd

Page 199 of 246

CICS

Defining Files
In CICS, Files cannot be created, Files can be created using IDCAMS Utility. Re-indexing, Creating new indexes, etc. should be done using IDCAMS Only.

Defining a file to CICS


Files should be defined in FCT (File Control Table). FCT will contain all the Information about a File (like dataset name, access methods, permissible file service request, etc.) Defining Files can be done either by CEDA Transaction or DFHFCT Macro.

All CICS files must be defined in the File Control Table ( FCT) The FCT eliminates the need for the programmer to define those data dependent variables in the INPUT-OUTPUT SECTION , SELECT statement , FD statement , JCL etc. thus giving data independence to the application programs. The file characteristics are defined to CICS in the FCT by the system programmer. The application programmer can code programs using the CICS commands to access the files for various operations as provided. Opening and closing of Files When an application program accesses a file, the file must be open under CICS . Files used by CICS are usually opened during start-up time CICS files must be closed if they need to be changed by a batch program since they cannot be updated by both CICS and the batch system concurrently. If the file is closed you can open the file using the Master Terminal Transaction ( CEMT) before initiating an application program.. SYNTAX OF DFHFCT MACRO DFHFCT TYPE=FILE, ACCMETH=VSAM, DATASETNAME=NAME, SERVRQ=(ADD,BROWSE,DELETE,READ,UPDATE), FILSTAT=(ENABLED,OPENED)

File Control Commands


READ READ FOR UPDATE Read a file for inquiry or access without update Read a file with the intent of changing the record

Maples ESM Technologies Pvt. Ltd

Page 200 of 246

CICS

REWRITE UNLOCK DELETE STARTBR READNEXT

Modify a record , read for update Release a record read for update , if update is not required Delete a record from the file Establish a starting point for a browse Read the next record after the STARTBR or a prior READNEXT command

READPREV

Read the previous record after the STARTBR or a prior READPREV Command

ENDBR RESETBR

Terminate a browse operation initiated by a STARTBR command End the previous browse operation and start anew one.

File Handling in Programs


Files should not be defined in the Program. Program should not open or close a File. Records can be written in any order. A number of records can be added at a time. Records can be inserted, updated or deleted. IMPORTANT KEY-WORDS Dataset/File Into/From (WS-Rec) : : Name in the FCT. Working-Storage Area defined in the program where the CICS Puts/Gets Data. RIDFLD RESP LENGTH : : : Contains the Record Key. Contains the return code of the executed command. Length of the Record to be Retrieved or Written.

Random Read
EXEC CICS READ File (filename) Into (data area ) RIdfld(Rec-Key) Keylength (datavalue) [Generic] [gteq/equal] Length(data value) [RBA/RRN] [update] END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 201 of 246

CICS

File Ridfld Keylength Generic Gteq Equal Length RBA RRN Update

File name has to be specified which should be defined in the FCT Specifies the record identification field contents can be a key (KSDS) RBA (ESDS), RRN (RRDS) Specifies length of key specified in RIDFLD. This option is invalid for ESDS or RRDS. Mandatory when generic is specified Specifies that the search key is generic whose length is specified in Keylength Condition for the search, either that key value or the next higher value will satisfy the search Only the same key value will satisfy the search Length of the record Relative byte address of the record Both for KSDS and ESDS Relative record number Only for RRDS This option specifies that the record is read with an intention to Update. In this case the CI containing the record is automatically locked.

Condition: AEXL DISABLED AEIS NOTOPEN

AEIM NOTFND AEIV LENGERR

AEIO DUPKEY AEIP INVREQ

AEIQ IOERR.

EXAMPLE FOR RANDOM READ

EXEC CICS READ File( 'INVMAS ') Into(WS-INVMAS-REC) Length(WS-INVMAS-LEN) RIdfld('7135950602') | RIdfld(WS-INVMAS-KEY) END-EXEC. Description The READ command retrieves a record from a VSAM file. Its used most often witk key sequenced files but can also be used with relative record and entry sequenced files. A record in a RRDS is identified by its RRN . The field that contains the RRN must be defined as a binary full word PIC S9(8) COMP . A record in an ESDS is identified by its RBA If the specified record does not exist a NOTFND exceptional condition occurs

Maples ESM Technologies Pvt. Ltd

Page 202 of 246

CICS

Sequential Read
Sequential Read is done by Browse Operation. Establish the pointer to the First Record to be Read Using STARTBR. Next and Previous Records can be Read as required Using ReadNext and ReadPrev. End the Browse Operation at last by using ENDBR. Browse can be re-positioned by using RESETBR. During Browse Operation, Records cannot be Updated

STARTBR
EXEC CICS STARTBR FILE(filename) RIDFLD(data-area) KEYLENGTH (data value) [GENERIC] GTEQ/EQUAL LENGTH (datavalue) [RBA/RRN]

END-EXEC. Condition: AEXL AEIQ AEIM AEIS DISABLED IOERR NOTFND NOTOPEN.

READING THE RECORD AFTER STARTBR Sequentially the Next or Previous Record can be read by a READNEXT or READPREV. The first READNEXT or READPREV will read the Record where the STARTBR has positioned the File Pointer. SYNTAX FOR READNEXT/READPREV EXEC CICS READNext | READPrev FILE(name) INTO(data-area) RIDFLD(data-area) END-EXEC. Condition: AEIO AEIT AEIQ AEIV AEIM DUPKEY ENDFILE IOERR LENGERR NOTFND.

Maples ESM Technologies Pvt. Ltd

Page 203 of 246

CICS

This command is used repeatedly to read records from a file in a sequential order either forward or backward ENDBR ENDBRowse terminates a previously issued STARTBR. SYNTAX :EXEC CICS ENDBR FILE(filename) END-EXEC. Condition: AEIP INVREQ RESETBR Its effect is the same as ENDBR and then giving another STARTBR. Syntax : EXEC CICS RESETBR FILE(filename) RIDFLD(data-area) END-EXEC. Condition: AEIQ IOERR AEIM NOTFND. This command is used to reposition the browse not only by changing the contents of Ridfld but also by changing the generic GTEQ options

WRITE COMMAND Adds a new record into the File. For ESDS, RIDFLD is not used but after write execution, RBA value is returned and Record will be written at the end of the File. For KSDS, RIDFLD should be the Record Key. Record will be written depending on the Key. MASSINSERTion must be done in ascending order of the Key. SYNTAX FOR WRITE EXEC CICS WRITE FILE(filename) FROM(data-area)

Maples ESM Technologies Pvt. Ltd

Page 204 of 246

CICS

RIDFLD(data-area) [RRN / RBA ] END-EXEC. Condition: AEXL AEIN AEIQ AEIV AEIR AEIS DISABLED DUPREC IOERR LENGERR NOSPACE NOTOPEN.

Description The WRITE command writes a new record to a VSAM ESDS , RRDS or KSDS file If the WRITE command tries to write a record with a key value that is already in the file a DUPREC exceptional condition occurs. .

REWRITE COMMAND Updates a Record which is Previously Read with UPDATE Option. REWRITE automatically UNLOCKs the Record after execution. SYNTAX FOR REWRITE EXEC CICS REWRITE FILE(filename) FROM(data-area) END-EXEC. Condition: AEIN DUPREC AEIQ IOERR AEIV LENGERR AEIR NOSPACE. Description The REWRITE command Updates a Record in a file . Before you issue a REWRITE command ,you must issue a READ command with UPDATE option You cannot change the value of a primary key .

Maples ESM Technologies Pvt. Ltd

Page 205 of 246

CICS

DELETE COMMAND Deletes a Record from a dataset. Record can be deleted in two ways, RIDFLD with the full key in it and the record read with READ with UPDATE will be deleted. Multiple Records Delete is possible using Generic Option SYNTAX FOR DELETE EXEC CICS DELETE FILE(filename) RIDFLD(data-area) END-EXEC. Condition: AEXL DISABLED AEIO AEIQ AEIM AEIS DUPKEY IOERR NOTFND NOTOPEN. Optional

UNLOCK To Release the Record, which has been locked by READ with UPDATE Command Syntax :

EXEC CICS UNLOCK FILE(filename) : [other options] END-EXEC. Condition: AEXL DISABLED AEIQ IOERR AEIS NOTOPEN. GENERAL EXCEPTIONS The following Exceptions usually will occur for ALL CICS File Handling Commands. FILENOTFOUND NOTAUTH SYSIDERR INVREQ

AEY7 AEYQ AEIP

In Addition to the above, Exceptions shown along the syntax will occur.

Maples ESM Technologies Pvt. Ltd

Page 206 of 246

CICS

CICS File Handling Program


IDENTIFICATION DIVISION. PROGRAM-ID. MTRG111. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. COPY DFHAID. COPY MAP3. 01 COMMAREA. 05 VARS PIC X(4). 01 REC1. 10 KEYR PIC X(4). 10 NAMER PIC X(20). 10 ADDRESSR PIC X(20). 10 PHNOR PIC X(10). 10 DOBR PIC X(10). 10 FILLER1 PIC X(16). 77 REC-KEY PIC X(4). 77 RBAFLD PIC S9(8) COMP. 77 WS-RESP PIC S9(8) COMP. 77 W-TEXT PIC X(27). LINKAGE SECTION. 01 DFHCOMMAREA. 05 VARS PIC X(4). PROCEDURE DIVISION. MAIN-PROC. IF EIBCALEN = 0 THEN MOVE LOW-VALUES TO HEADERO. IF EIBCALEN NOT = 0 THEN PERFORM RECEIVE-MAP. PERFORM SEND-MAP. PERFORM RETURN-TRANS. SEND-MAP. EXEC CICS SEND MAPSET('MAP011') MAP('HEADER') FROM(HEADERO) ERASE END-EXEC. RECEIVE-MAP. EXEC CICS ECEIVE MAPSET('MAP011') MAP('HEADER') INTO(HEADERI) END-EXEC. EVALUATE EIBAID WHEN DFHPF1 PERFORM ADD-PARA WHEN DFHPF2 PERFORM DELETE-PARA WHEN DFHPF3 PERFORM UPDATE-PARA WHEN DFHPF4 PERFORM VIEW-PARA THRU NEXTPARA WHEN DFHPF5 PERFORM CLEAR-PARA WHEN DFHPF9 PERFORM RETURN-PARA WHEN OTHER PERFORM ERROR-PARA END-EVALUATE. ERROR-PARA. MOVE "PRESS VALID KEY!!" TO MSGO. CLEAR-PARA.

Maples ESM Technologies Pvt. Ltd

Page 207 of 246

CICS

MOVE LOW-VALUES TO HEADERO. VIEW-PARA. MOVE 0 TO RBAFLD. MOVE CODEI TO REC-KEY. EXEC CICS STARTBR FILE("MTRGF011") RIDFLD(RBAFLD) EQUAL RBA END-EXEC. NEXTPARA. EXEC CICS READNEXT FILE("MTRGF011") INTO(REC1) RIDFLD(RBAFLD) RESP(WS-RESP) RBA END-EXEC. IF WS-RESP = DFHRESP(NORMAL) IF KEYR = REC-KEY MOVE KEYR TO CODEO MOVE NAMER TO NAMEO MOVE ADDRESSR TO ADDRO MOVE PHNOR TO PHO MOVE DOBR TO DOBO MOVE "RECORD READ SUCCESSFULLY !!" TO MSGO ADD 80 TO RBAFLD ELSE GO TO NEXTPARA ELSE MOVE "RECORD NOT AVAILABLE !!" TO MSGO. UPDATE-PARA. MOVE 0 TO RBAFLD. EXEC CICS READ FILE("MTRGF011") INTO(REC1) RIDFLD(RBAFLD) PDATE RESP(WS-RESP) RBA END-EXEC. IF WS-RESP = DFHRESP(NORMAL) MOVE SPACES TO REC1 MOVE NAMEI TO NAMER MOVE ADDRI TO ADDRESSR MOVE PHI TO PHNOR MOVE DOBI TO DOBR MOVE CODEI TO KEYR EXEC CICS REWRITE FILE("MTRGF011") FROM (REC1) RESP(WS-RESP) END-EXEC PERFORM CLEAR-PARA IF WS-RESP = DFHRESP(NORMAL) MOVE "RECORD UPDATED SUCCESSFULLY!" TO MSGO ELSE MOVE "RECORD NOT UPDATED SUCCESSFULLY!" TO MSGO

Maples ESM Technologies Pvt. Ltd

Page 208 of 246

CICS

END-IF ELSE MOVE "RECORD NOT AVAILABLE !! PL.CHECK!!" TO MSGO. DELETE-PARA. IF CODEI NOT = ' ' MOVE CODEI TO RBAFLD EXEC CICS DELETE FILE("MTRGF011") RIDFLD(RBAFLD) RESP(WS-RESP) RBA END-EXEC IF WS-RESP = DFHRESP(NORMAL) MOVE "RECORD DELETED SUCCESSFULLY!" TO MSGO ELSE MOVE "RECORD NOT DELETED PL. CHECK" TO MSGO END-IF ELSE MOVE "SPACE NOT ALLOWED" TO MSGO. ADD-PARA. MOVE SPACES TO REC1. MOVE NAMEI TO NAMER. MOVE ADDRI TO ADDRESSR. MOVE PHI TO PHNOR. MOVE DOBI TO DOBR. MOVE CODEI TO KEYR. EXEC CICS WRITE FILE("MTRGF011") FROM(REC1) RIDFLD(RBAFLD) LENGTH(LENGTH OF REC1) RESP(WS-RESP) RBA END-EXEC. PERFORM CLEAR-PARA IF WS-RESP = DFHRESP(NORMAL) MOVE "RECORD ADDED SUCCESSFULLY!" TO MSGO ELSE IF WS-RESP = DFHRESP(DUPREC) MOVE "DUPLICATE RECORD!" TO MSGO ELSE MOVE "RECORD NOT ADDED !! PL CHECK !!" TO MSGO. RETURN-TRANS. EXEC CICS RETURN TRANSID(EIBTRNID) COMMAREA(COMMAREA) LENGTH(LENGTH OF COMMAREA) END-EXEC. RETURN-PARA. MOVE 'THANK U !! TRY AGAIN !! ' TO W-TEXT. EXEC CICS SEND TEXT FROM(W-TEXT) ERASE END-EXEC. EXEC CICS RETURN END-EXEC. GOBACK.

Maples ESM Technologies Pvt. Ltd

Page 209 of 246

CICS

Queues
This chapter will highlight other data sets defined in CICS region itself to be handled by application programs. The different properties of such files and how they are accessed will be discussed .

Transient Data Control Introduction


Transient Data Queue (TDQ) is a queue used to store data records by a CICS application program. The Transient Data control Program (TDP) provides the capability to store and retrieve data in TDQ. It is a temporary sequential file on an auxiliary storage. Transient means passing quickly into and out of existence. A record passes into a transient data queue when you write to the queue and passes out of queue (and out of existence ) when you read it. As a result the data is truly transient in nature. Provides application programmer with a queuing facility Data can be stored/queued for subsequent internal or external processing Stored data can be routed to symbolic destinations TDQs require a DCT entry Identified by Destination id - 1 to 4 bytes

Characteristics
TDQ name and its characteristics must be defined to CICS in the Destination Control Table (DCT) before it can be referenced in an application program by TDQ commands. A TDQ is identified by a one to four character destination_identifier. New records are added to the end of the queue. TDQs must be read sequentially. Once a record is read, it cannot be read again by any task. Cannot update a record in a TDQ. TDQ can store any number of records from 1 to 32767 depending on the Trigger Level specified in the DCT entry.

Advantages
Useful for on-line printing of records in the TDQ. Length of a record can be fixed or variable. Useful mechanism known as TRIGGER is available with TDQ, by which a transaction can be initiated automatically.

TDQS
Intra-partitioned The Intra-partition TDQ is a group of sequential records (fixed or variable) which are created and retrieved by the same and/or different tasks executing within a CICS region, hence the name Intra-

Maples ESM Technologies Pvt. Ltd

Page 210 of 246

CICS

Partition. The intra-partition TDQs are kept in one VSAM file in a CICS region. The application program can access the records sequentially and the record will be logically removed from the queue after the read . Typical uses are: - ATI (Automatic Task Initiation) associated with trigger level - Message switching - Broadcasting etc Extra-partitioned The extra partition TDQ is a group of sequential records (only fixed) which interfaces between the transactions within the CICS region and the batch applications outside the CICS region. That is why it is called Extra Partition. Each extra partition TDQ is a separate physical file and it may be on disk, tape or printer. Therefore each file must be open within the CICS region when it is used by a CICS transaction. DCT specifies the initial OPEN/CLOSE file status. The Practical applications are Interface between CICS and non CICS application systems. Typical uses are: - Logging data, statistics & transaction error messages. - Create files for subsequent processing by Non-CICS / Batch programs.

Operations
Write data to a transient data queue (WRITEQ TD) Read data from a transient data queue (READQ TD) Delete an intra partition transient data queue (DELETEQ TD).

WRITEQ TD
Used to write a record in a TDQ (Destination) Syntax: EXEC CICS WRITEQ TD QUEUE(name) FROM(data-area) [LENGTH(data-value)] END-EXEC. Queue From Length Conditions: AEXL DISABLED AEIP INVREQ AEIQ IOERR AEIV LENGERR AEIR NOSPACE AEY7 NOTAUTH AEIS NOTOPEN AEYH QIDERR the name is up to four characters and defined in the DCT specifies the data area to be written specifies the length of the record to be written. Required for Variable length records

Maples ESM Technologies Pvt. Ltd

Page 211 of 246

CICS

TDQ-WRITE
This sample conversation program sends screen and rreceives data from screen using pseudo conversation sample tdq program IDENTIFICATION DIVISION. PROGRAM-ID. TDQPRG. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 W-LEN PIC S9(4) COMP. COPY MAP14. 01 COMMAREA. 02 VARS PIC X(4). 01 REC1. 10 CODER PIC X(5). 10 NAMER PIC X(20). 10 ADDRR PIC X(20). 10 PHR PIC X(10). 10 DOBR PIC X(10). LINKAGE SECTION. 01 DFHCOMMAREA. 02 VARS PIC X(4). PROCEDURE DIVISION. PERFORM MAIN-PROC 5 TIMES. MAIN-PROC. MOVE LOW-VALUES TO HEADERO. EXEC CICS SEND MAPSET('MAP011') MAP('HEADER') ERASE END-EXEC. EXEC CICS RECEIVE MAPSET('MAP011') MAP('HEADER') END-EXEC. MOVE SPACES TO REC1. MOVE CODEI TO CODER. MOVE NAMEI TO NAMER. MOVE ADDRI TO ADDRR. MOVE PHI TO PHR. MOVE DOBI TO DOBR. MOVE 65 TO W-LEN. EXEC CICS WRITEQ TD QUEUE('D011') FROM(REC1) LENGTH(W-LEN) END-EXEC. EXEC CICS SEND TEXT FROM(REC1) ACCUM ERASE END-EXEC. DISPARA. EXEC CICS SEND PAGE END-EXEC. ENDPARA. EXEC CICS RETURN END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 212 of 246

CICS

READQ TD
Reads the queue destructively - Data record not available in the queue after the read. The record read is logically deleted from the Queue Syntax: EXEC CICS READQ TD QUEUE(name) INTO(data-area) [LENGTH(data-value)] [NOSUSPEND] END-EXEC. Conditions: AEXL DISABLED AEIQ IOERR AEIP INVREQ AEIV LENGERR AEY7 NOTAUTH AEIS NOTOPEN AEYH QIDERR AEIW QZERO Nosuspend Specifies that the task suspension for the Qbusy condition should not occur and control should be returned to the next instruction in the program

TDQ-READ
Sample program to read TDQ
IDENTIFICATION DIVISION. PROGRAM-ID. TDQPRG. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 W-LEN PIC S9(4) COMP. COPY MAP14. 01 COMMAREA. 02 VARS PIC X(4). 01 REC1. 10 CODER PIC X(5). 10 NAMER PIC X(20). 10 ADDRR PIC X(20). 10 PHR PIC X(10). 10 DOBR PIC X(10). 77 AA PIC X(10) VALUE "ERROR". LINKAGE SECTION. 01 DFHCOMMAREA. 02 VARS PIC X(4). PROCEDURE DIVISION. EXEC CICS HANDLE CONDITION QZERO(ERRORPARA) END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 213 of 246

CICS

PERFORM MAIN-PROC 5 TIMES. MAIN-PROC. MOVE 65 TO W-LEN. EXEC CICS READQ TD QUEUE('D011') INTO(REC1) LENGTH(W-LEN) END-EXEC. MOVE CODER TO CODEO. MOVE NAMER TO NAMEO. MOVE ADDRR TO ADDRO. MOVE PHR TO PHO. MOVE DOBR TO DOBO. EXEC CICS SEND TEXT FROM(REC1) LENGTH(W-LEN) ACCUM END-EXEC. ENDPARA. EXEC CICS SEND PAGE END-EXEC. EXEC CICS RETURN END-EXEC. ERRORPARA. EXEC CICS SEND TEXT FROM(AA) LENGTH(10) END-EXEC. EXEC CICS RETURN END-EXEC

DELETEQ TD
Deletes all entries in the queue . An individual record cannot be deleted. Not Valid for Extra Partition TDQ Syntax: EXEC CICS DELETEQ TD QUEUE(name) END-EXEC. Conditions: INVREQ AEIP NOTAUTH AEY7 QIDERR AEYH

Destination Control Table


DCT is to register the information of all TDQs Destination Control Program (DCP) uses DCT to identify all TDQs and perform all I/O operations. DFHDCT is a macro to define intra & extra partition TDQs TYPE=INTRA/EXTRA REUSE option specified along with intra partition TDQ tells whether the space used by TDQ record will be removed & reused after it has been read.

Maples ESM Technologies Pvt. Ltd

Page 214 of 246

CICS

Automatic Task Initiation


Facility through which a CICS transaction can be initiated automatically DFHDCT TYPE=INTRA DESTID=MSGS TRANSID=MSW1 TRIGLEV=500 When the number of TDQ records reaches 500, the transaction MSW1 will be initiated automatically

Applications Message Switching


Messages can be accumulated in an Intra partition TDQ and at a certain level, a transaction can be initiated automatically through the ATI in order to route the messages.

Report Printing
Reports can be accumulated in an Intra partition TDQ and at a certain level as mentioned in the DFHDCT table , the transaction mentioned can be automatically initiated through the ATI in order to print the reports.

Transient Data Exception Conditions


IOERR LENGERR NOSPACE NOTOPEN QBUSY QIDERR QZERO An I/O error occurred and the record in error is skipped Length option not coded for variable length record No more space available on intra partition TDQ Destination is closed Application for QS only, a READQ TD command attempts to access a record in an intra partition queue that is being written to or deleted by another task. Queue name not found in DCT READQ TD is issued for an empty queue

Temporary Storage Control


Temporary Storage Queue (TSQ) is a queue used to store data records by a CICS application program. The Temporary Storage control Program (TSP) provides the capability to store and retrieve data in TSQ Provides application programmer the ability to store and retrieve data in a TSQ Application can use the TSQ like a scratch pad TSQs are Created and deleted dynamically No CICS table entry required if recovery not required

Maples ESM Technologies Pvt. Ltd

Page 215 of 246

CICS

Identified by Queue id - 1 to 8 bytes Typically a combination of termid/tranid/operid Each record in TSQ identified by relative position, called the item number The records in a TSQ can be accessed by any CICS program executing in the same CICS region only

Advantages
The length of an item (record) can be fixed or variable CICS will automatically assign a unique item number sequentially to each record written , which will be used later for retrieval The items in a queue can be read randomly or sequentially or can be updated any number of times The entire queue can be deleted when no longer needed by the application program but individual records cannot be deleted A queue can be created either in the main storage or in the auxiliary storage on a DASD In Main Storage accessing is faster but no recovery is possible On an Auxiliary storage i.e. an external VSAM data set (DFHTEMP) which is available to the application program always

TSQS Operations
Write and Update data Read data - Sequential and random Delete the queue

Access
Across transactions Across terminals

Storage
Main - Non-recoverable Auxiliary - Recoverable TST entry required, VSAM file DFHTEMP

Maples ESM Technologies Pvt. Ltd

Page 216 of 246

CICS

TSQS TYPICAL USES


Data passing among transactions Terminal Paging Report printing

WRITEQ TS
Syntax: EXEC CICS WRITEQ TS QUEUE(name) FROM(data-area) [LENGTH(data-value)] ITEM(data-area) [REWRITE] ] [MAIN|AUXILIARY] [NOSUSPEND] END-EXEC. Conditions: AEIZ AEIV AEY7 AEYQ AEIQ AEIP AEIR ITEM ITEMERR LENGERR NOTAUTH SYSIDERR IOERR INVREQ NOSPACE specifies a half word binary field of PIC S9(4) Comp. The initial contents of ITEM is ignored, CICS returns the item number after completion of the write command. If REWRITE option is specified the item field is to be set to the item number to be replaced. specifies that the item is to be written in an area of main storage specifies that the item is to be written to a VSAM file. This is the default.

MAIN AUXILIARY

This sample conversation program sends screen and receives data from screen using pseudo conversation sample TSQ program IDENTIFICATION DIVISION. PROGRAM-ID. TSQPRG. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 W-ITEM PIC S9(4) COMP. COPY MAP14. 01 COMMAREA. 02 VARS PIC X(4). 01 REC1. 10 CODER PIC X(4). 10 NAMER PIC X(20).

Maples ESM Technologies Pvt. Ltd

Page 217 of 246

CICS

10 ADDRR PIC X(20). 10 PHR PIC X(10). 10 DOBR PIC X(10). 10 FILLER1 PIC X(16). LINKAGE SECTION. 01 DFHCOMMAREA. 02 VARS PIC X(4). PROCEDURE DIVISION. MAIN-PROC. MOVE LOW-VALUES TO HEADERO. IF EIBCALEN = 0 THEN PERFORM SEND-MAP PERFORM RETURN-TRANS. IF EIBCALEN NOT = 0 THEN PERFORM RECEIVE-MAP PERFORM TRANS-END. SEND-MAP. MOVE LOW-VALUES TO HEADERO. EXEC CICS SEND MAPSET('MAP011') MAP('HEADER') ERASE END-EXEC. RECEIVE-MAP. EXEC CICS RECEIVE MAPSET('MAP011') MAP('HEADER') END-EXEC. MOVE SPACES TO REC1. MOVE CODEI TO CODER. MOVE NAMEI TO NAMER. MOVE ADDRI TO ADDRR. MOVE PHI TO PHR. MOVE DOBI TO DOBR. INSPECT REC1 REPLACING ALL '_' BY ' ' EXEC CICS WRITEQ TS QUEUE('MTRGQ011') FROM (REC1) ITEM(W-ITEM) END-EXEC. EXEC CICS SEND TEXT FROM(REC1) END-EXEC. RETURN-TRANS. MOVE "COMM" TO VARS OF COMMAREA. EXEC CICS RETURN TRANSID(EIBTRNID) COMMAREA(COMMAREA) LENGTH(LENGTH OF COMMAREA) END-EXEC. TRANS-END. EXEC CICS DELETEQ TS QUEUE('MTRGQ011') END-EXEC. EXEC CICS RETURN END-EXEC. GOBACK.

Maples ESM Technologies Pvt. Ltd

Page 218 of 246

CICS

READQ TS
Syntax: EXEC CICS READQ TS QUEUE(name) {INTO(data-area) | SET(ptr-ref) } LENGTH(data-value) [NUMITEMS(data-area)] [ITEM(data-area) | NEXT ] END-EXEC. Conditions: AEIZ AEIV AEYH AEY7 AEYQ AEIQ AEIP ITEM NEXT ITEMERR LENGERR QIDERR NOTAUTH SYSIDERR IOERR INVREQ specifies the item number to be read specifies that the next sequential logical item in the queue is to be read any task can affect the positioning of a READQ TS NEXT command by issuing a READQ TS command for the same queue NUMITEMS specifies half word binary field of PIC S9(4) COMP CICS places the total number of items in the queue in the field

DELETEQ TS
Deletes all entries in the queue Space used by the queue is released

Syntax: EXEC CICS DELETEQ TS QUEUE(name) END-EXEC. Conditions: AEIP AEY7 AEYH AEYQ INVREQ NOTAUTH QIDERR SYSIDERR

Note: Since TS is the default in the command format, TS can be omitted.

Maples ESM Technologies Pvt. Ltd

Page 219 of 246

CICS

The READQ command does not hold exclusive control over TSQ as there is no update option in the READQ command . Therefore if a TSQ is shared by other transactions, it is the programmers responsibility to establish exclusive control over the TSQ during update. In this case one must use the ENQ command before the READQ in order to gain exclusive control over the record. After the updation by REWRITE command use the DEQ command to release the exclusive control. Example EXEC CICS ENQ RESOURCE(TSQ-QID) The resource is reserved END-EXEC. EXEC CICS READQ QUEUE(TSQ-QID) END-EXEC. The TSQ is read for update

Procedure to update the contents of TSQ

EXEC CICS WRITEQ QUEUE(TSQ-QID) REWRITE END-EXEC. EXEC CICS DEQ RESOURCE(TSQ-QID) The resource is released. END-EXEC.

Maples ESM Technologies Pvt. Ltd

Page 220 of 246

CICS

Communication with Databases


CICS-DB2
CICS provides interface to DB2. DB2 requires CICS Attachment Facility to connect itself to CICS CICS programs can issue commands for SQL services in order to access the DB2 database. EXEC SQL function [options] END-EXEC

DB2 DATABASE ACCESS BY CICS


Operating System

CICS Region App. Pgm. EXEC SQL

DB2 Region CICS Attachment Facility

DB2 Database

RCT ENTRY
The CICS-to-DB2 connection is defined by creating and assembling the resource control table (RCT) The information in RCT is used to control the interactions between CICS & DB2 resources DB2 attachment facility provides a macro (DSNCRCT) to generate the RCT. The RCT must be link-edited into a library that is accessible to MVS

Maples ESM Technologies Pvt. Ltd

Page 221 of 246

CICS

DB2 PRECOMPILER
Source Program (EXEC SQL... | EXEC CICS...) DB2 Precompiler | CICS command translator | Compile By COBOL | Linkedit by Linkage editor | Load Module

Sample program that illustrates CICS & DB2 connectivity code


IDENTIFICATION DIVISION. PROGRAM-ID. MTRGP005. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. COPY DFHAID. COPY MAP7. EXEC SQL DECLARE EMPDET TABLE ( DEPTNO SMALLINT, DESC VARCHAR(25) ) END-EXEC. 01 DCLEMPDET. 10 DEPTNO PIC S9(4) USAGE COMP. 10 DESC. 49 DESC-LEN PIC S9(4) USAGE COMP. 49 DESC-TEXT PIC X(25). 01 COMMAREA. 05 VARS PIC X(4). 01 REC1. 02 CODER PIC S9(4) COMP. 02 DESCR PIC X(25). EXEC SQL INCLUDE SQLCA END-EXEC. 77 WS-RESP PIC S9(8) COMP. 77 W-TEXT PIC X(27). LINKAGE SECTION. 01 DFHCOMMAREA. 05 VARS PIC X(4). PROCEDURE DIVISION. MAIN-PROC. IF EIBCALEN NOT = 0 THEN PERFORM RECEIVE-MAP. PERFORM SEND-MAP PERFORM RETURN-TRANS. SEND-MAP. IF EIBCALEN = 0 THEN MOVE LOW-VALUES TO HEADERO. EXEC CICS SEND MAPSET('MAP005') MAP('HEADER') FROM(HEADERO)

Maples ESM Technologies Pvt. Ltd

Page 222 of 246

CICS

ERASE END-EXEC. RECEIVE-MAP. EXEC CICS RECEIVE MAPSET('MAP005') MAP('HEADER') INTO(HEADERI) END-EXEC. EVALUATE EIBAID WHEN DFHPF1 PERFORM ADD-PARA WHEN DFHPF2 PERFORM DELETE-PARA WHEN DFHPF3 PERFORM UPDATE-PARA WHEN DFHPF4 PERFORM VIEW-PARA WHEN DFHPF5 PERFORM CLEAR-PARA WHEN DFHPF9 PERFORM RETURN-PARA WHEN OTHER PERFORM ERROR-PARA END-EVALUATE. ERROR-PARA. MOVE "PRESS VALID KEY !!" TO MSGO. CLEAR-PARA. MOVE LOW-VALUES TO HEADERO. VIEW-PARA. MOVE SPACES TO REC1. MOVE CODEI TO DEPTNO. EXEC SQL SELECT DEPTNO,DESC INTO :DEPTNO,:DESC FROM EMPDET WHERE DEPTNO=:DEPTNO END-EXEC. IF SQLCODE = 0 MOVE DEPTNO TO CODEO MOVE DESC-TEXT TO DESCO MOVE "RECORD READ SUCCESSFULLY !!" TO MSGO ELSE MOVE "RECORD NOT AVAILABLE !!" TO MSGO. UPDATE-PARA. MOVE SPACES TO REC1. MOVE CODEI TO DEPTNO. MOVE DESCI TO DESCR. EXEC SQL SELECT DEPTNO,DESC INTO :DEPTNO,:DESC FROM EMPDET WHERE DEPTNO=:DEPTNO END-EXEC. IF SQLCODE = 0 EXEC SQL UPDATE EMPDET SET DESC = :DESCR WHERE DEPTNO=:DEPTNO END-EXEC. IF SQLCODE = 0 MOVE "RECORD UPDATED SUCCESSFULLY!" TO MSGO ELSE MOVE "RECORD NOT UPDATED SUCCESSFULLY!" TO MSGO. DELETE-PARA. MOVE SPACES TO REC1. MOVE CODEI TO DEPTNO. IF CODEI NOT = ' ' EXEC SQL DELETE FROM EMPDET WHERE DEPTNO=:DEPTNO

Maples ESM Technologies Pvt. Ltd

Page 223 of 246

CICS

END-EXEC. IF SQLCODE = 0 MOVE "RECORD DELETED SUCCESSFULLY!" TO MSGO ELSE MOVE "ERROR WHILE DELETION PL. CHECK" TO MSGO. ADD-PARA. MOVE SPACES TO REC1. MOVE CODEI TO CODER. MOVE DESCI TO DESCR. EXEC SQL INSERT INTO EMPDET VALUES(:CODER,:DESCR) END-EXEC. IF SQLCODE = 0 MOVE "RECORD ADDED SUCCESSFULLY!" TO MSGO ELSE MOVE "RECORD NOT ADDED !! PL CHECK !!" TO MSGO. RETURN-TRANS. EXEC CICS RETURN TRANSID(EIBTRNID) COMMAREA(COMMAREA) LENGTH(LENGTH OF COMMAREA) END-EXEC. RETURN-PARA. MOVE 'THANK U !! TRY AGAIN !! ' TO W-TEXT EXEC CICS SEND TEXT FROM(W-TEXT) ERASE END-EXEC. EXEC CICS RETURN END-EXEC. GOBACK.

JCL used to submit CICS & DB2 Program


//MTRG005R JOB ,,NOTIFY=&SYSUID,TIME=(,2) // JCLLIB ORDER=(MTRG005.CICS.DB2) //STEP01 EXEC DFHDSN,MEM=MTRGP005,WSPC=500 //TRN.SYSIN DD DISP=SHR,DSN=MTRG005.CICS.DB2(&MEM) //PC.DBRMLIB DD DISP=SHR,DSN=MTRG005.DBRMLIB.DATA(&MEM) //COB.SYSLIB DD DSN=MTRG005.CICS.MAP(MAP7),DISP=SHR //LKED.SYSLMOD DD DISP=SHR,DSN=CICSTS13.MTRG.PRGLOAD(&MEM) //LKED.SYSIN DD * INCLUDE SYSLIB(DSNCLI) NAME MTRGP005(R) /* //* //BIND EXEC PGM=IKJEFT01,DYNAMNBR=20,COND=(4,LT) //STEPLIB DD DISP=SHR,DSN=DSN610.SDSNLOAD //SYSTSPRT DD SYSOUT=(*) //SYSTSIN DD * DSN SYSTEM(DBA1) BIND PLAN(MTRGP005) MEMBER(MTRGP005) VALIDATE(BIND) ISOLATION(CS) RELEASE(C) EXPLAIN(NO)-

Maples ESM Technologies Pvt. Ltd

Page 224 of 246

CICS

OWNER(MTRG005)LIB('MTRG005.DBRMLIB.DATA') /* //

Other Interval Control Commands


START Used to start a transaction at the specified terminal and at the specified time or interval Data can be passed to the new transaction Syntax: EXEC CICS START TRANSID(transid) [TERMID(termid) [FROM (data area)] TIME(hhmmss) | INTERVAL(hhmmss) ] [LENGTH(data value)][RTRANSID(name)] [RTERMID(name)][QUEUE(name)] END-EXEC Conditions: INVREQ, LENGERR, TERMIDERR, TRANSIDERR TRANSID TERMID FROM TIME /INTERVAL LENGTH RTRANSID RTERMID QUEUE POST WAIT EVENT RETRIEVE CANCEL specifies the transaction identifier of the task to be initiated specifies terminal identifier to which the task will be associated specifies the data to be passed to the started task start the transaction at the specified time or after the time interval specifies the length of the data passed specifies the transaction identifier to be passed to the started task probably for subsequent START command specifies the terminal identifier to be passed to the started task probably for subsequent START command specifies an eight character name of a TSQ to be passed to the started task. The new transaction may access the queue. to request notification when the specified time has expired. to wait for an event to occur. used to retrieve the data passed by the START used to cancel the Interval Control requests. Example: DELAY, POST and START identified by REQID.

Post / Wait Event


Issue a POST command to request notification when the specified has expired. The POST command creates a four bytes Timer Event Control Block that expired when the specified time interval has elapsed. Issue a WAIT EVENT command to suspend a task until the posted event expired. The WAIT EVENT command checks ECB set by the POST command for time expiration. When the time has expired, control will be given to the statement after the WAIT EVENT command.

Maples ESM Technologies Pvt. Ltd

Page 225 of 246

CICS

These two commands are used as pair, as an alternative to the DELAY command The general command format is EXEC CICS POST {INTERVAL(hhmmss)/INTERVAL/TIME(hhmmss)} SET (pointer-ref) {REQID(name)} END-EXEC. SET specifies a full word binary field of PICS9(8) comp. into which CICS places the address of the Timer Event Control area. REQID specifies a one to eight character request identifier that is associated with the Timer. Event Control Area if omitted, CICS generates a unique request identifier and places it in the EIBREQID field in he EIB. EXEC CICS WAIT EVENT ECADDR(pointer-value) END-EXEC. ECADDR specifies a full word binary field of PIC s9(8) comp. that contains the address of the timer Event Control Area that must expire before the task must continue. This value can be obtained from the SET of the POST command that created the Timer Event Control Area.

Retrieve
Used in the started transaction to retrieve the data passed to it by the START command. Terminal tasks may issue consecutive RETRIEVE commands. The general command format is EXEC CICS RETRIEVE {INTO(data area)/SET(pointer-ref)} (LENGTH(data-value)) {RTRANSID(data area)} {RETERMID(data area)} {QUEUE(data area)} {WAIT} END-EXEC. INTO: Specifies the data area into which the data specified in the from option of the START command will be placed. LENGTH: Specifies the length of the retrieved data. When INTO option is specified this field indicates the maximum length that can be retrieved. If the input data exceeds this length, it is truncated and the LENGERR condition is raised. CICS updates this field with the actual length of retrieved data.

Maples ESM Technologies Pvt. Ltd

Page 226 of 246

CICS

RTRANSID/RETERMID/QUEUE: Specifies an area into which the data specified in the respective options of the START command is placed. WAIT: Specifies that if, all expired data has been retrieved ,the task is to be suspended until further expired data becomes available. If this option is omitted ,the ENDDATA exceptional condition occurs when no more data exists.

CANCEL:
Used to cancel a DELAY,POST,OR START command which has been previously issued. The commands to be cancelled are identified by a request identifier (REQID) parameter. The general format is EXEC CICS CANCEL {REQID(name)} {TRANSID(name)} {SYSID(NAME)} END-EXEC. REQID: Specifies the request identifier that was associated with the command to be cancelled. Not required for canceling a POST command issued earlier in the same task required, when both TRANSID and SYSID options are specified.

RECOVERY & RESTART


THE NEED FOR RECOVERY/RESTART The possible failures that can occur outside the CICS system are Communication failures (in online systems) Data set or database failures Application or system program failures Processor failures & Power supply failures.

Recovery/Restart facilities are required to minimize or if possible, eliminate the damage done to the online system, in case of the above failures to maintain the system & data integrity.

RECOVERY
An attempt to come back to where the CICS system or the transaction was when the failure occurred

Maples ESM Technologies Pvt. Ltd

Page 227 of 246

CICS

Recoverable Resources VSAM files Intrapartition TDQ TSQ in the auxiliary storage DATA tables Resource definitions & System definition files

RESTART
To resume the operation of the CICS system or the transaction when the recovery is completed FACILITIES FOR RECOVERY / RESTART Facilities for CICS Recovery / Restart Dynamic Transaction Backout Automatic Transaction Restart Resource Recovery Using System Log Resource Recovery Using Journal System Restart Extended Recovery Facility (XRF)

Dynamic Transaction Backout (DTB)


When the transaction fails, backing out the changes made by the transaction while the rest of the CICS system continues normally is called DTB CICS automatically writes the before image information of the record into the dynamic log for the duration of one LUW ,the work between the two consecutive SYNC points When an ABEND occurs, CICS automatically recovers all recoverable resources using the info. in dynamic log (Set DTB=YES in PCT)

LUW & SYNC POINT


The period between the start of a particular set of changes and the point at which they are complete is called a logical unit of work- LUW The end of a logical unit of work is indicated to CICS by a synchronization point (sync pt). Intermediate SYNC pt. can be done by

Maples ESM Technologies Pvt. Ltd

Page 228 of 246

CICS

Syntax : EXEC CICS SYNCPOINT [ROLLBACK] END-EXEC LUWS & SYNC POINTS |- - - - - - - - - - - - LUW - - - - - - - - - | Task A|---------------------------------------------| SOT EOT-SP |- - - LUW- - |- - - LUW- - |- - -LUW- - | Task B|---------------->--------------->--------------| SOT SP SP EOT-SP When the failure occurs, changes made within the abending LUW will be backed out.

Automatic Transaction Restart


CICS capability to automatically restart a transaction after all resources are recovered through DTB If the transaction requires automatic restart facility, Set RESTART=YES in PCT Care should be taken in order to restart the task at the point where DTB completes in the case of intermediate SYNC point

Extended Recovery Facility - XRF


XRF is to increase the availability of CICS by automating the fast recovery of CICS resources There are two systems with same configuration All the resources are shared by the two systems If the failure occurs in one system, the other system will continue The system downtime can be reduced to few minutes if XRF is used

CICS Supplied Transactions CESN Transactions


End Users wishing to begin an on-line session will first identify themselves to CICS by sign-on option Enables CICS to associate user with terminal Necessitates Name and Password to be defined in the SIGN-ON TABLE To sign on to CICS system

Maples ESM Technologies Pvt. Ltd

Page 229 of 246

CICS

CESN[USERID=userid][,PS=password] [,NEWPS=newpassword][,LANGUAGE=l] Userid & password values can be from 1-8 chars. In RACF, the Userid given in CESN is verified. NEWPS to change the password and LANGUAGE to choose national language Sign off by CESF which breaks the connection between the user and CICS If the Sign on is done twice for the same userid at the terminal, the previous operator will be signed off

CECI - Command Level Interpreter


Invokes command level interpreter. Allows to enter CICS commands , checks its syntax To build and test the effect of EXEC CICS commands CECI ASSIGN is used to get the current userid,sysid, terminal id, application id etc.. Before using the maps in programs, it can be tested using CECI to check how it appears on the screen. CECI gives the complete command syntax of the specified command. CECI READQ TD QUEUE(TESTL001) will read the current record of the given TDQ

CEMT - Master Terminal Transaction


Helps inquire about the status of specified resources Helps set a status of a resource CEMT provides the following services Displays the status of CICS & system resources Alter the status of CICS & system resources Remove the installed resource definitions Perform few functions that are not related to resources

CEDF - Execution Diagnostic Facility


Allows to test Command level application program Intercepts execution of the application program at every CICS command and displays information about the arguments. To test command level application programs interactively CEDF [termid/sysid/sessionid] [,ON/,OFF] Termid - the identifier of the terminal on which the transaction to be tested is being run

Maples ESM Technologies Pvt. Ltd

Page 230 of 246

CICS

Sessionid - to test/monitor a transaction attached across an MRO/ISC session Sysid - to test a transaction across an APPC session The points at which EDF interrupts execution of the program and sends a display to the terminal At transaction initialization, after EIB has been initialized and before the app. pgm given control Start of execution of each CICS command (argument values can be changed at this point) End of execution of each CICS command and before the Handle condition mechanism is invoked (response code values can be changed) At program termination & at normal task termination When an ABEND occurs & at abnormal task termination. EIB values can be changed & CEBR can be invoked

CEBR - Temporary Storage Browse


Displays the contents of a TSQ. Allows to Browse copy or purge TSQ and intra partition TDQ To browse the contents of CICS temporary storage queues (TSQ) CEBR by default will show the queue associated with the current terminal CEBRL001 which can be overridden to view any other queue TERM to browse TSQ for another terminal QUEUE to make the named queue, current PUT to copy the current queue contents into TDQ GET to fetch TDQ for browsing PURGE erases the contents of the current queue

CESF - CICS supplied sign-off transaction


The primary function of CICS sign-off is to terminate CICS user-id from CICS in terms of security

Processing Program Table (PPT)


One PPT entry can be defined using an Assembler macro DFHPPT DFHPPT TYPE=ENTRY PROGRAM |MAPSET= name [PGMLANG= ASM|COBOL|PLI] [RES= NO|FIX|YES] : : other options DFHPPT TYPE=ENTRY,PROGRAM=TEST, PGMLANG=COBOL DFHPPT TYPE =ENTRY,MAPSET=MSBINQ

Maples ESM Technologies Pvt. Ltd

Page 231 of 246

CICS

Program or Mapset is used to specify the name of the application program ( 1-8 characters) or name of the mapset ( 1-7 characters)respectively Pgmlang is used to specify the programming language Res indicates the residency status of the program If not mentioned NO is assumed and the program will be fetched only at the first execution time If YES is specified the program will be resident in ( virtual storage) If FIX is specified the program will be placed in the real storage

Program Control Table (PCT)


DFHPCT TYPE=ENTRY TRANSID= name PROGRAM=name TASKREQ=pf6 DTIMOUT=mmss RTIMOUT=mmss RESTART=NO/YES Transid Program Taskreq Dtimout Rtimout Restart defines the transaction identifier as specified in PPT indicates the PF or PA function keys to initiate the transaction length of timeout for the transaction deadlock case length of time out for the terminal response indicates whether automatic restart is to be applied after abnormal termination

Program Preparation Introduction


Preparing a Program to run in CICS Environment. Defining the Program in the CICS Region. Executing the Program.

Preparing a Program
CICS requires the following steps to prepare a Program. Translating the Program. Assemble or Compile the Translator Output. & Link the Program.

Maples ESM Technologies Pvt. Ltd

Page 232 of 246

CICS

Translation
Translates the EXEC CICS Statements into the Statements your Language (COBOL) Compiler can understand. The Translator gives two outputs, a Program Listing as SYSPRINT and a Translated Source in SYSPUNCH. The SYSPUNCH is given as the input to the Program Compiler. If any Copy Books are used in the Program, there should not be any CICS Statements in the Copy Book.

Compiling or Linkage
As the CICS Commands have been translated, The Compilation of the CICS Program is the same as Language Program. Hence, the Compiler Options can be specified as required.

Defining the Program


The Application should be defined and Installed into the PPT. This can be done either by using CEDA Trans. or DFHPPT.

Screen Definition Facility SDF - II Introduction - SDF


An interactive tool for defining information to be displayed on the screen Objects created by SDF are used by various systems like CICS/BMS, IMS, ISPF etc.. The SDF objects are Panel and Panel Groups (etc..) corresponding to map and mapset in CICS/BMS

SDF FUNCTIONS
Creation of objects which is common for all the systems Provides functions to alter and test the objects Generation function to create code for the objects like macro codes for CICS/BMS Provides utilities to print, migrate & convert objects Provides functions to develop application prototypes

Maples ESM Technologies Pvt. Ltd

Page 233 of 246

CICS

PANEL COMMANDS
SDF has panel commands like TOP BOTTOM UP DOWN , to browse through the the panels PRESERVE to protect the panel AUTOSAVE to set the automatic save option on commands SAVE to record the changes and CANCEL/CCANCEL to quit the changes TEST to test the appearance of the object Commands are available to edit the panels... like to create, alter & view the fields and its attributes E.g. ATTRIBUTE, EDIT, SHOW, HIDE etc.

PANEL & LINE COMMANDS


SDF has got panel commands to do the following. To browse through the panel To quit/save the changes To protect the panel and to restore the panel in case or errors To test the appearance of the panel Panel editor commands to create, alter & view the fields and its attributes And Line commands to copy, move, delete, repeat & insert lines

PANELS
To create a panel, Enter a existing panel which is to be used as a skeleton for the new panel OR Enter a device type Panel text can be defined by typing the text in the required panel position in format mode. Variable fields can be defined by variable field marks and arrays can be defined by specifying a dimension and direction. Variable fields can be defined by variable field marks A panel can be included in another panel with few restrictions Default attributes are assigned to fields which can be changed. E.g. for attributes are, Color, protection, intensity, cursor position, justify, field format, field validation, modified data flag, etc. To change the panel, Enter the panel name and library identifier where the panel resides

Maples ESM Technologies Pvt. Ltd

Page 234 of 246

CICS

PANEL GROUPS
A panel group contains information about a group of panels, and the names of the panels that belong to the panel group. Procedure of Creating and editing panel group is same as panel Define the global parameters of the panel group thru Panel Group Characteristics opt. E.g. BMS characteristics like generation name (later used in generation) & logical device code etc.

GENERATION
As SDF objects are stored in internal rep. they have to be generated to be used in applications Output of generation , depends on the object type Panel => Map Panel group => Mapset One or more data structures(used in Cobol) or control blocks (BMS macros) can be generated

SDF LIBRARIES
Define libraries(created in ISPF) to be used by SDF II to store and retrieve objects SDF II library is a partitioned data set with a three-level dataset name (project.group.dgipnl) Only the first two levels can be defined & third level added by sdf depends on the object type DGIPNL-for panels, DGIGRP-for panel groups and DGIPST-for partition sets 'ID' is assigned for each library which is used to search the objects in the library Password can be given to protect the library.

SDF UTILITIES
Print: The print utility produces printouts of panels, panel groups, partition sets etc. Migration: To Migrate objects from various sources into SDF libraries. Example- Maps, map sets & partition sets defined with CICS/BMS macros Conversion Utility: To convert objects from one target system to a new target system.

Maples ESM Technologies Pvt. Ltd

Page 235 of 246

CICS

Test Yourself:
1. For data fields that should not be entered or cleared you can use what characteristic? A. Unprotected. B. Normal. C. Initial Value. D. Autoskip. 2. Which two entries are usually found in the linkage section? A. Execute Interface Block/Transaction Work Area. B. Symbolic Maps/DFATTRBS. C. DFHEIV11 / Communication Area. D. Dfhcommarea/Execute Interfaced Block. 3. Which of the following CICS Tables utilizes trans IDs? A. TCT. B. PCT. C. RCT. D. PPT. 4. Which of the following is the correct syntax for reading a record from a temporary storage queue? A. Read TSQ. B. ReadTSQ. C. ReadQue TS. D. ReadQ TS. 5. The XCTL command transfers control from one program to another at the same: A. storage address. B. logical level. C. higher level. D. lower level. 6. For what is the CEDF transaction used? A. task management. B. files and DASD control. C. CICS data facility manager. D. Debugging programs 7. On which type of file would you use readprev? A. Vsam. B. Qsam. C. IMS. D. Bdam. 8. Which are the correct ways to initiate CICS tasks? A. Automatic Task Initiation/Exec CICS Start. B. CALL Statement/Receivable Map/Send Map. C. Permanent Transaction ID/Temporary Transaction ID. D. PA Key/XCTL Statement/Interval Control Transaction ID 9. The cursor can be controlled by using a special one byte field called: A. stopper field. B. jump field. C. shift field. D. tag field. 10. If the program uses other keys besides "enter" to control logic, a copy of ___________ should be used in working storage of program. A. ebaid. B. dfhaid. C. dfhbmsca. D. dfheivar

Maples ESM Technologies Pvt. Ltd

Page 236 of 246

CICS

CICS Lab Exercise


Day 1

1. Write a simple COBOL program that receives the transaction id along with some message and send same message as reply. 2. Write a simple COBOL program that receives the transaction id along with Two Numbers and find the sum of two numbers and send it back. 3. Write a COBOL program that receives the transaction id along with Two Numbers and an arithmetic operator, based on operator perform the operation and send the same back to terminal.

Day 2

4. Try the above program along with Handle Condition. 5. Try the above arithmetic program with PF keys. 6. Make use of RESP in the above cases

Day 3

7. Design a map with Employee details with EmpNo, Name, Designation and Salary. Generate the Physical and Symbolic map. 8. Write Cobol program that accept the values from map and give response message. 9. Design a map with like calculator. 10. Write the Cobol program for the above to accept value and operator result to be displayed to the map.

Day 4

11. Write a program to display the KSDS file content to the terminal with out map. 12. Try the above program with map. 13. Design a map with fields of KSDS file and option for Read, Write, Search and Delete, Update. 14. Write the application program to perform the above manipulation. 15. Try to perform the same with ESDS and RRDS file.

Maples ESM Technologies Pvt. Ltd

Page 237 of 246

CICS

Day 5

16. Write a Pseudo conversation program to send the Menu Employee map. 17. Write a Pseudo conversational COBOL program to send the Emp Map generated and Receive the Employee Data. 18. Write CICS-COBOL program to create a TSQ, insert records into the TSQ from the Employee file.

Day 6

19. Write CICS-COBOL program to create a TDQ, insert records into the TDQ from the Employee file. Try to get the record from TDQ in CICS region. 20. Write a COBOL program for Random retrieval from TSQ.

Day 7

21. Create Employee Table in DB2 22. Use the same employee map for employee details entry 23. Write CICS-DB2-COBOL program to insert,search,edit and delete records into the Employee table.

Maples ESM Technologies Pvt. Ltd

Page 238 of 246

CICS

Common Abend Codes


When a task abends, a four character, abend code is returned by CICS to indicate the cause of the abend and in many situations this code alone provides enough information to debug the problem that caused the abend. The most commonly used abend codes are provided in the following list. CODE AEIA AEID AEIE AEIK AEIM AEIN AEIO AEIP AEIQ AEIR AEIS AEIT AEIV AEIW AEIZ AEI0 AEI1 AEI2 AEI3 AEI8 AEI9 AEXL AEYH AEYQ AEY7 AEY9 CONDITION ERROR EOF EODS TERMIDERR NOTFND DUPREC DUPKEY INVREQ IOERR NOSPACE NOTOPEN ENDFILE LENGERR QZERO ITEMERR PGMIDERR TRANSIDERR ENDDATA INVTSREQ TSIOERR MAPFAIL DISABLED QIDERR SYSIDERR NOTAUTH UNSUPPORTED

Maples ESM Technologies Pvt. Ltd

Page 239 of 246

CICS

CICS
ABEND ADDRESS ALLOCATE ASKTIME ASSIGN CANCEL

Commands Summary
To terminate a task abnormally To access CICS system area To acquire a session To request the current time of the day To obtain CICS system values To cancel previous interval control command To initiate a process To converse ( send & receive ) with terminal or LU To suspend the processing of a task To delete records To delete all records from an Intra-Partition TDQ To delete the TSQ To release exclusive control from a resource To dump main storage area To end a browse operation To acquire exclusive control over a resource To create a user trace entry To select format of date and time To release main storage To acquire main storage To intercept an abnormal termination of task To intercept attention identifier keys To intercept exceptional conditions To ignore exceptional conditions

CONNECT PROCESS CONVERSE DELAY DELETE DELETEQ TD DELETEQ TS DEQ DUMP ENDBR ENQ ENTER FORMATTIME FREEMAIN GETMAIN HANDLE ABEND HANDLE AID HANDLE CONDITION IGNORE CONDITION

Maples ESM Technologies Pvt. Ltd

Page 240 of 246

CICS

ISSUE COPY ISSUE PRINT JOURNAL LINK LOAD POP HANDLE POST PURGE MESSAGE PUSH HANDLE READ READNEXT READPREV READQ TD READQ TS RECEIVE RECEIVE MAP RELEASE RESTBR RETRIEVE RETURN REWRITE ROUTE SEND SEND CONTROL SEND MAP

To copy screen image To print a hard copy of the screen image To create a journal record To pass control to a program expecting return To load a program , table or mapset To reinstate HANDLE commands To post time expiration To delete a logical message To suspend HANDLE condition To read a record To read a record sequentially forward To read a record sequentially backward To read a record from a TDQ To read a record from a TSQ To receive data from terminal or LU To receive mapped input data To delete a loaded program To reset the start of a browse operation To retrieve data passes by START command To return control To rewrite a record To route messages to terminal To send data to a terminal To send terminal control orders To send mapped output data

Maples ESM Technologies Pvt. Ltd

Page 241 of 246

CICS

SEND PAGE SEND TEXT START STARTBR SUSPEND SYNCPOINT UNLOCK WRITE WRITEQ TD WRITEQ TS XCTL

To send a logical message To send text without mapping To initiate a transaction To start a browse operation To suspend the execution of a task To establish a sync point To release exclusive control To write a record To write a record into a TDQ To write a record into a TSQ To transfer control to another program

Maples ESM Technologies Pvt. Ltd

Page 242 of 246

CICS

Glossary
ABEND AID Abnormal end of online task or batch job. Attention Identifier. Terminal key which causes device interrupt to transmit data to the host computer. CEDF CICS Execute Diagnostic Facility. An IBM program product which works under CICS for interactive execution and debugging of CICS application programs. CEMT CESF CICS supplied Master terminal transaction CICS supplied sign-off transaction. This terminates a CICS session. CESN CWA CICS supplied sign-on transaction. Common Work Area . a common work area in CICS whose size is defined in the System Initialization Table DCT Destination Control Table. This registers all Transient Data Queues (TDQ) DFOC Dynamic File Open/Close . A technique by which files in a CICS region can be dynamically Opened or Closed from a CICS

application program or batch job. DTB Dynamic Transaction Backout. A process to recover recoverable resources based on information stored in the dynamic Log. Dynamic Log A main storage area of a CICS region where all changes made to recoverable resources are stored. EIB Execute Interface Block . A CICS control block containing useful CICS system information. It is given to each CICS application program. EIP Execution Interface Program . This interfaces between CICS control programs and application programs. FCP File Control Program. Manages all input/output operations of files under CICS FCT Generic Key File Control Table. Registers all files to be used in the CICS region. A higher part of a record key. It is used to identify a group of records generically or a record which belongs to that generic group. ICP Interval Control Program . Provides all time related services under CICS.

Maples ESM Technologies Pvt. Ltd

Page 243 of 246

CICS

JCP

Journal Control Program. Performs logging of data onto external files called journals.

JCT

Journal Control Table. Registers the system log file and all user journal files.

KCP LUW

Task Control Program. It controls a flow of CICS tasks. Logical Unit of Work. A sequence of processing between two sync points. Resource recovery is to be applied for one LUW.

Map Mapset MDT

A format to create a screen layout based on MVS A group of BMS maps link edited together. Modified Data Tag . Last bit of an attribute character which indicates whether the screen field has been modified ( if 1 ) or not (if 0)

MRO

Multi Region Operation . communication between a CICS system and other CICS systems in the same processor

Multitasking

Execution of more than one task concurrently within the same region.

Multithreading

Execution of more than one task concurrently initiated by same program within the same region.

the

Non reentrant

A concept that a program modifies itself during its execution so that it cannot reenter to itself after an interruption by the operating system.

PA Key

Program Attention ( Access) key . It is used for triggering attention to the associated program.

Page (BMS)

BMS makes it possible to send a series of screen panels to a terminal as one logical message. In such a case one screen panel of this logical message is called a page.

Page (VS)

One unit of virtual storage ( 4 Kb ) which is to be brought in or out from the real storage.

PF key

Program Function key . It is used to perform a special function assigned to that key.

PCP

Program Control Program. It manages the flow of CICS application programs.

PCT

Program Control Table. It registers all CICS transactions with various options such as security, priority, recovery.

PPT

Processing Program Table. It registers all CICS application programs.

Maples ESM Technologies Pvt. Ltd

Page 244 of 246

CICS

Pseudo-Conversational

A mode of dialog between program and terminal which appears to the operator as a continuous conversation but which is actually carried by a series of separate tasks.

QID

Queue Identifier. One to eight character code which identifies a Temporary Storage Queue (TSQ)

Quasi-Reentrant

A concept that a program does not modify itself during its execution under CICS , so that it can reenter into itself after an interruption by CICS at a CICS command.

Reentrant

A concept that a program does not modify itself during its execution under OS so that it can reenter into itself after an interruption reentrant. by OS. An online program under OS must be

SCP

Storage Control Program. It manages request of dynamic storage by CICS control programs and application programs.

SIT

System Initialization Table. It contains control information for CICS initialization.

Skipper

An unlabeled 1-byte field in a BMS Map with the auto skip attribute. It makes unprotected field. the cursor automatically skip to the next

Stopper

An unlabeled 1-byte field with the protect attribute. It makes the cursor stop forcefully at its position.

SVC Sync Point

Supervisory call. Synchronization point. A point during processing activities of a program where all resource updates are complete and the

resources are in good condition. Task A basic unit of work which is scheduled by the operating system or CICS. TCA Task Control Area. A CICS control block for governing execution of a CICS task. TCP Terminal Control Program. Manages data exchange between terminals and CICS application programs. TCT TCTTE Terminal control Table. Registers all terminals used under CICS. Terminal Control Table Terminal Entry. A system area of the TCT entry for a terminal. TCTUA Terminal Control Table User Area. Auser area of the TCT entry for a terminal.

Maples ESM Technologies Pvt. Ltd

Page 245 of 246

CICS

TDP

Transient Data Program. It manages input/output operations of Transient Data Queue.

TDQ

Transient Data Queue. A group of sequential data placed in the external dataset under CICS.

TIOA

Terminal Input/Output operations.

Area. A buffer for terminal input/output

Transaction

An entity which initiates execution of a task. In CICS transaction is identified by the transaction identifier.( 1 to 4 characters)

Transaction deadlock

An infinite wait state where two tasks are waiting for each other to release resources which are held by the other.

TSP

Temporary Storage Program. It manages input/output operations of TSQ.

TSQ

Temporary Storage Queue. A group of sequential data used for scratchpad purposes under CICS.

TST

Temporary Storage Table. Registers all Temporary Storage Queues which requires recovery or security check.

TWA

Transaction Work Area. A user work area for a CICS task whose size is defined in Program Control Table.

XRF

Extended Recovery Facility. An advanced CICS recovery facility by which CICS system can be recovered and restarted automatically.

Maples ESM Technologies Pvt. Ltd

Page 246 of 246

Das könnte Ihnen auch gefallen