67% found this document useful (3 votes)
2K views268 pages

Fresher Notes PDF

The document provides information about COBOL programming on mainframe systems. It describes the key components of online and batch systems that use COBOL, including common programs like data entry, inquiry, update, and report programs. It also outlines the basic structure of a COBOL program, including the identification, environment, and data divisions, and provides steps for creating, compiling, and running a COBOL batch program.

Uploaded by

Chinnammal M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
67% found this document useful (3 votes)
2K views268 pages

Fresher Notes PDF

The document provides information about COBOL programming on mainframe systems. It describes the key components of online and batch systems that use COBOL, including common programs like data entry, inquiry, update, and report programs. It also outlines the basic structure of a COBOL program, including the identification, environment, and data divisions, and provides steps for creating, compiling, and running a COBOL batch program.

Uploaded by

Chinnammal M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 268

School of MAINFRAMES Email: schoolofmainframes@gmail.

com Ph : 040-64515137

IBM
MAINFRAMES

BY
MADHU PADALA

School Of MAINFRAMES

1
School of MAINFRAMES Email: schoolofmainframes@gmail.com Ph : 040-64515137

2
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

COBOL

1
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

2
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Online and Batch systems

Almost all mainframe systems will have both Online and Batch systems.

Online system
Data to be processed in the batch is entered from online or another batch system.
Technologies used in online system COBOL, CICS, DB2 / VSAM

Activities of online system


1. Data entry
Data entry operators enter the data from the hard copy to mainframes using
CICS application. They are trained on these CICS applications.
Ex: Premium payment on policy at premium collection counters
Deposit or withdrawal at bank teller
Fill account opening form of a policy or a bank account
Fill loan application form
Correction of data when primary data is not correct
2. Data inquiry
Customer care team responds to the enquiries of customers
Ex: Enquiry of credit balance
Debit Card or credit card locking on card theft
Enquiry of next EMI or next premium payment date
Wave off of late payment charges
It is a primary source of the data. It gives instantaneous access to data.
Online system is up during the day time and will come down before batch processing starts.

Online Users
1. Data entry operators
2. Customer care team
3. Business user’s team
4. Data correction team
5. SIT/UAT, Developers to place test transactions

Types of COBOL programs in Online region


1. Inquiry Programs
A. Simple Inquiry
Most of these programs are used for the data inquiry by customer service or user team
B. Inquire single record in multiple pages with F10 and F11 logic
When a record has lot of fields and not fit into single page then show it into multiple
pages. Use navigation keys F10 and F11 to move from one page to other page.
Different pages are defined with different BMS maps.
C. Inquire multiple records with single screen but with a paging logic by using
F7 and F8
2. Update/Insert/Delete programs
More validations required for both Update and Insert programs.
Confirmation is required before deleting a record
3. Menu driven programs
It is designed with more programs and its corresponding transactions. Terminal user
knows about main transaction and this transaction invokes main program.

3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Batch System
Technologies used in batch system COBOL, JCL, DB2 /VSAM
Data is collected from online or from another batch system and it is processed

Activities done in Batch system


1. Online unloads to sequential file
2. Collection of data from various upstream interface systems
3. Processing of transactions from collected from online and other batch system and
Updating all master files.
4. Generating reports.
5. Data extraction and sending to downstream systems.

Batch processing is done during night cycle with series of JCLs one after the other.

Examples:
Premiums are paid online
Premiums are processed in batch to generate commissions and reports
Cheques are entered online
Cheques are processed in batch for collections
Payments/withdrawals done in online
Reports and interest calculations are done in batch
Payrolls are processed in batch
Bank interest calculations are done in batch
Bank statements are generated batch
Account application, Loan application done in online
Account issue, Loan application enquiry, Loan issue done in batch.

Types of COBOL programs in Batch region

1. Extract programs.
Extracts data from one or more master VSAM Files/DB2 tables based on business rules.
2. Update programs.
update/delete/insert records into different VSAM files/DB2 tables based on business rules.
Most of transactions entered in online are processed in batch with business processing logics to
update master files.
3. Report programs.
These programs Reports the data available in files into a readable format to the users. Which
contains page headers, detail headers, detail records, sub totals, grand totals, page footers.
These reports can be printed on mainframe printers and will be reviewed by the business users.
4. Combination of above three types of programs.
Update + Extract
Update + Extract + Report
Update + report

4
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Process to execute Cobol batch program


Steps to create and run the COBOL program

1. Create a Source Library and load Library in ISPF 3.2


2. Create a member to write a program in ISPF 3.4
3. Write program based on the requirement
4. Compile COBOL program with compile JCL to create a Load module if the program is
error free. In every installation compile JCL will be available. Copy it to PDS and
change it to supply Source program and load library to create a load module.
5. Create a RUN JCL in Source library or a separate JCL library to run the load module
of the COBOL program.
6. Create input files in ISPF 3.2 that are using in the COBOL program and prepare data
according to the layout.
7. Run the JCL and Check the results in output file. Output files will be created in
RUN JCL.

History of Cobol
COBOL is created in late 1950's.
Initially it is used for military applications. Later it is designed for business applications.
In 1974 it is standardized as OS/VS-COBOL or VS-COBOLI.
In 1985 it is standardized as VS-COBOLII.

Advantages of Cobol
1. English like language.
2. Easy to understand with Top Down approach.
3. Every verb is self-explanatory.
4. Easy to test program.
Disadvantages of Cobol
1. Lengthy programming.
2. It is not designed for scientific applications.

Language Structure.
Character Set - Digits (0-9), Alphabets (A-Z), Space, Special Characters (+ - * / ( ) = $; " ><.)

Word - One or more characters- User defined or Reserved. It can have 1-30 characters with at
least one alphabet in it. Hyphen is the only allowed special character but it cannot be first
or last letter of the word.

Clause - One or more words. It specifies an attribute for an entry.


Statement - One or more valid words and clauses.
Sentence - One or more statements terminated by a period.
Paragraph - One or more sentences.
Section - One or more paragraphs.
Division - One or more sections or paragraphs.
Program - Made up of four divisions.

5
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Divisions in COBOL
There are four divisions in a COBOL program and Data division is optional.
1. Identification Division.
2. Environment Division.
3. Data Division.
4. Procedure Division.

IDENTIFICATION DIVISION
The IDENTIFICATION DIVISION is the first division of a COBOL program. It supplies the
information about the program to others who may read or use the program. The
IDENTIFICATION DIVISION is divided into the following paragraphs :

PROGRAM-ID. Program-name.
Used to specify the program name. Use names of eight characters or less, letter and digits only,
because such names are accepted on all systems.

AUTHOR. Author-name.
Used to specify the programmer’s name.

DATE-WRITTEN. Date.
Specify the date the program was coded.

DATE-COMPILED. Date.
Can be coded with an actual date. But if it is coded without a date entry, the compiler itself will
automatically fill in the actual date of compilation.

ENVIRONMENT DIVISION
The ENVIRONMENT DIVISION is the only machine-dependent division of a COBOL program. It
is composed of two sections :

CONFIGURATION SECTION.
SOURCE-COMPUTER. Computer. Computer used for compiling the program.
OBJECT-COMPUTER. Computer. Computer used for executing the program. Usually this
Configuration Section is omitted.

INPUT-OUTPUT SECTION.
FILE CONTROL.
It contains information regarding the files to be used in the program with SELECT clause with
DDNAME. It also contains the organization, access mode, record key and file status of the file. It
is required only if the files are used in this program.

DATA DIVISION
The DATA DIVISION defines and describes fields, records, and files in storage. Commonly, it
consists of the following sections:

FILE SECTION
Defines all input and output files with recording mode and file layouts under FD entry (File
Description Entry)

6
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

WORKING-STORAGE SECTION
Reserves storage for fields not part of input or output but these fields are required for processing.
These include constants, end-of-file indicators, counters, accumulators and work areas. Usually
these are field names precede with WS-.

LINKAGE SECTION
Linkage section is used in two situations.

1. In the Sub program


Used to receive data items that will be passed to the called program from the calling program
and vice-versa.
2. In the Main program
Used to pass the data to the Main program from PARM parameter in the JCL. Maximum of
100 characters can be passed like this. In both the cases the USING clause should be coded on
procedure division as shown below. Procedure Division Using LK-Variables.

PROCEDURE DIVISION
The PROCEDURE DIVISION is divided into paragraphs. Each paragraph is an independent
module or routine that includes a series of instructions designed to perform specific set of
operations. Paragraph names are coined by the programmer following the rules for forming data-
names. A PROCEDURE DIVISION may also consist of several sections. A section may contain
several paragraphs.

Coding Rules
1-6 sequence number
3 Page num + 3 Line Num
Sometimes used for a request number on changed line

7 comment/continuation
* -
Comments are used for
Brief descriptions of processing logic
Change history
To comment existing code

8-11 Area A
Division Names
Section Names
Entry names
01, 77 level declarations
Paragraph names

12-72 Area B
02-49, 66, 88 level declarations
All procedure division verbs
Select statement in environment division
Copy statement in declaration and procedure divisions.

73-80 User area


It is commonly used for request number on changed lines.

7
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

A Sample COBOL Program

IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE1.
AUTHOR. MADHU PADALA.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE CONTROL.
SELECT IN-FILE ASSIGN TO DD1.
SELECT OUT-FILE ASSIGN TO DD2.

DATA DIVISION.
FILE SECTION.
FD IN-FILE.
01 IN-REC PIC X(20).

FD OUT-FILE.
01 OUT-REC PIC X(20).

WORKING-STORAGE SECTION.
01 WS-EOF-IN PIC X(1) VALUE ‘N’.

PROCEDURE DIVISION.
000000-MAINLINE.

PERFORM 100000-INITIALIZATION THRU 100000-EXIT.


PERFORM 200000-PROCESS THRU 200000-EXIT
UNTIL WS-EOF-IN = ‘Y’.
PERFORM 300000-TERMINATION THRU 300000-EXIT.

STOP RUN.

100000-INITIALIZATION.

OPEN INPUT IN-FILE


OUTPUT OUT-FILE.

100000-EXIT.
EXIT.

200000-PROCESS.

READ IN-FILE AT END MOVE 'Y' TO WS-EOF-IN


GO TO 200000-EXIT.

MOVE IN-REC TO OUT-REC


WRITE OUT-REC.

200000-EXIT.
EXIT.

300000-TERMINATION.

CLOSE IN-FILE
OUT-FILE.
300000-EXIT.
EXIT.

8
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Variables and constants


In a program, data is used in Variables and constants.
Constants are two types and these are literals and Figurative Constants.

Literal Figurative Constants Variable/Identifier

Numeric Non Numeric Space, Spaces Variable is a name for a


18 digits 160 characters Zero, Zeros, Zeroes memory location.
Ex: 100 'Y' Quote, Quotes Values can be changed in
20.50 '20111122' High-value, High-values a variable
-20.50 'HYDERABAD' Low-Value, Low-Values
ALL

Numeric literals should be coded without quotes. Non Numeric literals should be coded with
quotes. Figurative constants are used for better readability

Variable Declaration
Level Number Identifier PIC Datatype (Length) Usage Period
Value
Sign
Justified
Sync
Rules on level numbers
01 is a group/elementary/record level
02 to 49 cannot be declared without 01
02 to 48 may be elementary or group level
49 is used on DB2 varchar field
Level number on down side levels should be incremented.
Same level number is recommended for each down side level

Special level numbers


77 -- Pure elementary
66 -- Renames
88 -- Condition Names

Data types: A - Alphabetic


9 - Numeric Maximum length is 18 digits
X - Alpha numeric
A - Alphabetic data type
A field that may contain only letters or blanks.
Ex: 05 CITY-NAME PIC A(10).

X - Alphanumeric data type


A field that may contain any character i.e. letters, digits, blanks and/or special characters. It is
used for both alphabets and numeric.
Ex: 01 ACT-HOLDER-NAME PIC X(20).  ALPHABETS ARE STORED
01 ACT-HOLDER-DOB PIC X(8).  NUMERIC IS STORED
Even though numeric item is stored in this data type it is not used in arithmetic operations.

9
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

9 - Numeric data type


Any signed or unsigned field that will contain only digits is considered numeric.
Ex: 01 ACT-NUMBER PIC 9(10). PURE INTEGER
01 ACT-BALANCE PIC S9(9)V99. DECIMALS

PICTURE Clause
Group items are defined by a level number and a name, which is followed by a period.
Elementary items must be described with a PICTURE (or PIC, for short) clause.
Functions of the PICTURE Clause
1. Specifies the type of data contained within an elementary item.
2. Indicates the size of the field.

Ex:
01 WS-FIELD1 PIC A.
01 WS-FIELD2 PIC AAA.
01 WS-FIELD3 PIC A(3).

01 WS-FIELD1 PIC 9.
01 WS-FIELD2 PIC 9(01).
01 WS-FIELD3 PIC 999.
01 WS-FIELD4 PIC 9(3).
01 WS-FIELD5 PIC 9(3)V99.

01 WS-FIELD1 PIC X.
01 WS-FIELD2 PIC XXX.
01 WS-FIELD3 PIC X(3).

Filler

Filler is used when a data name is not required for a memory location. Filler is used in 3 different
situations
1. When a field under a group variable is declared with a constant value and is not modified this
through the program then instead of giving a name to the field it can be declared as filler. With
number of variables can be reduced.
Ex: Page headers and detail headers in reports.
01 DETAIL-RECORD.
05 FILLER PIC X(10) VALUE 'AGENT NUM'.
05 FILLER PIC X(5) VALUE SPACES.
05 FILLER PIC X(10) VALUE 'SALES DATE'.
05 FILLER PIC X(5) VALUE SPACES.
05 FILLER PIC X(15) VALUE 'SALES AMOUNT'.

2. When spacing is required in a file between two fields. It increases readability


Ex: 01 OUT-RECORD.
05 AGENT-NUM PIC X(5).
05 FILLER PIC X(2).
05 AGENT-NAME PIC X(20).
05 FILLER PIC X(2).
05 AGENT-DOJ PIC X(8).
05 FILLER PIC X(2).
05 AGENT-DOB PIC X(8).

10
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

3. When future expansion is expected in a file. It reduces maintenance. This type of file layouts
are placed in a COPYBOOK. When a new field is to be added to the file then include that new
field in the end by reducing the filler length.
Ex: 01 EMP-REC.
05 EMP-NUM PIC X(5).
05 EMP-NAME PIC X(20).
05 EMP-DOJ PIC X(8).
05 EMP-DOB PIC X(8).
.
.
05 FILLER PIC X(20).

If a filler is available in a copybook and a new field is required Programs that are using this new
field are impacted Programs that are not using this new field are not impacted. If filler is not
available in a copybook and a new field is required. Programs that are using this new field are
impacted Programs that are not using this new field are recompiled to get the new length of the
copybook. PROC that is creating this file is impacted to increase LRECL

Structures
Structures are used to handle variables with more flexibility.
Case1:
01 EMP-REC PIC X(52).

Case2: Case3:
01 EMP-REC. 01 EMP-REC.
02 EMP-NUM PIC 9(4). 02 EMP-NUM PIC 9(4).
02 EMP-STATUS PIC X(1). 02 EMP-STATUS PIC X(1).
02 EMP-NAME PIC X(20). 02 EMP-NAME.
02 EMP-DOJ PIC 9(8). 03 FIRST-NAME PIC X(10).
02 EMP-BASIC PIC 9(7)V99. 03 LAST-NAME PIC X(10).
02 EMP-HRA PIC 9(3)V99. 02 EMP-DOJ.
02 EMP-ALLOWANCE PIC 9(3)V99. 03 EMP-DOJ-CCYY.
04 EMP-DOJ-CC PIC 9(02).
04 EMP-DOJ-YY PIC 9(02).
03 EMP-DOJ-MM PIC 9(02).
03 EMP-DOJ-DD PIC 9(02).
02 EMP-SALARY-DTLS.
03 EMP-SALARY PIC 9(7)V99.
03 EMP-HRA PIC 9(7)V99.
03 EMP-ALLOWANCE PIC 9(7)V99.
Case4
01 EMP-REC.
05 EMP-NUM PIC 9(4).
05 EMP-STATUS PIC X(1).
05 EMP-NAME.
10 FIRST-NAME PIC X(10).
10 LAST-NAME PIC X(10).
05 EMP-DOJ.
10 EMP-DOJ-CCYY.
15 EMP-DOJ-CC PIC 9(02).
15 EMP-DOJ-YY PIC 9(02).
10 EMP-DOJ-MM PIC 9(02).
10 EMP-DOJ-DD PIC 9(02).
05 EMP-SALARY-DTLS PIC 9(7)V99.
10 EMP-SALARY PIC 9(7)V99.
10 EMP-HRA PIC 9(7)V99.
10 EMP-ALLOWANCE PIC 9(7)V99.

11
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

The Above 4 cases takes the same memory i.e. 52 bytes.

In case 1: Employee record is shown as a single field. It is not possible to see it in different fields.

In case 2: Employee record is shown as multiple fields. The data in the employee record can be
seen as a record or different sub fields.

In case 3: Employee record is shown as multiple fields.


EMP-NAME field is again split into sub fields.
EMP-DOJ field is again split into sub fields.
Salary fields are grouped under group field EMP-SALARY-DTLS.
Sub levels are coded in an incremental order.
There is lot flexibility in handling every elementary and group fields.

In case 4: It is same as Case3 but the level numbers are used as 01, 05, 10, 15..
instead of 01, 02, 03, 04..It is a standard level numbers used in real applications.

Structures have lot of flexibility in handling data in elementary and group fields.

Value clause
1. It is coded in variable declaration to supply initial value or a default value.
2. For A and X type the value is required in Quotes
01 WS-IND PIC X(1) VALUE 'N'.
3. For data type 9 the value is coded without Quotes.
01 BONUS-PERCENT PIC 9(3)V99 VALUE 33.33.
4. Value clause on File section and Linkage Section are ignored
5. PIC clause is not allowed On a Group variable but value clause can be coded
6. Length of the Value clause can be smaller than PIC clause but should not exceed
7. Value clause is recommended with initial or any other value for all working storage
variables to avoid garbage values
8. Initial values are highly recommended on numeric items to avoid S0C7 abend
9.If the value in the Value clause is continuing to another line then use '-' in col 7.

Value clause is to provide initial value at the declaration.


01 WS-IND PIC X(1) VALUE 'N'.
77 WS-COUNT PIC 9(4) VALUE 0.

01 WS-TOTAL PIC 9(7)V99 VALUE ZEROS.

01 WS-NAME PIC X(20) VALUE SPACES.

01 BONUS-PERCENT PIC 9(3)V99 VALUE 33.33.

01 WS-DATE VALUE '20111122'.


05 CCYY PIC 9(4).
05 MM PIC 9(2).
05 DD PIC 9(2).

01 WS-DATE.
05 CCYY PIC 9(4) VALUE 2011.
05 MM PIC 9(2) VALUE 11.
05 DD PIC 9(2) VALUE 22.

12
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Qualification of datanames
1. Same variable name can be declared if it is not 01, 77 and 88 level.
2. If the same variable name is used in 02 to 48 levels then use qualification of
datanames while using those variables in procedure division
Ex:
01 HDR1.
05 HDR1-CCYY PIC 9(4).
05 FILLER PIC X(1) VALUE ‘/’.
05 HDR1-MM PIC 9(2).
05 FILLER PIC X(1) VALUE ‘/’.
05 HDR1-DD PIC 9(2).
01 WS-DATE1.
05 CCYY PIC 9(4).
05 MM PIC 9(2).
05 DD PIC 9(2).
01 WS-DATE2.
05 CCYY PIC 9(4).
05 MM PIC 9(2).
05 DD PIC 9(2).

MOVE CCYY IN WS-DATE2 TO HDR1-CCYY.


MOVE MM IN WS-DATE2 TO HDR1-MM.
MOVE DD IN WS-DATE2 TO HDR1-DD.

USAGE clause
Numeric data in a computer may be represented in one of two basic modes. They may be
represented as character data or as numeric data. The arithmetic registers of computers perform
arithmetic with numeric data that is in numeric, not character mode. If numeric data is
represented in character mode, it must first be converted to numeric mode before arithmetic
computations can be performed.

In COBOL, data in character mode is described in DISPLAY mode, while data in numeric mode is
described as being COMPUTATIONAL MODE. All data items are assumed to be in DISPLAY
mode unless they are declared to be COMPUTATIONAL. The declaration is done in the DATA
DIVISION with the USAGE clause.
Terms used for memory
Nibble - 4 Bits is one nibble. In packed decimal, each nibble stores one digit.
Byte - 8 Bits is one byte. By default, every character is stored in one byte.
Half word - 16 bits or 2 bytes is one half word. (MVS)
Full word - 32 bits or 4 bytes is one full word. (MVS)
Double word - 64 bits or 8 bytes is one double word. (MVS)

Memory occupied for different usage clauses


DISPLAY - Default. Number of bytes required equals to the size of the data item.
COMP - Binary representation of data item.PIC clause can contain S and 9 only.
S9(01) - S9(04) Half word.
S9(05) - S9(09) Full word.
S9(10) - S9(18) Double word.
Most significant bit is ON if the number is negative.
Examples of COMP:
01 WS-COUNT PIC S9(4) COMP.
01 NUM-OF-RECS PIC S9(4) COMP.
01 NUM-OF-TRXNS PIC S9(8) COMP.

13
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

COMP-1 - Single word floating point item. PIC Clause should not be specified.
COMP-2 - Double word floating-point item. PIC Clause should not be specified.

COMP-3 - Packed Decimal representation. Two digits are stored in each byte.
Last nibble is for sign. (F for unsigned positive, C for signed positive and D for signed negative)
Formula for Bytes: Integer ((n/2) + 1)) => n is number of 9s.
Examples of COMP-3:
01 SALARY PIC S9(7)V99 COMP-3.
01 COMM-AMOUNT PIC S9(7)V99 COMP-3.
01 ACT-BAL PIC S9(7)V99 COMP-3.
01 HRA-PERCENT PIC S9(3)V99 COMP-3.

COMP is used for pure numbers like counters, number of payments, number of children, number
of months and Effective memory. Faster computation because it is stored in binary format.
COMP-3 is used for amounts, rates, percentages and Effective memory.

Sync clause
It is used for faster access because the data item stored in word boundaries. With this reason it is
effective computation. It is used only on COMP, COMP-1 and COMP-2 items

Without SYNC With SYNC


01 WS-GROUP1. 01 WS-GROUP1.
05 WS-COUNTRY PIC X(3). 05 WS-COUNTRY PIC X(3).
05 WS-COUNT1 PIC S9(4) COMP. 05 WS-COUNT1 PIC S9(4) COMP SYNC.
05 WS-FLAG PIC X(1). 05 WS-FLAG PIC X(1).

SIZE OF WS-GROUP1 = 3+2+1 = 6 SIZE OF WS-GROUP1 = 3+ SLAG BYTE +2+1 = 7


WS-COUNT1 occupies its own word boundary.

Why SYNC is not used in many installations?


1. Memory is wasted in slag bytes.
2. It is difficult to find the offset of the next field because one should know about the number of
slag bytes wasted.

Sign clause
Syntax:
SIGN IS TRAILING/LEADING (SEPARATE CHARACTER).
It is applicable when the picture string contain 'S'.
Default is TRAILING (WITH NO SEPARATE CHARACTER). So 'S' doesn't take any space.
It is stored in the first nibble of last digit. It is used only for DISPLAY numeric items but not comp
and comp-3.

Where the sign is stored in the numeric items?


In Zoned decimal by default it is stored in the first nibble of the last digit. In Packed decimal it is
stored in the right most nibble in both packed and zoned decimals. C is +ve, D is -ve and F is
unsigned.
In signed Binary items it is stored in the left most bit. If it is 0 then it is +ve. If it is 1 then
it is -ve. In unsigned Binary items left most bit is always 0.
In all the cases it is not going occupy any extra byte. So the length is not going to be changed if
sign is used. When it is required show in the report then it has to be converted into edited
numeric.

14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Few examples of Signed numeric

Numeric Type Value Hex on for When When Length


stored Internal display Written in
storage ed file
9(3) 456 FFF 456 456 3
456

S9(3) +456 FFC 45F 45F 3


456

S9(3) -456 FFD 45O 45O 3


456
S9(3) LEADING
SEPERATE -456 6FFF -456 -456 4
CHARACTER 0456

S9(3) TRAILING -456 FFD 45O 45O 3


456

S9(3) TRAILING -456 FFF6 456- 456- 4


SEPERATE 4560
CHARACTER

9(3) COMP-3 456 46 456 á? 2


5F

S9(3) COMP-3 +456 46 456 á% 2


5C

S9(3) COMP-3 -456 46 45O á_ 2


5D

S9(4) COMP 86 05 0086 î 2


06

S9(4) COMP -86 FA 008O ¡ 2


FA

Justified clause

Numeric
For numeric items the default justification is Right for Integer part and Left for Decimal part. And
it cannot be changed with Justified clause. So Justified clause is not allowed to Numeric items

Alphanumeric and Alphabetic


For Alphabetic and Alphanumeric the default justification is Left and it can be changed with
'Justified Right'. If the receiving field is smaller than the sending field then the truncation is done
on the right side by default. If Justified Right is specified then truncation is done on left side.
Ex.1: 01 M PIC X(3) VALUE 'AB '.
01 N PIC X(4) VALUE'ABCD'.

Move M to N.
Display 'N:' N.
RESULT:
N: 'AB '

15
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Ex.2: 01 M PIC X(3) VALUE 'AB '.


01 N PIC X(4) JUSTIFIED RIGHT VALUE 'ABCD'.

Move M to N.
Display 'N:' N.
RESULT:
N: ' AB '

Ex.3: 01 M PIC X(3) VALUE 'AB '.


01 N PIC X(4) VALUE 'ABCD'.

Move N to M.
Display 'M:' M.
RESULT:
M: 'ABC'

Ex.4: 01 M PIC X(3) JUSTIFIED RIGHT VALUE 'AB '.


01 N PIC X(4) VALUE 'ABCD'.

Move N to M.
Display 'M:' M.
RESULT:
M: 'BCD'
It is rarely used in report formats.

Redefines clause

Reusing the existing memory of one variable/structure to another variable/structure.

Limitations
1. Redefined item should follow original item.
2. Redefining should be done on the same level.
3. Same item or a structure can be redefined more than one time.
4. Redefined item can be smaller or larger than the original item.
5. But redefining into larger item is not recommended.
6. Redefining can be done in 01 level if it is not file declaration.

Different situations to use Redefines


1. on mutually exclusive conditions when two variables/structures are getting values then
redefines can be used. In this case the memory can be saved.
Ex1:
Agent file shown below has two different layouts, one is without redefines which takes 61
bytes and other one is 36 bytes. An Individual or a company can act as an agent. An Individual
have First-Name and Last-Name but Company will have a company name.

In layout1, there is a separate memory for both INDIVIDUAL-AGENT-NAME and COMPANY-


NAME. Either of these fields will have spaces in every record. So memory is wasted in every
record.
In layout2, the memory for both INDIVIDUAL-AGENT-NAME is used for COMPANY-NAME.

16
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Layout1: 01 AGENT-REC.
05 AGENT-ID PIC X(05).
05 INDIVIDUAL-AGENT-NAME.
10 FIRST-NAME PIC X(20).
10 LAST-NAME PIC X(10).
05 COMPANY-NAME PIC X(25).
05 AGENT-TYPE PIC X(1).
88 INDIVIDUAL-AGENT VALUE 'I'.
88 CORPORATE-AGENT VALUE 'C'.

Data in layout1
AAA01STEPHEN FLEMING I
AAC05MICHEAL JOHN I
AAC07 BERTRAM FINANCIAL CO C
AYM05 PROCTER & GAMBLE C

Layout2 01 IN-REC.
05 AGENT-ID PIC X(05).
05 INDIVIDUAL-AGENT-NAME.
10 FIRST-NAME PIC X(20).
10 LAST-NAME PIC X(10).
05 COMPANY-NAME REDEFINES INDIVIDUAL-AGENT-NAMEPIC X(25).
05 IN-AGENT-TYPE PIC X(1).
88 INDIVIDUAL-AGENT VALUE 'I'.
88 CORPORATE-AGENT VALUE 'C'.

Data in layout2
AAA01STEPHEN FLEMING I
AAC05MICHEAL JOHN I
AAC07BERTRAM FINANCIAL COMPANY C
AYM05PROCTER & GAMBLE C

Ex2:
Account master file contains multiple account types that has different layouts each layout is
redefined.
01 ACCOUNT-REC.
05 ACCOUNT-GENERAL-INFO.
10 ACCT-NUM PIC X(10).
10 ACCT-HOLDER-NAME PIC X(20).
.
.
10 ACCT-TYPE PIC X(1).
88 SAVINGS-ACCOUNT VALUE 'S'.
88 CURRENT-ACCOUNT VALUE 'C'.
88 NRI-ACCOUNT VALUE 'N'.

05 ACCOUNT-INFO PIC X(500).


05 SAVINGS-ACCOUNT-INFO REDEFINES ACCOUNT-INFO.
10 MAX-ACCT-BAL PIC S9(7)V99 COMP-3.
10 MAX-DEPOSIT-PER-DAY PIC S9(7)V99 COMP-3.
10 MAX-WITHDRAWL-PER-DAY PIC S9(7)V99 COMP-3.
.
.
05 CURRENT-ACCOUNT-INFO REDEFINES ACCOUNT-INFO.
10 OVER-DRAFT-AMT PIC S9(7)V99 COMP-3.
10 TAX-NUMBER PIC X(10).
10 MIN-BAL-AMOUNT PIC S9(7)V99 COMP-3.
.
.

17
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

05 NRI-ACCOUNT-INFO REDEFINES ACCOUNT-INFO.


10 RESIDENCY-COUNTRY PIC X(3).
10 CURRENCY-CODE PIC X(3).
10 PASSPORT-NUM PIC X(10).
10 TAX-NUMBER PIC X(10).
10 MAX-OVERDRAFT-AMT PIC S9(7)V99 COMP-3.
.
. .
Three different accounts savings, current and NRI account types can be stored the above account
file. All three account records will contain general information which is of 500 bytes. The general
information is common for all accounts but the account level layout is different for each type of
account and it takes 500 bytes. If a redefines is not coded then each record occupies 2000 bytes. If
redefines is used, then it takes 500 bytes for general info and 500 bytes for all layouts so it takes
only 1000 bytes for every record.

2. Alphanumeric items are to be used in arithmetic operations, then redefine alphanumeric item
into numeric item and use the numeric item in the arithmetic operations.
05 WS-DATE PIC X(8).
05 WS-DATE-N REDEFINES WS-DATE PIC 9(8).
COMPUTE COMP-EFF-DATE = 99999999 - WS-DATE-N.
WS-DATE-N can be used in the arithmetic operations.

3. When a numeric item is to be used with different decimals


05 BONUS-PERCENT PIC 9(3)V99 VALUE 33.00.
05 BONUS-RATE REDEFINES BONUS-PERCENT PIC 9(1)V9(4).
Bonus-percent 33.00 is visible as 0.3300 in bonus-rate. Based on different situations either
bonus-percent or bonus-rate can be used.

4. To see the same variable with different fields.


05 POLICY-NUMBER PIC X(10).
05 POLICY-TYPE REDEFINES POLICY-NUMBER PIC X(1).
88 INDIVIDUAL-POLICY value '1'.
88 GROUP-POLICY value '2'.

05 POLICY-NUMBER.
10 POLICY-TYPE PIC X(1).
88 INDIVIDUAL-POLICY value '1'.
88 GROUP-POLICY value '2'.
10 FILLER PIC X(9)
5. Output map fields redefine input map fields of symbolic map in CICS.

RENAMES Clause
The RENAMES clause provides the programmer with the capability of regrouping elementary
data items. It resembles the REDEFINES clause, except that it can form a new grouping of data
items which combines several items. Use of the RENAMES clause is always signaled by the
special 66 level number.
Ex: 01 TAX-RECORD.
02 SOC-SEC-NUMBER PIC X(9).
02 NAME.
03 FIRST-NAME PIC X(10).
03 LAST-NAME PIC X(15).
02 TOTAL-YTD.
03 GROSS-PAY PIC 9(8)V99.
03 NET-PAY PIC 9(8)V99.
03 TAX PIC 9(5)V99.
66 LAST-GROSS RENAMES LAST-NAME THRU NET-PAY.

18
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Classifications of Verbs

Arithmetic  ADD, SUBTRACT, DIVIDE, MULTIPLY, COMPUTE


Assignment  MOVE, SET, INITIALIZE
Conditional  IF, EVALUATE
Paragraph invocation  PERFORM, PERFORM with THRU
Iteration  PERFORM with TIMES or UNTIL condition
Subprogram invocation  CALL, GOBACK, CANCEL, EXIT PROGRAM
Copybook invocation  COPY
Control transfer  GO TO, NEXT SENTANCE
High level utilities  SORT, SEARCH, SEARCH ALL
File handling  OPEN, CLOSE, READ, WRITE, REWRITE, DELETE, START,
READ NEXT, RELEASE, RETURN
Terminal input output  ACCEPT, DISPLAY
String manipulation  STRING, UNSTRING, INSPECT
Do nothing  CONTINUE, EXIT

Arithmetic verbs

Syntax:
VERB {Identifier/literal} {TO/FROM/BY/INTO}
{Identifier K /Identifier GIVING Identifier K}
[ROUNDED] [ON SIZE ERROR Statement-Block END-VERB]

Most COBOL arithmetic verbs conform to the template above. For example,
ADD ALLOWANCE TO SALARY.
ADD BONUS TO SALARY GIVING GROSS-SALARY.

SUBTRACT TAX FROM EARNINGS.


SUBTRACT TAX FROM GROSSPAY GIVING NETPAY.

DIVIDE TOTAL-AGENT-NUM INTO TOTAL-SALES GIVING AVERAGE-SALES.


DIVIDE TOTAL-SALES BY TOTAL-AGENT-NUM GIVING AVERAGE-SALES.

MULTIPLY HRA-FACTOR BY BASIC-SAL GIVING HRA-AMOUNT.


MULTIPLY 0.6 BY TAX.

The exceptions are the COMPUTE and the DIVIDE with REMAINDER.

The ROUNDED option


Receiving Field Actual Result Truncated Result Rounded Result
PIC 9(3)V9. 123.25 123.2 123.3
PIC 9(3). 123.25 123 123

The ROUNDED option takes effect when, after decimal point alignment, the result calculated
must be truncated on the right hand side. The option adds 1 to the receiving item when the
leftmost truncated digit has an absolute value of 5 or greater.

19
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

The ON SIZE ERROR option


Receiving Field Actual Result SIZE ERROR
PIC 9(3)V9. 245.96 YES
PIC 9(3)V9. 1245.9 YES
PIC 9(3). 124 NO
PIC 9(3). 1246 YES
PIC 9(3)V9 Not Rounded 124.45 YES
PIC 9(3)V9 Rounded 124.45 NO
PIC 9(3)V9 Rounded 3124.45 YES
A size error condition exists when, after decimal point alignment, the result is truncated on either
the left or the right hand side. If an arithmetic statement has a rounded phrase then a size error
only occurs if there is truncation on the left hand side (most significant digits).

ADD Examples

Ex.1: ADD Cash TO Total.


Before 3 1000
After 3 1003
Ex.2: ADD Cash, 20 TO Total, Wage.
Before 3 1000 100
After 3 1023 123
Ex.3: ADD Cash, Total GIVING Result.
Before 3 1000 0015
After 3 1003 1003

Ex.4: ADD Males TO Females GIVING TotalStudents.


Before 1500 0625 1234
After 1500 0625 2125

SUBTRACT Examples

Ex.1: SUBTRACT Tax FROM GrossPay, Total.


Before 120 4000 9120
After 120 3880 9000

Ex.2: SUBTRACT Tax, 80 FROM Total.


Before 100 480
After 100 300

Ex.3: SUBTRACT Tax FROM GrossPay GIVING NetPay.


Before 750 1000 0012
After 750 1000 0250

MULTIPLY Examples

Ex.1: MULTIPLY Subs BY Members GIVING TotalSubs


ON SIZE ERROR DISPLAY "TotalSubs too small"
END-MULTIPLY.
Subs Members TotalSubs
Before 15.50 100 0123.45
After 15.50 100 1550.00

Ex.2: MULTIPLY 10 BY Magnitude, Size.


Before 355 125
After 3550 1250

20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

DIVIDE Exception
Syntax:
DIVIDE {Identifier/Literal} INTO {Identifier/Literal}
GIVING {Identifier [ROUNDED]}REMAINDER Identifier
[{ON SIZE ERROR/NOT ON SIZE ERROR} Statement-Block END-DIVIDE]

Ex.1: DIVIDE 201 BY 10 GIVING Quotient REMAINDER Remain.


Before 201 1424
After 020 0001

Ex.2: DIVIDE Total BY Members GIVING Average ROUNDED.


Before 9234.55 100 1234.56
After 9234.55 100 92.35

The COMPUTE
Syntax:
COMPUTE {Identifier [ROUNDED]}... = Arithmetic Expression
[{ON SIZE ERROR/NOT ON SIZE ERROR} Statement-Block END-COMPUTE]

If complex or extensive arithmetic operations are required in a program, the use of the four
arithmetic verbs may prove cumbersome. The COMPUTE verb provides another method of
performing arithmetic. The COMPUTE statement uses the following arithmetic symbols :
+ Add
- Subtract
* Multiply
/ Divide
** exponentiation

Ex.1: COMPUTE TOTAL = AMT1 + AMT2 – AMT3.


To round the results in a COMPUTE statement to the specifications of the receiving field, use the
ROUNDED option directly following the receiving field. If we need to test for a size error
condition we may use the ON SIZE ERROR clause as the last one in the statement.
The sequence in which operations are performed in a COMPUTE statement
**
* or / (whichever appears first from left to right)
+ or – (whichever appears first from left to right)

Ex.2: Compute IrishPrice = SterlingPrice / Rate * 100.


Before 1000.50 156.25 87
After 179.59 156.25 87

21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Editing characters
Edited Pictures are PICTURE clauses which format data intended for output to screen or reports.
Basic picture symbols (9 X A V S).
Editing picture symbols (, B 0 / . + - CR DB $ S Z *)

SENDING RECEIVING
Picture Internal Actual Picture Result
Storage value
PIC 999999 123456 123456 PIC 999,999 123,456
PIC 9(6) 000078 000078 PIC ZZZ,ZZZ 78
PIC 9(6) 000178 000178 PIC ***,*** ****178
PIC 9(6) 002178 002178 PIC ***,*** **2,178
PIC 9(6) 120183 120183 PIC 99/99/99 12/01/83
PIC 999V99 12345 123.45 PIC 999.99 123.45
PIC S999 12L -123 PIC -999 -123
PIC S999 12L -123 PIC 999- 123-
PIC S999 12C +123 PIC -999 123
PIC S9(3) 12C +123 PIC +9(3) +123
PIC S9(3) 12L -123 PIC +9(3) -123
PIC S9(3) 12L -123 PIC 9(3)+ 123-
PIC 9(4) 0080 0080 PIC $$,$$9.00 $80.00
PIC 9(5) 57397 57397 PIC $$,$$9 $7,397
PIC S9(4) 008{ +0080 PIC ++++9 +80
PIC S9(4) 008} -0080 PIC ----9 -80
PIC S9(4) 123D +1234 PIC 9(4)CR 1234
PIC S9(4) 123M -1234 PIC 9(4)CR 1234CR
PIC S9(4) 123D +1234 PIC 9(4)DB 1234
PIC S9(4) 123M -1234 PIC 9(4)DB 1234DB

INITIALIZE

INITIALIZE is used to initialize the data items with its default values in the procedure division.
VALUE clause is used to initialize the data items in the declaration.
Syntax: INITIALIZE IDENTIFIER-1 REPLACING
(ALPHABETIC/ALPHANUMERIC/ALPHA-NUMERIC-EDITED NUMERIC/NUMERIC-EDITED)
DATA BY (IDENTIFIER-2 /LITERAL-2)

INITIALIZE sets the alphabetic, alphanumeric and alphanumeric-edited items to SPACES and
numeric and numeric-edited items to ZERO. To initialize data items other than the default value
use REPLACING option. INITIALIZE statement on FILLER, OCCURS DEPENDING ON items are
not affected.

Ex.1: 01 WS-TOTAL-AMT PIC S9(7)V99.


01 WS-AGENT-NAME PIC X(20).

INITIALIZE WS-TOTAL-AMT WS-AGENT-NAME.

WS-TOTAL-AMT IS INITIALIZED WITH ZEROS AND WS-AGENT-NAME WITH SPACES.


The above statement can be replaced with move statement but it needs two move statements.

MOVE ZEROS TO WS-TOTAL-AMT


MOVE SPACES TO WS-AGENT-NAME

22
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Ex.2: 01 HEADER-LINE1.
05 HDR1-DATE PIC X(08)
05 FILLER PIC X(49) VALUE SPACES.
05 FILLER PIC X(17) VALUE 'ULL AGENT REPORTS'.
05 FILLER PIC X(46) VALUE SPACES.
05 FILLER PIC X(05) VALUE 'PAGE '.
05 HDR1-PAGE-NUM PIC 9(06).

INITIALIZE HEADER-LINE1.

Initialize on group variable moves default values to elementary data items on its data type.
In the above example HDR1-DATE is moved with spaces, HDR1-PAGE-NUM is moved with
zeros and values in the filler items are not affected.

Ex.3: 01 WS-VARIABLES.
05 WS-FLAG1 PIC X(1).
05 WS-FLAG2 PIC X(1).
05 WS-COUNT1 PIC S9(4) COMP.
05 WS-COUNT2 PIC S9(4) COMP.

INITIALIZE WS-VARIABLES REPLACING ALPHANUMERIC DATA BY 'N' NUMERIC DATA BY 1.


Replacing option is used to initialize data items other than its default value.

Move Statement

Rules:
1. Receiving field is refreshed with spaces or zeros on datatype X, A with Spaces and
9's with zeros
2. Default justification on X, A is RIGHT. I.e. Values moves from left to right.
3. Default justification can be changed to RIGHT on X, A
4. On 9's, Integer part takes right justification and decimal part takes left justification
5. Sending field is unchanged

1. Move on Alpha numeric and alphabetic variables

Case1 Case2

01 X PIC X(4) VALUE 'ABCD'. 01 X PIC X(3) VALUE 'ABC'.


01 Y PIC X(3) VALUE 'MNO'. 01 Y PIC X(4) VALUE 'MNOP.

MOVE X TO Y MOVE X TO Y

Before ABCD MNO Before ABC MNOP


After ABCD ABC After ABC ABC
Case3 Case4

01 X PIC X(4) VALUE 'ABCD'. 01 X PIC X(3) VALUE 'ABC'.


01 Y PIC X(3) JUSTFIED RIGHT 01 Y PIC X(4) JUSTIFIED RIGHT
VALUE 'MNO'. VALUE 'MNOP.

MOVE X TO Y MOVE X TO Y

Before ABCD MNO Before ABC MNOP


After ABCD BCD After ABC ABC

23
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

2. Move on numeric variables

Case1 Case2

01 X PIC 9(4) VALUE 1234. 01 X PIC 9(4)V99 VALUE 1234.56.


01 Y PIC 9(4) VALUE 5678. 01 Y PIC 9(4)V99 VALUE 5678.91.

MOVE X TO Y MOVE X TO Y

Before 1234 5678 Before 1234.56 5678.91


After 1234 1234 After 1234.56 1234.56

Case3 Case4

01 X PIC 9(4) VALUE 1234. 01 X PIC 9(3) VALUE 123.


01 Y PIC 9(3) VALUE 567. 01 Y PIC 9(4) VALUE 4567.

MOVE X TO Y MOVE X TO Y

Before 1234 567 Before 123 4567


After 1234 234 After 123 0123

Case5 Case6

01 X PIC 9(3)V99 VALUE 123.45. 01 X PIC 9(2)V9 VALUE 12.3.


01 Y PIC 9(2)V9 VALUE 67.8. 01 Y PIC 9(3)V99 VALUE 456.78.

MOVE X TO Y MOVE X TO Y

Before 123.45 67.8 Before 12.3 456.78


After 123.45 23.4 After 12.3 012.30
Case7 Case8

01 X PIC 9(3)V99 VALUE 123.45. 01 X PIC 9(2)V9 VALUE 12.3.


01 Y PIC 9(5) VALUE 67891. 01 Y PIC 9(3)V99 VALUE 456.78.

MOVE X TO Y MOVE X TO Y

Before 123.45 67891 Before 12.3 456.78


After 123.45 00123 After 12.3 012.30

Valid moves CASE1, CASE2, CASE4, CASE6.

3. Move on Alphanumeric to numeric


This type of move is possible but not recommended. Make sure that X is having
numeric data before it is moved. To make sure use 'IS NUMERIC' condition.

01 A PIC X(3).
01 B PIC 9(3).

IF A IS NUMERIC
MOVE A TO B
ELSE
DISPLAY 'A IS NOT NUMERIC'
END-IF
Justification depends on receiving field. i.e. Right justification.

24
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

4. Move on Numeric to Alphanumeric


It is possible only when numeric variable is unsigned zoned integer.
Numeric should not have assumed sign, assumed decimal, compressed formats.
01 WS-DATE1 PIC 9(8).
01 WS-DATE2 PIC X(8).
MOVE WS-DATE1 TO WS-DATE2.  It is recommended

01 A PIC S9(3)V99.
01 B PIC X(5).
MOVE A TO B.  It is not recommended

01 A PIC S9(3)V99 COMP-3.


01 B PIC X(5).
MOVE A TO B.  It is not recommended

Different Types of Move


Elementary Move
Elementary move with reference modification
Group Move
Group Move with corresponding

Elementary move
Ex.1: 05 GROSS-PAY PIC 9(6)v99 VALUE 36000.00.
05 TOTAL-AMOUNT PIC 9(6)V99.
MOVE GROSS-PAY TO TOTAL-PAY.
Ex.2: 01 IN-REC PIC X(30).
01 OUT-REC PIC X(30).
MOVE IN-REC TO OUT-REC.

Elementary move with reference modification


It moves partial data into receiving field. Other part of the receiving field is unchanged.
Ex: MOVE IN-REC(1:20) TO OUT-REC(11:20)
Here first 20 chars of in-rec are moved to last 20 chars of out-rec and the first 10 chars of out-rec
are unchanged.

Group move
Ex: 01 WS-DATE1.
05 WS-DATE-CCYY PIC X(4).
05 WS-DATE-MM PIC X(2).
05 WS-DATE-DD PIC X(2).
01 WS-DATE2.
05 WS-DATE-CCYY PIC 9(4).
05 WS-DATE-MM PIC 9(2).
05 WS-DATE-DD PIC 9(2).
MOVE WS-DATE1 TO WS-DATE2.

25
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Group Move with corresponding


Syntax: MOVE {CORRESPONDING/CORR} group-item-1 TO group-item-2
It is used to move one group to another group even though the structure of the two groups are not
same. It is used to reduce the number of move statement. It moves elementary items with same
name and leaves other elements.

Ex: 01 IN-REC.
05 EMP-NUM PIC x(4).
05 EMP-NAME PIC x(10).
05 EMP-DOJ.
10 EMP-DOJ-CCYY PIC 9(4).
10 EMP-DOJ-MM PIC 9(2).
10 EMP-DOJ-DD PIC 9(2).
05 EMP-SAL PIC S9(6)V99.

01 DETAIL-REC.
05 EMP-NUM PIC x(4).
05 FILLER PIC x(2) VALUE SPACES.
05 EMP-NAME PIC x(10).
05 FILLER PIC x(2) VALUE SPACES.
05 EMP-DOJ.
10 EMP-DOJ-MM PIC 9(2).
10 FILLER PIC X(1) VALUE '/'.
10 EMP-DOJ-DD PIC 9(2).
10 FILLER PIC x(1) VALUE '/'.
10 EMP-DOJ-CCYY PIC 9(4).
05 TOTAL-SALARY PIC ZZZZZZ.99.

Above two structures are not same so simple group move cannot move elementary to elementary.
MOVE CORRESPONDING IN-REC TO DETAIL-REC.
It reduces number of individual elementary moves. Total-salary is not having a matching name in
the sending structure then it is untouched in the receiving structure.

Conditional verbs

IF and Evaluate are conditional verbs. These are used to conditionally execute statements.
IF statement
The most famous decision making statement in all language is 'IF'. It has the following keywords
IF/THEN/ELSE/END-IF.

General Syntax of IF statement:


IF CONDITION THEN
STATEMENT1/CONTINUE/NEXT SENTANCE
ELSE
STATEMENT2
END-IF

‘THEN’ is a Noise word and it is optional.

Continue/Next Sentence
Both are used when if is empty. Without statement in the IF, ELSE cannot be used. To fulfill IF
statement Continue or next sentence are used. Continue executes next logical statement where
Next sentence executes statement after period. In this situation Continue or Next Sentence can
be used.

26
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Case1 Case2 Case3 Case4


IF condition THEN IF condition IF condition IF condition
statement1 statement1 continue Next Sentance
ELSE ELSE ELSE ELSE
statement2 statement2 statement1 statement1
END-IF END-IF END-IF END-IF

statement2. statement2.
statement3. statement3.
Case5 Case6 Case7
IF condition1 and/or condition2 IF condition1 IF condition1
statement1 statement1 statement1
ELSE ELSE ELSE
statement2 IF condition2 IF condition2
END-IF statement2 statement2
ELSE ELSE
IF condition3 IF condition3
statement3 statement3
ELSE ELSE
statement4 statement4.
END-IF
END-IF
END-IF

1. CASE2, Then used in Case1 is a noisy word, so this can be omitted as shown in Case2.
2. If there are no statements in the IF part of the condition then Continue/Next sentence
can be used. Continue executes next logical statement and Next sentence executes
statement after the period.
In case3, if the condition is true then it will execute statement2.
In case4, if the condition is true then it will statement3.
3. Case5, multiple conditions can be coded with AND/OR logical operations.
4. Case6, Nested if statements can be coded. Nested IF statements can be replaced with
EVALUATE statement for better readability.
5. Case7, all trailing END-IF statements can be closed with a period.

Ex for Case6 Ex for Case7


IF GENDER = 'F' IF GENDER = 'F'
MOVE 50.00 TO BONUS-PERCENT MOVE 50.00 TO BONUS-PERCENT
ELSE ELSE
IF GENDER = 'M' IF GENDER = 'M'
MOVE 30.00 TO BONUS-PERCENT MOVE 30.00 TO BONUS-PERCENT
ELSE ELSE
IF GENDER = 'C' IF GENDER = 'C'
MOVE 20.00 TO BONUS-PERCENT MOVE 20.00 TO BONUS-PERCENT
ELSE ELSE
DISPLAY 'INVALID GENDER' DISPLAY 'INVALID GENDER'.
END-IF
END-IF
END-IF

27
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Evaluate statement
With COBOL85, EVALUATE verb can be used to implement the SWITHC CASE structure of
other languages. Multiple IF statements can be efficiently and effectively replaced with EVALUATE
statement.
General Syntax:
EVALUATE subject1 (ALSO subject2…)
WHEN object1 (ALSO object2..)
WHEN object3 (ALSO object4..)
WHEN OTHER imperative statement
END-EVALUATE.

1. Evaluate is similar to SWITCH CASE statement in C language.


2. Evaluate statement is used to replace nested if statements.
3. When conditions in evaluate statement executes from top to bottom.
4. If any when condition is true then other when conditions will be bypassed.
5. Code the most occurring when condition on top of the other when conditions.
6. If none of the when condition are true then it executes statements coded in WHEN OTHER
condition.
7. WHEN OTHER is optional, so it can be omitted.
8. Continue/Next Sentence cannot be used in WHEN OTHER condition.

There are three types of evaluate statements.

Type1 Type2 Type3


EVALUATE Variable (or) EVALUATE TRUE/FALSE EVALUATE TRUE/FALSE ALSO TRUE/FALSE
(Arithmetic Exp) WHEN condition1 WHEN condition1 ALSO condition2
WHEN value1 Statement1 Statement1
Statement1 WHEN condition1 WHEN condition2 ALSO condition3
WHEN value2 Statement2 Statement2
Statement2 WHEN condition1 WHEN condition4 ALSO condition5
WHEN value3 Statement3 Statement3
Statement3 END-EVALUATE END-EVALUATE
WHEN OTHER
Statement4
END-EVALUATE

Ex:
01 AGENT-REC.
.
.
05 GENDER PIC X(1).
88 FEMALE VALUE 'F'.
88 MALE VALUE 'M'.
88 CORPORATE VALUE 'C'.
05 MARITAL-STATUS PIC X(1).
88 MARRIED VALUE 'M'.
88 UN-MARRIED VALUE 'U'.
88 DIVORCED VALUE 'D'.
88 WIDOW VALUE 'W'.
88 SINGLE VALUES 'U', 'D', 'W'.

28
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Ex for Method1 Ex for Method2

EVALUATE GENDER EVALUATE TRUE


WHEN 'F' WHEN GENDER = 'F'
MOVE 50.00 TO BONUS-PERCENT MOVE 50.00 TO BONUS-PERCENT
WHEN 'M' WHEN GENDER = 'M'
MOVE 30.00 TO BONUS-PERCENT MOVE 30.00 TO BONUS-PERCENT
WHEN 'C' WHEN GENDER = 'C'
MOVE 20.00 TO BONUS-PERCENT MOVE 20.00 TO BONUS-PERCENT
END-EVALUATE

Ex for Method2 with 88 level condition Ex for Method3 with 88 level condition
EVALUATE TRUE EVALUATE TRUE ALSO TRUE
WHEN FEMALE WHEN FEMALE ALSO MARRIED
MOVE 50.00 TO BONUS-PERCENT MOVE 50.00 TO BONUS-PERCENT
WHEN MALE WHEN MALE ALSO MARRIED
MOVE 30.00 TO BONUS-PERCENT MOVE 40.00 TO BONUS-PERCENT
WHEN CORPORATE WHEN FEMALE ALSO SINGLE
MOVE 20.00 TO BONUS-PERCENT MOVE 40.00 TO BONUS-PERCENT
END-EVALUATE WHEN MALE ALSO SINGLE
MOVE 30.00 TO BONUS-PERCENT
END-EVALUATE

Different types of Conditions

1. Relational condition
2. Class Condition
3. Sign condition
4. Condition name condition

Relational condition
It uses relational operators given below
'=', '<', '>', 'NOT =' '<=' '>=‘ these can be used with combination of logical operators
'OR' 'AND' 'NOT'
Ex: IF POLICY-STATUS = 'A'
IF SALES-AMOUNT > 0
IF ACT-BAL NOT = 0

SIGN condition
It is used to check the sign of a data item. it is used only on numeric items.
Syntax: IF identifier is POSITIVE/NEGATIVE/ZERO

Ex: IF SALES-AMOUNT IS POSITIVE


IF ACT-BAL IS NEGATIVE
IF PREMIUM-AMOUNT IS ZERO

But this sign condition can be replaced with relational condition as shown below.

IF SALES-AMOUNT > 0
IF ACT-BAL < 0
IF PREMIUM-AMOUNT = 0

29
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

CLASS condition
It is used to check the content of data item against pre-defined range of values. It can be done as
follows IF identifier IS NUMERIC/ALPHABETIC/ALPHABETIC-HIGHER/ALPHABETIC-LOWER
Ex:
IF WS-DATE IS NUMERIC
Continue
ELSE
GO TO PARA-EXIT
END-IF.
Class condition is extensively used to avoid S0C7 abend.

How to avoid S0C7 abend with Class condition


COMPUTE WS-COMM-AMOUNT = IN-SALES-AMT * COMM-PERCENT
In the above statement, In-sales-amt is a field of input record. If it has non numeric data,
then it will fail with S0C7 abend. S0C7 abend can be avoided with the below statement.
IF IN-SALES-AMT IS NUMERIC
COMPUTE WS-COMM-AMOUNT = IN-SALES-AMT * COMM-PERCENT
ELSE
GO TO EXIT-PARA
END-IF

Condition names or 88 Level


88 level is called condition names and it is used to give a name to a value of a field. It increases
business meaning for a field value.
05 POLICY-TYPE PIC X(1).
Based on the value of the policy-type a specific code is being executed like it is shown below.

EVALUATE POLICY-TYPE
WHEN '1'
PERFORM PARA1
WHEN '2'
PERFORM PARA2
WHEN '3'
PERFORM PARA3
WHEN OTHER
DISPLAY 'INVALID POLICY TYPE:' POLICY-TYPE
END-EVALUATE

Policy-Type can have values 1, 2, 3. Where 1 stands for individual policy, 2 for Family-policy, 3
for corporate policy. If the above code is reviewed by someone then it is difficult to understand
the meaning of the policy-type. If the condition names used then it increases the meaning as
shown below.
05 POLICY-TYPE PIC X(1).
88 INDIVIDUAL-POLICY VALUE '1'.
88 FAMILY-POLICY VALUE '2'.
88 CORPORATE-POLICY VALUE '3'.

EVALUATE TRUE
WHEN INDIVIDUAL-POLICY
PERFORM PARA1
WHEN FAMILY-POLICY
PERFORM para2
WHEN CORPORATE-POLICY
PERFORM PARA3
WHEN OTHER
DISPLAY 'INVALID POLICY TYPE:' POLICY-TYPE
END-EVALUATE

30
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Advantages of 88 Level
1. It increases readability for the business codes
2. It reduces coding when multiple values are to be checked
One or more values can be given to 88 level.

Ex.1: 05 MARITAL-STATUS PIC X(1).


88 UN-MARRIED VALUE 'U'.
88 MARRIED VALUE 'M'.
88 DIVORCEE VALUE 'D'.
88 WIDOW VALUE 'W'.
88 SINGLE VALUES 'U', 'D', 'W'.

How to move values to group variable of 88 Level ?


Value for the group variable can be given in two ways.
1. MOVE 'M' to MARITAL-STATUS
2. SET MARRIED to TRUE
Note: SET to FALSE is not applicable.

If the 88 level with multiple values is set to true then first value is set. SET Single to TRUE. Then
marital-status gets value 'U'.

How to use group variable or 88 condition name in IF condition


Method1 Method2
Ex.1 Ex.1
IF MARITAL-STATUS = 'M' IF MARRIED
MOVE 10.00 TO BONUS-PERCENT MOVE 10.00 TO BONUS-PERCENT
END-IF END-IF

Ex. 2 Ex.2
IF MARITAL-STATUS = 'U' OR IF SINGLE
'D' OR MOVE 05 TO BONUS-PERCENT
'W' END-IF
MOVE 05 TO BONUS-PERCENT
END-IF

Ex.2: 05 STATE-CODE PIC X(2).


88 ANDHRA-PRADESH VALUE 'AP'.
88 ARUNACHALA-PRADESH VALUE 'AR'.
.
.
88 CHATHIS-GHAD VALUE 'CH'.
88 KARNATAKA VALUE 'KA'.
88 KERALA VALUE 'KE'.
88 ORISSA VALUE 'OR'.
88 TAMIL-NADU VALUE 'TN'.
88 SOUTHERN-STATES VALUES 'AP','CH', 'KA', 'OR', 'TN'.
88 UNION-TERITTORIES VALUES 'GO', 'ND', 'DD'.

Ex.3: 05 AGENT-GENDER PIC X(1).


88 MALE VALUE 'M'.
88 FEMALE VALUE 'F'.
88 CORPORATE VALUE 'C'.
88 INDIVIDUAL VALUES 'M', 'F'.

31
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Ex.4: 05 SUBJECT-MARKS PIC 9(3).


88 FAIL VALUES ARE 1 THRU 34.
88 PASS VALUES ARE 35 THRU 100.
88 FIRST-CLASS VALUES ARE 60 THRU 69.
88 DISTINCTION VALUES ARE 70 THRU 100.

ACCEPT/DISPLAY verbs

Accept
Accept is used in two situations.
1. To accept the instream data given in the SYSIN of the run JCL into a program variable.
Syntax: ACCEPT IDENTIFIER
Ex: 01 WS-COUNTRY-CODE PIC X(3).
ACCEPT WS-COUNTRY-CODE

//SYSIN DD *
IND
/*
The above code is used to pass the control information to the program. If some wants to process
input records based on the country code passed from the SYSIN of the JCL. Maximum of 80
characters can be accepted into a single accept statement. One line in SYSIN is accepted into a
single ACCEPT statement. More than one line can be given in SYSIN, however each line should
have one accept statement. Alphanumeric data and numeric data without sign can be accepted
from SYSIN. Whereas Numeric with SIGN and Numeric items with Compressed formats cannot
be accepted. This type of ACCEPT is rarely used in real-time. Instead of this PARM is used in
real-time.
2. To accept system date and system time into a program variable.

01 DATE-YYMMDD PIC 9(6).


01 DATE-OF-YEAR.
05 YY PIC 9(2).
05 DDD PIC 9(3).
THE ABOVE ONE IS A JULIAN DATE.

01 WEEK-DAY PIC 9(1).


MONDAY is 1
TUESDAY is 2
.
SUNDAY IS 7

01 TIME-HHMMSSSS PIC 9(8).

FIRST TWO CHARS HH IT IS HOURS


NEXT TWO CHARS MM IT IS MINUTES
NEXT TWO CHARS SS IT IS SECONDS
NEXT TWO CHARS SS IT IS MILLI SECONDS

ACCEPT DATE-YYMMDD FROM DATE.


ACCEPT DATE-OF-YEAR FROM DAY.
ACCEPT WEEK-DAY FROM DAY-OF-WEEK.
ACCEPT TIME-HHMMSSSS FROM TIME.

32
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

DISPLAY
Syntax: DISPLAY {IDENTIFIER..} {LITERAL}

It is used to display literals or value of identifiers. Display items can be found in the spool in the
sysout of run job. In the below situation display is used.

1. To display descriptions at the time of error situations.


2. To display program statistics before stop run.
3. It is used to debug the program when debug tools are not available. It is done by putting
display statements in the program navigation.
4. Displays can be used extensively at the time of testing but remove unwanted display
statements before finalizing code.

Few examples
DISPLAY 'PROGRAM STARTED'
DISPLAY 'ACCOUNT NOT FOUND IN ACCOUNT MASTER:' IN-ACCT-NUM
DISPLAY 'TOTAL NUMBER OF TRXS PROCESSED' WS-PROCESS-TOTAL
DISPLAY 'TOTAL NUMBER OF TRXS ERRORED ' WS-ERROR-TOTAL

Perform

Perform is used to execute a group of statements given in a paragraph.


Paragraphs are used to code group of statements.

Advantages
1. To Achieve Top Down approach
2. To reduce redundant code executes from different locations of the same program.
Place redundant code in a Para and perform it from multiple locations.
3. To Achieve iterations. To execute a Para multiple times conditionally or number of
times unconditionally.
4. To loop through internal table (Arrays).

Paragraph Rules
1. Para name should have maximum of 30 Chars
2. Close Para name with a period
3. The last statement of the Para should be coded with period
4. Para ends before next Para starts or end of the program
5. Para's should be started after the main statements in the procedure division
6. Code EXIT statement when there are no statements in a paragraph.

Various Performs
1. Simple Perform
2. Perform with THRU
3. Perform with Times
4. Perform with Until
5. Perform with Varying and Until
6. Inline Perform
7. Perform with Until Test before/Test after

33
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

1. Simple perform
Syntax1:
PERFORM PARA1.
Stmt4
PARA1.
Stmt1
Stmt2
Stmt3.
In example Perform executes statements in Para1 and then executes Stmt4.
Ex: PERFORM INITIALIZE-PARA.
INITIALIZE-PARA.
OPEN INPUT IN-FILE
OUTPUT OUT-FILE.
INITIALIZE WS-TOTAL
WS-BALANCE
WS-COUNT.

2. Perform with THRU option


Syntax: PERFORM para1 thru para2.

Case1 Case2 Case3

Perform Para1 thru para2 GO TO Para1. Perform Para1 thru para1-exit.


stmt10 stmt10 Perform Para2 thru para2-exit.
STOP RUN. STOP RUN. stmt7
STOP RUN.
Para1. Para1.
Stmt1 Stmt1 Para1.
Stmt2 Stmt2 Stmt1
Stmt3. Stmt3. Stmt2
Stmt3.
Para2. Para2. Para1-exit.
Stmt4 Stmt4 exit.
Stmt5 Stmt5
Stmt6. Stmt6. Para2.
Stmt4
Para3. Para3. Stmt5
Stmt7 Stmt7 Stmt6.
Stmt8 Stmt8 Para2-exit.
Stmt9. Stmt9 exit.

In Case1, Perform executes statements in Para1, Para2 and Para3 then it executes Stmt10
In Case2, Perform executes statements in Para1, Para2 and Para3 and it won't come back to
Stmt10.
In Case3, It is most used perform. In most of the real applications exit Para is used to find the end
of the paragraph and also to use GO TO statement to the exit Para.
Exit Paras are not coded with any statements, so it is better to code EXIT statement.
Ex: PERFORM INITIALIZE-PARA THRU INITIALIZE-EXIT.
INITIALIZE-PARA.
OPEN INPUT IN-FILE
OUTPUT OUT-FILE.
INITIALIZE WS-TOTAL
WS-BALANCE
WS-COUNT.
INITIALIZE-EXIT.
EXIT.

34
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

3. Perform with TIMES option


Syntax: PERFORM para1 N times.

Case1 Case2

Perform Para1 5 times move 3 to N


Stmt4 Perform Para1 N times ->Executes 3 times only
Stmt4

Para1. Para1.
Stmt1 Stmt1
Stmt2 Stmt2
Stmt3. Stmt3
MOVE 5 TO N.

In Case1, Perform executes statements in Para1 5 times and then executes Stmt4.
In Case2, Perform executes statements in Para1 3 times. Even though N is modified in the Para1,
perform takes the initial value of N.
Ex: PEFORM WRITE-PARA 5 TIMES.
WRITE-PARA.
MOVE SPACES TO OUT-REC
WRITE OUT-REC.

4. Perform with UNTIL option


Syntax: PERFORM para1 until condition.
(It will executes for false condition and stops for true condition)
Ex:
PROCEDURE DIVISION.
PERFORM 100000-INITIALIZE THRU 100000-EXIT.
PERFORM 200000-PROCESS THRU 200000-EXIT UNTIL WS-STATUS = '10'
PERFORM 300000-TERMINATE THRU 300000-EXIT.
STOP RUN.

100000-INITIALIZE.
OPEN INPUT IN-FILE
OUTPUT OUT-FILE.
100000-EXIT.
EXIT.

200000-PROCESS .
READ IN-FILE
IF WS-STATUS = '10'
GO TO 200000-EXIT.  GO TO is recommended only when THRU option is used
 GO TO is always used to the exit para
 It is used to skip the process for a given condition
 It increases readability
IF EMP-STATUS = 'T'
GO TO 200000-EXIT.
.
200000-EXIT.
EXIT.

300000-TERMINATE
CLOSE IN-FILE
OUT-FILE.
300000- EXIT.
EXIT.

35
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Different points that can be noted down with the above example.
1. Top down approach is achieved. i.e. Performs are coded after procedure division and
paragraphs are expanded after the main statements.
2. Paragraph name are coded with numbers in lacks. It is a standard in most of real applications.
3. Use Para name 110000- if the Para called from 100000-. With this naming conversion, Paras
can be coded up to 6 levels down.
4. Every paragraph is coded with its exit paragraph. Exit paragraph is coded with the same
number used for the main paragraph. With this naming conversion, it is easy to find the end of
the paragraph and also to skip the code on a given conditions.
5. 200000-PROCESS is a main process and it is executed conditionally until end of input file is
reached.

5. Perform with VARYING and UNTIL option


Syntax: PERFORM PARA1 VARYING IDENTIFIER1 FROM IDENTIFIER2/LITERAL1
BY INDENTIFIER3/LITERAL2 UNTIL CONDITION
Initialize IDENTIFIER1with IDENTIFIER2 and test the condition. If the condition is false
execute the statements in para1 thru Para-n and increment IDENTIFIER1 by IDENTIFIER3
and check the condition(s) again. If the condition is again false, repeat this process till the
condition is satisfied.
Ex: PERFORM MONTHLY-EARNS VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10

MONTHLY-EARNS.
ADD EARNS-TABLE(WS-COUNT) TO WS-TOTAL.

6. Inline Perform.
Inline perform is used to execute statements coded with in Perform and End-Perform.
Scope terminator END-PERFORM is mandatory for inline perform. It cannot be with a period.
It is mainly used to process Cobol internal tables (Arrays).
Syntax: PERFORM
STATEMENT1
STATEMENT2
END-PERFORM

Ex: Inline Perform with Varying and Until


Find the actual length of the name by removing trailing spaces.
MOVE 'N' TO STOP-LOOP
PERFORM VARYING WS-COUNT FROM 40 BY -1 UNTIL WS-COUNT < 1
OR STOP-LOOP = 'Y'
IF WS-NAME(WS-COUNT:1) > SPACE
MOVE 'Y' TO STOP-LOOP
DISPLAY 'ACTUAL LENGTH OF NAME ' WS-COUNT
END-IF
END-PERFORM

36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

7. Perform With Test Before/After


Syntax: PERFORM PARA-1 WITH TEST BEFORE/AFTER UNTIL CONDITION(S).
WITH TEST BEFORE, condition is checked first and if it found false, then PARA-1 is executed
and this is the default.(functions like DO-WHILE)
WITH TEST AFTER, PARA-1 is executed once and then the condition is checked.
(functions LIKE DO-UNTIL)

Ex:
PERFORM VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10  Executes 10times
stmt1
stmt2
END-PERFORM

PERFORM VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10 TEST AFTER  Executes
stmt1 11times
stmt2
END-PERFORM

Difference between Perform and GO TO


Perform executes a Para and come back to the next statement after the perform
GO TO starts executing given PARA and all Paras till end of the program.
GO TO jump to the Para and will never comeback
GO TO is highly recommended when used with perform THRU option

EXIT statement
It is a COBOL reserved word that performs no operation. It is used to allow execution to pass
over other statements or to transfer control back to the statement following the original
PERFORM. It is used, when necessary, as an end point in a paragraph.
If it is used other statements cannot be used in the paragraph. It is coded in the Para-exit as a
single statement.

37
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Occurs/Table handling

When the similar variables are repeated on the same purpose in a continuous memory location,
then occurs can be used to reduce number of variables.
It is similar to Arrays in other languages.
Syntax:
(level-number 02-48) identifier OCCURS N TIMES
{ASCENDING/DESCENDING KEY IS data-name-2}
{INDEXED BY index-name-1}
Limitations
1. It cannot be declared in 01, 66, 77,88 levels
2. It can be defined at sub elementary or a sub group level
3. Value clause can be given on occurs level with 'VALUE ALL' clause
4. Data names below occurs level should not have value clause
5. In COBOL, occurs starts from 1 where as in other languages it starts from 0.
6. In COBOL 85 standard, table can be declared up to 7 levels but it is not recommended
beyond 3 levels.
Occurs cannot be declared at 01 or 77 level because it is to repeat fields within the record but not
to repeat record itself

Method1: Declaration without Occurs


05 PROD-DETAILS1.
10 PROD-CODE1 PIC X(4)
10 PROD-PRICE1 PIC S9(5)V99.

05 PROD-DETAILS2.
10 PROD-CODE2 PIC X(4)
10 PROD-PRICE2 PIC S9(5)V99.

05 PROD-DETAILS3.
10 PROD-CODE3 PIC X(4)
10 PROD-PRICE3 PIC S9(5)V99.
..
..
05 PROD-DETAILS10.
10 PROD-CODE10 PIC X(4)
10 PROD-PRICE10 PIC S9(5)V99.

Method2: Declaration with Occurs


05 PROD-DETAILS OCCURS 10 TIMES.
10 PROD-CODE PIC X(4)
10 PROD-PRICE PIC S9(5)V99.

In Method1, more number of variables are declared.


In Method2, less number of variables are declared.
Both Method1 and Method2 occupy the same memory. Occurs is used to reduce number of
variable but not to reduce memory.

38
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

How to get the product price of the input product code in Method1
EVALUATE TRUE
WHEN IN-PROD-CODE = PROD-CODE1
MOVE PROD-PRICE1 TO WS-PRICE
WHEN IN-PROD-CODE = PROD-CODE2
MOVE PROD-PRICE2 TO WS-PRICE
.
.
WHEN IN-PROD-CODE = PROD-CODE10
MOVE PROD-PRICE1. TO WS-PRICE
WHEN OTHER
DISPLAY 'Product price not found for product:' IN-PROD-CODE
END- EVALUATE

How to get the product price of the input product code in Method2
MOVE 'N' TO STOP-LOOP
PERFORM VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10 OR
STOP- LOOP = 'Y'
IF IN-PROD-CODE = PROD-CODE(WS-COUNT)
MOVE PROD-PRICE(WS-COUNT) TO WS-PRICE
MOVE 'Y' TO STOP-LOOP
END-IF
END-PERFORM
IF STOP-LOOP = 'N'
DISPLAY 'Product price not found for product:' IN-PROD-CODE
END-IF

Advantages of occurs
1. To reduce the number of variables
2. To ease the coding with looping through the table using inline perform
3. To search elements faster using SEARCH or SEARCH ALL
4. With occurs depending clause, memory can be saved in a file. In this case file becomes a
variable lengthed records.
Ex: 1. Employee children info occurs 1 to n times depending on another field number of
children in the same record
2. Policy coverages info occurs 1 to n times depending on another field number of
coverages in the same record
5. When sequential file is to be searched on a field then load the file it into table and search table.
Ex: Conversion rates for different currency codes in a file and get the conversion rates
to process data in another file
Note: Occurs reduces number of variables but memory is not reduced

How to use an element of occurs


05 PROD-DETAILS OCCURS 10 TIMES.
10 PROD-CODE PIC X(4)
10 PROD-PRICE PIC 9(5)V99.

Display PROD-DETAILS (1)


Display PROD-DETAILS(WS-COUNT)
Display PROD-DETAILS(WS-COUNT + 1)

Display PROD-CODE(1)
Display PROD-PRICE(1)
Subscript should be any numeric integer field.
Note: Field at occurs level and fields below occurs level cannot be used without subscript

39
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

How to display all elements of table


PERFORM VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10
DISPLAY PROD-CODE(WS-COUNT)
DISPLAY PROD-PRICE(WS-COUNT)
END-PERFORM

How to search a table


Method 1:
PERFORM VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10

IF IN-PROD-CODE = PROD-CODE(WS-COUNT)
MOVE PROD-PRICE(WS-COUNT) TO WS-PRICE
END-IF

END-PERFORM

Method 2:
PERFORM VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10
IF IN-PROD-CODE = PROD-CODE(WS-COUNT)
MOVE PROD-PRICE(WS-COUNT) TO WS-PRICE
MOVE 10 TO WS-COUNT
END-IF
END-PERFORM

Method 3:
MOVE 'N' TO STOP-LOOP
PERFORM VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10 OR
STOP- LOOP = 'Y'
IF IN-PROD-CODE = PROD-CODE(WS-COUNT)
MOVE PROD-PRICE(WS-COUNT) TO WS-PRICE
MOVE 'Y' TO STOP-LOOP
END-IF
END-PERFORM
IF STOP-LOOP = 'N'
DISPLAY 'PRODUCT NOT FOUND:' IN-PROD-CODE
END-IF

In Method1, the loop is not stopped after the matching element is found
In Method2 and Method3, the loop is stopped after matching element is found
However Method3 is always a better coding because in this method one can find whether
matching element is found or not.

How to load a table


PERFORM VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10
ACCEPT PROD-DETAILS (WS-COUNT)
END-PERFORM

Different ways to assign values to occurs at declaration


Method 1: 'Value ALL'
Ex: 05 TBL1 PIC 9(3) OCCURS 10 TIMES VALUE ALL 100.
All elements are initialized with 100.

40
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Method 2: Value clause on Group field above occurs level


Ex: 01 MONTH-GROUP VALUE
'01JAN02FEB03MAR04APR05MAY06JUN07JUL08AUG09SEP10OCT11NOV12DEC'.
05 MONTH-TABLE OCCURS 12 TIMES.
10 MONTH-NUM PIC 9(2).
10 MONTH-NAME PIC X(3).
It is not suggestible when the value is going bigger. Use method 3 instead of method2.

Method 3: Occurs with redefines


Ex:
01 MONTH-GROUP.
05 FILLER PIC X(5) VALUE '01JAN'.
05 FILLER PIC X(5) VALUE '02FEB'.
05 FILLER PIC X(5) VALUE '03MAR'.
05 FILLER PIC X(5) VALUE '04APR'.
05 FILLER PIC X(5) VALUE '05MAY'.
05 FILLER PIC X(5) VALUE '06JUN'.
05 FILLER PIC X(5) VALUE '07JUL'.
05 FILLER PIC X(5) VALUE '08AUG'.
05 FILLER PIC X(5) VALUE '09SEP'.
05 FILLER PIC X(5) VALUE '10OCT'.
05 FILLER PIC X(5) VALUE '11NOV'.
05 FILLER PIC X(5) VALUE '12DEC'.
01 MONTH-GROUP1 REDEFINES MONTH-GROUP.
05 MONTH-TBL OCCURS 12 TIMES.
10 MONTH-NUM PIC 9(2).
10 MONTH-NAME PIC X(3).
Values given in each filler is assigned to each occurrence of the MONTH-TBL.

Ex: Use above table


01 WS-DATE1 VALUE '20111203'.
05 CCYY1 PIC 9(4).
05 MM1 PIC 9(2).
05 DD1 PIC 9(2).
01 WS-DATE2.
05 MM2-DESC PIC X(3).
05 FILLER PIC X(1) VALUE '-'.
05 DD2 PIC 9(2).
05 FILLER PIC X(1) VALUE '-'.
05 CCYY2 PIC 9(4).

MOVE MONTH-NAME(MM1) TO MM2-DESC


MOVE DD1 TO DD2
MOVE CCYY1 TO CCYY2
WS-DATE2 is DEC-03-2011

Using Index
Search
Search is faster than manual looping.
05 PROD-DETAILS OCCURS 10 TIMES INDEXED BY INDX1.
10 PROD-CODE PIC X(4)
10 PROD-PRICE PIC 9(5)V99.
SET INDX TO 1
SEARCH PROD-DETAILS
AT END 'DISPLAY PRODUCT NOT FOUND;'
WHEN PROD-CODE(INDX1) = PARM-PROD-CODE
DISPLAY PROD-PRICE(INDX1)
END-SEARCH.

41
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Search all
If a table is declared with ascending/descending clause then it can be used for SEARCH ALL
(binary search) which is much faster than Search. To search an occurs with 1000 elements, it
takes maximum of 1000 iterations to get a matching element with SEARCH verb and 10
iterations with SEARCH ALL verb. Maximum iterations in search all is N from next nearest 2^N.
Occurs with 1000 elements takes maximum of 10 iterations and occurs with 300 elements takes
maximum of 9 iterations. Next nearest 2 power for 1000 is 1024 and it is 2^10
Next nearest 2 power for 300 is 512 and it is 2^9
It is programmers responsibility to sort the table on given keys before it is used for Search All.
Otherwise it may return incorrect results. Sorting can be done with bubble sort or insertion sort
or shuttle sort techniques.
05 PROD-DETAILS OCCURS 10 TIMES ASCENDING KEY IS PROD-CODE
INDEXED BY INDX1.
10 PROD-CODE PIC X(4)
10 PROD-PRICE PIC 9(5)V99.
SEARCH ALL PROD-DETAILS
AT END 'DISPLAY PRODUCT NOT FOUND;'
WHEN PROD-CODE(INDX1) = PARM-PROD-CODE
DISPLAY PROD-PRICE(INDX1)
END-SEARCH.
Note: If the table elements are not in ascending/descending order as specified in the table
declaration, then it will lead to incorrect results.

Indexed table can also be used with subscript


Note: Although table is declared with index, a subscript can also be used to in place of index.
Vice versa is not possible.
MOVE 'N' TO STOP-LOOP
PERFORM VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 10 OR
STOP-LOOP = 'Y'
IF IN-PROD-CODE = PROD-CODE(WS-COUNT)
MOVE PROD-PRICE(WS-COUNT) TO WS-PRICE
MOVE 'Y' TO STOP-LOOP
END-IF
END-PERFORM
IF STOP-LOOP = 'N'
DISPLAY 'PRODUCT NOT FOUND:' IN-PROD-CODE
END-IF

Difference between SUBSCRIPT and INDEX

Subscript Index

1. Working Storage item. 1. It is not a working-storage item. It takes


implicit declaration.
2. It says occurrence of an element. 2. It says the displacement of an element from
start of the table.
3. Occurrence, in turn translated to 3. Faster and efficient.
displacement to access elements and
so slower than INDEX access.
4. Subscript can be modified with 4. INDEX can only be modified with SET verb.
move or arithmetic statement
5. Cannot be searched with manual loop 5. Can be used with Search/Search All verb.
with perform statement

42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Difference between Search and Search All

SEARCH SEARCH ALL

1. Sequential/Linier SEARCH. 1. Binary Search.


2. Table should have INDEX. 2. Table should have INDEX with ASC/DESC
3. Table need not be in SORTED order. 3. Table should be in sorted order of the
searching argument. There should be
ASCENDING/DESCENDING Clause.
4. Multiple WHEN conditions can be coded. 4. Only one WHEN condition can be coded.
5. Any logical comparison is possible in 5. Only EQUL sign is possible on Key field
WHEN condition
6. Index should be set to 1 before using 6. Index need not be set to 1 before using
SEARCH. SEARCH ALL.
7. Prefer when the table size is small. 7. Prefer when the table size is Significantly
large.

Dynamic OCCURS
Dynamic array is the array whose size is decided during runtime just before the access of first
element of the array.
How to declare dynamic occurs
Ex1:
01 EMP-REC.
05 EMP-NUM PIC X(4).
05 EMP-NAME PIC X(20).
05 EMP-DOJ PIC X(8).
05 EMP-CHILD-STATUS PIC X(1).
05 EMP-CHILDREN-NUM PIC 9(1).
05 EMP-CHILDREN-INFO OCCURS 1 TO 5 TIMES
DEPENDING ON EMP-CHILDLREN-NUM.
10 CHILD-NAME PIC X(20).
10 CHILD-AGE PIC 9(2).
10 CHILD-DOB PIC X(8).
Here number of EMP-CHILDREN-INFO buckets are created based on the value on the field
EMP-CHILDLREN-NUM. This record becomes a variable lengthen record because each record
length varies number of children.
Length of the record = 4 bytes used for variable length + Fixed record area +
value in depending field * record Size in the occurs
Minimum length of the record = 4 + 34 + (1 * 30) = 64
Maximum length of the record = 4 + 34 + (5 * 30) = 184
Ex2:
01 AGENT-LICENSE-REC.
05 AGENT-NUM PIC X(10).
05 LICENSE-NUMBER PIC X(10).
05 NUMBER-OF-LICENSES PIC 9(2).
05 STATE-LICENSE OCCURS 1 TO 54 TIMES DEPENDING ON
NUMBER-OF-LICENSES.
10 STATE-CODE PIC X(2).
10 LICENSE-TYPE PIC X(2).
10 LICENSE-EFF-DATE PIC X(8).
10 LICENSE-REN-DATE PIC X(8).
Minimum length of the record = 4 + 22 + (1 * 20) = 46
Maximum length of the record = 4 + 22 + (54 * 20) = 1106

43
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Examples of simple occurs


Ex1:
01 ACCT-REC.
05 ACCT-NUM PIC X(10).
.
.
.
05 MONTHLY-BALANCES OCCURS 12 TIMES.
10 LEAST-BAL PIC S9(7)V99 COMP-3.
10 LEAST-BAL-DATE PIC X(8).
10 INTEREST-ACCUMULATION PIC S9(7)V99 COMP-3.
Ex2:
01 POLICY-REC.
05 POLICY-NUM PIC X(10).
.
.
.
05 BENIFITS OCCURS 10 TIMES.
10 BENIFIT-NUM PIC 9(3).
10 BENIFIT-NAME PIC X(20).
10 BENIFIT-TYPE PIC X(1).
10 BENIFIT-RETURNS PIC S9(7)V99 COMP-3.

Example for a TWO DIMENSIONAL Occurs


Ex1:
01 LOAN-REC.
05 LOAN-ACCT PIC X(10).
05 ACCT-NAME PIC X(20).
05 LOAN-AMT PIC S9(7)V99 COMP-3.
05 LOAN-YEARS OCCURS 5 TIMES.
10 LOAN-MONTHS OCCURS 12 TIMES.
15 LOAN-EMI PIC S9(7)V99 COMP-3.
15 LOAN-DUE-DATE PIC X(8).

Ex2:
01 PROCUT-DETAILS.
05 STATE-TABLE OCCURS 54 TIMES.
10 STATE-CODE PIC X(2).
10 PRODUCT-TABLE OCCURS 30 TIMES.
15 PCODE PIC X(4).
15 PRICE PIC S9(6)V99 COMP-3.

Exceptions
When occurs is referenced beyond the maximum occurs, and if program compiled with
SSRANGE option, it will abend with S0C4
Two dimension occurs cannot be searched with single search or search all verb. It has to
be searched in two different searches. one on outer table and another on inner table.

44
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Subprograms

When a specific functionality need to be performed in more than one program, then it is better to
keep this functionality in a sub-program and call it from different main programs with a CALL
statement. Sub-program is not executable.
Advantages:
It increases the readability, reduces the testing effort and also reduce the maintenance.
Common Examples:
Date validation modules
Interest calculations modules
Account validation modules
Name formatting modules
Abend handling routines

Steps to follow to call a sub-program from a Main-program


1. Write a subprogram & Compile it
2. Write main-program with a CALL statement to call sub-program and compile
main- program Supply Subprogram loadlib in the compilation of main-program
3. Execute Main-program. Supply the sub-program loadlib in the JOBLIB if the
sub- program is called dynamic.

How to call a subprogram

In Main-program In Sub-program
WORKING-STORAGE SECTION. LINKAGE SECTION.
01 WS-VAR1 PIC ... 01 LS-VAR1 PIC ...
01 WS-VAR2 PIC ... 01 LS-VAR2 PIC ...
01 WS-VAR3 PIC ... 01 LS-VAR3 PIC ...

PROCEDURE DIVISION. PROCEDURE DIVISION USING LS-VAR1,


LS-VAR2,
CALL 'SUB1' USING WS-VAR1, LS-VAR3
WS-VAR2,
WS-VAR3 STATEMENT1
STATEMENT1 STATEMENT2
STATEMENT2 ..
.. GOBACK/EXIT PROGRAM.
STOP RUN.

Number of variables, data type, length and position of sending and receiving variables should be
same. Name of sending and receiving variables can be different.
Main-program is called CALLING program and sub-program is called CALLED program

Different ways of passing variables


There are two ways to pass variables from main-program to sub-program
1. BY CONTENT
Only value is passed to the sub-program.
Value modified in the sub-program is not reflected to the main program.
2. BY REFERENCE
Address is passed to the sub-program.
Value modified in the sub-program is reflected to the main program.

45
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Case1 Case2

CALL 'SUB1' USING CALL 'SUB1' USING


BY CONTENT WS-VAR1, BY REFERENCE WS-VAR1,
BY CONTENT WS-VAR2, BY REFERENCE WS-VAR2,
BY CONTENT WS-VAR3, BY REFERENCE WS-VAR3

Case3 Case4

CALL 'SUB1' USING CALL 'SUB1' USING


BY CONTENT WS-VAR1, WS-VAR1,
BY CONTENT WS-VAR2, WS-VAR2,
BY REFERENCE WS-VAR3 WS-VAR3

Different ways of calling sub-program

STATIC DYNAMIC

1. PROGRAM-ID. MAIN1. 1. PROGRAM-ID. MAIN1.


CALL 'SUB1' USING WS-VAR1, 01 WS-SUB PIC X(8) VALUE 'SUB1'.
WS-VAR2
CALL WS-SUB USING WS-VAR1,
PARM=(NODYNAM) -- Static WS-VAR2
PARM=DYNAM -- Dynamic
PARM=(NODYNAM/DYNAM) -- Dynamic
2. Sub-program expands into main-program
2.Sub-program dont expands into
3. No need to supply sub-program main-program
loadlib in the run time 3.Supply sub-program loadlib in the
4. When sub-program is changed, then run time
recompile main-program to reflect 4.When sub-program is changed, then
changes of sub-program no need to recompile main-program

Factors that are considered for Static/Dynamic


The below are the key factors used to decide static or dynamic
Memory -- Low memory
Speed -- High speed
Maintenance -- Low maintenance

Out of the above 3 factors maintenance is more important

STATIC DYNAMIC
1.High memory utilization Low memory
because sub-pgm expands into main-pgm
2.Relatively high speed
because no need to load in the run time Relatively low speed
3.High Maintenance
When sub-pgm is updated, recompile all
main-pgms to pickup changes of sub-pgm Low Maintenance

46
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Choose Dynamic call on the below situations


1. When more changes are expected in the sub-program. No need to compile main-program to
reflect the changes of the sub-program.
2. When sub-program is called more places in the main-program. So that memory is not wasted.

Choose Static call on the below situation


1. When changes are not expected in the sub-program.
2. When more processing speed is required.

Where to supply sub-program loadlib in the main program compilation and RUN
In Compile jcl
1. Compile sub-program before main-program is compiled
2. Compile Main-program and supply sub-program loadlib in the syslib of link edit
//STEP1 EXEC PGM=IGYCRCTL,PARM=(DYNAM/NODYNAM)
//SYSIN DD DSN=USERID.SRCLIB(MAIN1),DISP=SHR
//*
//..
//..
//STEP2 EXEC PGM=IEWL,PARM=('AMODE=31,RMODE=ANY)
//SYSLIN DD DSN=&&TEMP1,DISP=(OLD,DELETE)
//SYSLIB DD DSN=USERID.LOADLIB2,DISP=SHR  Sub-program loadlib
//SYSLMOD DD DSN=USERID.LOADLIB1(MAIN1),DISP=SHR  Main-program loadlib
//..
//..

In Run Jcl
Case1: When a sub-program called dynamic. Supply sub-program Loadlib
//JOBLIB DD DSN=USERID.LOADLIB1,DISP=SHR
// DD DSN=USERID.LOADLIB2,DISP=SHR
//*
//STEP1 EXEC PGM=MAIN1
//..
Case2: When a sub-program called static, No need to supply sub-program Loadlib
//JOBLIB DD DSN=USERID.LOADLIB1,DISP=SHR
//*
//STEP1 EXEC PGM=MAIN1
//..
//..
What are different situations to create sub-programs

Common Functionality Modular

1. When a same functionality is required 1. Main-program functionality is split into multiple


in many programs then this type of sub-programs for better readability and
sub-programs are used maintainability.

2. Advantages are 2. Advantages are


Reduced code with re-usability Increased readability
Reduced testing
Easy to maintain

3. Developer get a rare chance to code or 3. Developer gets lot of chances to code/update
update such a programs. These are such a programs
pre-written in many systems

47
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Ex: Date validation Ex: Trasaction Driver and funtional program


Future date Report Driver and different report program
Future Business date
Interest calculation
Name formatting
Abend routines

A statically called subprogram will be in its initial state for the first time it is called. For
subsequent times it will be in the excited state.
Use 'IS INITIAL PROGRAM' in the program-id entry of sub-program to bring it to
initial state for every call.
A dynamically called subprogram will always be in its initial

Case1: Static Call without IS INITIAL PROGRAM

PROGRAM-ID. MAIN1. PROGRAM-ID. SUB1.

WORKING-STORAGE SECTION. WORKING-STORAGE SECTION.


01 A PIC 9(3). 01 WS-NUM PIC 9(3) VALUE 5.

MOVE 0 TO A LINKAGE SECTION.


CALL 'SUB1' USING A. 01 A PIC 9(3).

DISPLAY A. --> It is 6 PROCEDURE DIVISION USING A.

MOVE 0 TO A ADD +1 TO WS-NUM


CALL 'SUB1' USING A. MOVE WS-NUM TO A.

DISPLAY A. --> It is 7

Case2: Static Call with IS INITIAL PROGRAM

PROGRAM-ID. MAIN1. PROGRAM-ID. SUB1 IS INITIAL PROGRAM.

WORKING-STORAGE SECTION. WORKING-STORAGE SECTION.


01 A PIC 9(3). 01 WS-NUM PIC 9(3) VALUE 5.

MOVE 0 TO A LINKAGE SECTION.


CALL 'SUB1' USING A. 01 A PIC 9(3).

DISPLAY A. --> It is 6 PROCEDURE DIVISION USING A.

MOVE 0 TO A ADD +1 TO WS-NUM


CALL 'SUB1' USING A. MOVE WS-NUM TO A.

DISPLAY A. --> It is 6

How to supply files to the DDNAMEs given in Subprograms


Ex: DD1 and DD2 are used in MAIN1 and DD3 and DD4 are used in SUB1.
And this SUB1 is called from MAIN1
//STEP1 EXEC PGM=MAIN1
//DD1 DD DSN=FILE1,DISP=SHR
//DD2 DD DSN=FILE2,DISP=SHR
//DD3 DD DSN=FILE3,DISP=SHR
//DD4 DD DSN=FILE4,DISP=SHR

48
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Extra care required when files used in sub-programs


If files are used in the sub-program, then supply the DDNAMEs of the files under EXEC statement
of MAIN PROGRAM in the RUN JCL.
Extra care is required to open and close files in the sub-program when it is called from main
program. This can be done in two methods.

Method1:
Every time the sub-program is called, in the sub-program open the file and use any I/O statement
like read, write, rewrite or delete. Then Close the file before GOBACK statement.
In this lot of overhead to open and close every time it is called.

Method2:
Open the file in the sub-program when it is called for the first time.
For all subsequent calls use any I/O operation like read, write, rewrite or delete.
Close the file in the sub-program when it is called for the last time before termination process in
the main program.
Note: Method 2 is always a good because it reduces open and close statements. For this one extra
variable has to be passed to the sub-program to tell about the I/O operation.

Copybook
Copybook is a member of a PDS which contains a common code and is used in one or more
programs with COPY statement.
Syntax: COPY Member-name.

Where these copybooks are expanded


Copybooks are expanded in the compilation time from the SYSLIB parameter of IGYCRCTL
providing ‘LIB’ option in compilation parameter.
//STEP1 EXEC PGM=IGYCRCTL,PARM=('LIB')
//SYSLIB DD DSN=TSO.COPYLIB,DISP=SHR

Advantages of Copybook
1. Reduces coding effort
2. Reduces maintenance when a new field is added to a copybook of a file
3. Gives common naming for the layouts used in different program

What are common areas that copybooks used


Copybook can be used for common code in 3 different areas.
1. Layout used in the file section
Ex: Master File, transaction file layouts used in multiple programs
2. Layout used in the working storage section or linkage section
Ex: Common working storage layouts used to call a sub-programs
3. For a Common coding in the Procedure division
Ex: Any common procedure division code used in many programs. But these are not
recommended in many real time programs.

What is the difficulty without a copybook


When a layout is hard coded in multiple programs without a copybook, and this layout is changed
in future then all the programs need to be changed. When a copybook is used, then change
copybook and compile all programs. When a same file is used in two programs and the layout of
this file is same, then It can be done in two ways like shown in CASE1 and CASE2.

49
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

CASE1.
PGM1 PGM2
FD AGENT-FILE. FD AGENT-FILE.
01 AGENT-REC.01 AGENT-REC.
05 AGENT-NUM PIC X(4). 05 AGENT-NUM PIC X(4).
05 AGENT-NAME PIC X(20). 05 AGENT-NAME PIC X(20).
05 AGENT-DOJ PIC X(8). 05 AGENT-DOJ PIC X(8).
05 AGENT-DOB PIC X(8). 05 AGENT-DOB PIC X(8).
05 AGENT-SAL PIC 9(6)V99. 05 AGENT-SAL PIC 9(6)V99.

CASE2 Code this common layout in a member of a PDS(i.e. copy library) with name COPY1.
COPY1 contains the below layout.

01 AGENT-REC.
05 AGENT-NUM PIC X(4).
05 AGENT-NAME PIC X(20).
05 AGENT-DOJ PIC X(8).
05 AGENT-DOB PIC X(8).
05 AGENT-SAL PIC 9(6)V99.

Now copy this copybook in both the programs PGM1 and PGM2.
PGM1 PGM2
FD AGENT-FILE. FD AGENT-FILE.
COPY COPY1. COPY COPY1.

Impact on programs when a new filed is introduced


If a new field AGENT-STATUS PIC X(1) is introduced in the file layout then its impact on both
the cases.
In CASE1
Change both the programs PGM1 and PGM2 to include new field in the layout of the file. Then
compile both the programs.

In CASE2
Change COPY1 to include new field in the layout and compile two programs PGM1 and PGM2.

How to use the same copybook for two files in the same program
Same layout is required in both input and output files in the program PGM1. then it cannot be
used as shown below because same 01 level cannot be used more than one time.

In PGM1 COPY1
FD INFILE. 01 AGENT-REC.
COPY COPY1. 05 ……..
FD OUTFILE. 05 ……..
COPY COPY1.
This can be done in two alternate methods.

Method 1. With replacing option in PGM1

FD INFILE.
COPY COPY1 REPLACING AGENT-REC BY IN-AGT-REC.

FD OUTFILE.
COPY COPY1 REPLACING AGENT-REC BY OUT-AGT-REC.

50
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Method 2. Comment out 01 level in the copybook and code that 01 level in PGM1.

FD INFILE COPY1
01 IN-AGT-REC. *01 AGENT-REC.
COPY COPY1. 05 ……..
05 ……..
FD OUTFILE
01 OUT-AGT-REC.
COPY COPY1.

Impact on the system when a new field is introduced for a file


When a filler is available in the copybook
1. Update the Programs that use this new field.
Note: Programs that don't use this new field are not impacted. Even though the data is
available in the new field of the file, it is not used in the procedure division of these
programs. These programs still see that data as filler.
2. JCL/PROCs that is creating or using this file are not impacted.

When a filler is not used


1. Update the Programs that use this new field.
2. Recompile the Programs that don't use this new field.
Even though the data of the new field is not required in these programs, these programs
has to be recompiled. Otherwise the old copybook will have old length and file is having new
length which will lead to attribute mismatch i.e. U4038 Abend.
3. Update PROC/JCL that is creating this file to increase LRECL.

What is difference between Subprogram and Copybook

Copybook Subprogram

1. These are expanded in compile time 1. These are expanded in link edit time
2. No need to supply in the run time 2. Supply these in the run time when
dynamically called
3. These are stored in copy library 3. Source is stored in source library
Load is stored in load library
4. Sending and receiving fields are not 4. Sending and receiving fields are possible.
possible

51
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

String Handling

String
To concatenate one or more Literals or Identifiers delimited by value or size into a single
identifier The STRING statement move data into receiving field from left to right just like
alphanumeric fields are moved, but it does not pad spaces in the end. It is mostly used in reports
to report first name, last name and middle name as a single name with commas.

Rules for using the STRING statement


1. Receiving field must be an elementary data item with no editing symbols or JUSTIFIED
RIGHT clause.
2. All literals must be described as non-numeric
3. Identifier specified with the POINTER clause must be an elementary numeric item.

Syntax:
STRING {identifier-1} DELIMITED BY {identifier-2}
{literal-1 } {literal-2 } ...{SIZE }
INTO identifier-3 ON OVERFLOW Imperative statement
[ WITH POINTER identifier-3 ]

05 FULL-NAME.
10 LAST-NAME PIC X(10) VALUE 'EDISON'.
10 MIDDLE-NAME PIC X(10) VALUE 'ALVA'.
10 FIRST-NAME PIC X(10) VALUE 'THOMAS'.
05 NAME-OUT PIC X(21) value spaces.

Ex.1: STRING FIRST-NAME DELIMITED BY SIZE,


LAST-NAME DELIMITED BY SIZE
INTO NAME-OUT
OUTPUT: 'THOMAS EDISON '

Ex.2: STRING FIRST-NAME DELIMITED BY SPACES,


LAST-NAME DELIMITED BY SPACES
INTO NAME-OUT
OUTPUT: 'THOMASEDISON'

Ex.3: STRING FIRST-NAME DELIMITED BY SPACES,


',' DELIMITED BY SIZE,
LAST-NAME DELIMITED BY SPACES
INTO NAME-OUT
OUTPUT: 'THOMAS,EDISON'

Ex.4: MOVE 'XXXXXXXXXXXXXXXXXXXXX' TO NAME-OUT


STRING FIRST-NAME DELIMITED BY SPACES,
',' DELIMITED BY SIZE,
LAST-NAME DELIMITED BY SPACES
INTO NAME-OUT
OUTPUT: 'THOMAS,EDISONXXXXXXXX'

Ex.5: MOVE 4 TO STR-PTR


STRING FIRST-NAME DELIMITED BY SPACES,
',' DELIMITED BY SIZE,
LAST-NAME DELIMITED BY SPACES
INTO NAME-OUT WITH POINTER STR-PTR
OUTPUT: ' THOMAS,EDISON'

52
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Unstring
Unstring is used to split Source string into multiple destination strings delimited by value. The
UNSTRING statement move data from left to right just like alphanumeric fields are moved, if the
receiving fields are smaller then it files spaces in the right side

Rules for using the UNSTRING statement


1. The sending field must be non-numeric. The receiving fields may be numeric or non-numeric.
2. Each literal must be non-numeric.
3. The [WITH POINTER identifier] and [ON OVERFLOW imperative-statement] clauses may
be used in the same way as with the STRING.
Syntax :
UNSTRING IDENTIFIER-1 DELIMITED BY [ALL] IDENTIFIER-2/LITERAL-1
INTO IDENTIFIER-3, IDENTIFIER-4 ....
[ ON OVERFLOW IMPERETIVE STATEMEN]
[ TALLYING IN IDENTIFIER-5 ]
[ WITH POINTER IDENTIFIER-6 ]

05 FULL-NAME PIC X(30) VALUE 'THOMAS ALVA EDISON'


05 FIRST-NAME PIC X(10).
05 MIDDLE-NAME PIC X(10).
05 LAST-NAME PIC X(10).

Ex.1:UNSTRING FULL-NAME DELIMITED BY ALL SPACES


INTO FIRST-NAME, MIDDLE-NAME, LAST-NAME
TALLYING IN WS-NAMES-RECEIVED
OUTPUT:
FIRST-NAME = 'THOMAS '
MIDDLE-NAME = 'ALVA '
LAST-NAME = 'EDISON '
WS-NAMES-RECEIVED = 3

Ex.2:UNSTRING CUSTADDRESS DELIMITED BY ','


INTO ADRLINE1,
ADRLINE2,
ADRLINE3,
CITY-NAME,
PIN-CODE.

Ex.3:MOVE 10 TO STR-PTR
UNSTRING CUSTADDRESS DELIMITED BY ','
INTO ADRLINE1,
ADRLINE2,
ADRLINE3,
CITY-NAME,
PIN-CODE.
WITH POINTER STR-PTR
If Pointer is given then it starts unstring the data from 10 th character in the sending field.

53
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

INSPECT
The INSPECT scans the Source String from left to right counting and/or replacing characters
under the control of the TALLYING, REPLACING or CONVERTING phrases

INSPECT- FOR TALLYING


It is used to tally the occurrence of a single character or groups of characters in a data field.
Syntax:
INSPECT IDENTIFIER-1 TALLYING IDENTIFIER-2 FOR
{ALL/LEADING LITERAL-1|IDENTIFIER-3
[BEFORE|AFTER INITIAL IDENTIFIER-4|LITERAL-2] } ...
{CHARACTERS [BEFORE|AFTER INITIAL IDENTIFIER-4|LITERAL-2]} ...

Ex: ZIP-CODE - '132-330-1450'

INSPECT ZIP-CODE TALLYING WS-COUNT FOR ALL '-'.


RESULT: VALUE IN WS-COUNT IS 2.

INSPECT- FOR REPLACING


REPLACING option changes a character or string with another character or string.
Syntax:
INSPECT IDENTIFIER-1 REPLACING
{ALL|LEADING LITERAL-1|IDENTIFIER-2 BY IDENTIFIER-3|LITERAL-2
[BEFORE|AFTER INITIAL IDENTIFIER-4|LITERAL-2]} ...
{CHARACTERS BY IDENTIFIER-2 BEFORE|AFTER INITIAL
IDENTIFIER-3|LITERAL-1 }...

Ex: EMAIL-ID 'JOHN.JOHNSON@CNO.COM'


INSPECT EMAIL-ID REPLACING '.COM ' BY '.CO.IN' AFTER 'CNO'
OUTPUT: 'JOHN.JOHNSON@CNO.CO.IN'

INSPECT- FOR CONVERTING


CONVERTING Option replaces a corresponding character of the CONVERTING set with the
corresponding in the TO set.
Syntax:
INSPECT IDENTIFIER-1 CONVERTING
{LITERAL-1|IDENTIFIER-2} TO {IDENTIFIER-3|LITERAL-2}...
[BEFORE|AFTER INITIAL IDENTIFIER-4|LITERAL-2]

In the below example small case is converted to upper case.


INSPECT CUSTADDRESS CONVERTING "abcdefghijklmnopqrstuvwxyz"
TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ".

Ex: EMAIL-ID 'John.Johnson@Cno.Com'


INSPECT EMAIL-ID CONVERTING 'abcdefghijklmnopqrstuvwxyz'
TO 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
OUTPUT: 'JOHN.JOHNSON@CNO.COM'

54
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

File Handling

Files
Files are used to store the processing data. These are used in the programs to read, write, update
or delete based on the processing logic.
Types of files

FLAT Files VSAM


ESDS
KSDS
RRDS
LDS
Out of these files, only PSEQ and KSDS files are used.
PSEQ is used to Read/write processing data
KSDS is used to Read/update/insert/delete master data

1. Physical sequential files or flat files


These are mostly used to carry processing data from one program to another program.
These are used in batch programming only. Updates or deletes are not done on these files.
Example for sequential files
Transaction files
Intermediate files to carry data from one program to another program
Report files
Extract files that are sent to another system
Extract files that are received from another system
Backup files

2. VSAM files (ESDS, KSDS, RRDS, LDS)


These are mostly used as a Database to store master data
These are updated with the data from the transaction files in the programs
These are used in both batch and online programming.

Example for VSAM KSDS files


Master files like
Policy master file
Account master file
Agent Master file
Earnings master file
Loan master file
History file

Sequential files
These files are used extensively in the batch processing
Entire application cannot be done in single program, so the processing logic is done in many
programs with many JCLs. In this process, files are used to pass the data from one program to
another program.
Reading and writing a data into these files are done in a sequential order.
Logical files are given in the COBOL program where as physical files are supplied in the JCL.

55
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Different Divisions/Sections that are used in files


Declaring file and assigning to DDNAME with SELECT statement.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.

FILE CONTROL.

SELECT TRXN-FILE ASSIGN TO TRXFLE


ORGANIZATION IS SEQUENTIAL
ACCESSMODE IS SEQUENTIAL
FILE STATUS IS WS-STATUS.

Declare recording mode and layout of the file.


DATA DIVISION.
FILE SECTION.

FD TRXN-FILE
RECORDING MODE IS FB
RECORD CONTAINS 23 CHARACTERS
BLOCK CONTAINS 230 CHARACTERS.

01 TRXN-REC.
05 ACCT-NUM PIC X(4).
05 TRXN-CODE PIC X(2).
05 TRXN-DATE PIC X(8).
05 TRXN-AMT PIC 9(7)V99.

PROCEDURE DIVISION.

OPEN INPUT TRXN-FILE.


PERFORM UNTIL WS-STATUS = '10'
READ TRXN-FILE
IF WS-STATUS = '00'
DISPLAY TRXN-REC
END-IF
END-PERFORM.

CLOSE TRXN-FILE.
STOP RUN.

Data in the file


A001DE20110503000500000
A002WI20110503000600000
EOF

Normal Order of file activities in procedure division


1. Open. This is done one time and it should be done prior to other i-o statements.
2. Read/Write/Rewrite. This is done for more number of times. That is why it is kept in
a loop until a condition is met.
3. Close. This is done in the end after completing all other i-o statements.

Connections of logical and physical files are done with DDNAME in select statement of program
and DDNAME in the JCL.
A is logical file name
B is DDNAME
C is physical file name

56
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

A=B AND B=C SO A=C.


In COBOL
A = B
SELECT LOGICAL-FILE ASSIGN DDNAME

In JCL
B = C
//DDNAME DD DSN=PHYSICALFILE,DISP=SHR
Ex: A B
SELECT TRX-FILE ASSIGN TRXFLE
B C
//TRXFLE DD DSN=TSO.USERID.DLYTRX,DISP=SHR
Create and delete of a physical file is done in JCL. Whereas open, read, write, rewrite, delete a
record, close are done in the program.

Complete File Operations


Sequential files: Open, Close, Read, Write, Rewrite
VSAM KSDS files : Open, Close, Read, Write, Rewrite, Delete, Start, Read Next
Sort Work files : Release, Return

Open Statement
Syntax: Open mode Logical-File1, Logical-File2..
mode Logical-File3, Logical-File4..
Different modes on PSEQ
Input - Read
Output - Write
Extend - Write/Append
I-O - Read/Rewrite

OPEN in COBOL VS DISP in JCL on Sequential files

Open Mode DISP Action

INPUT SHR File should be existing and other jobs can read it
OLD File should be existing and other jobs cannot read it

OUPUT NEW File should not be existing, It will create


MOD
File may or may not be existing
If file not existing then it will create
If file is existing then it will append data
SHR/OLD
File should be existing. Deletes existing data and writes new data

NEW File should not be existing


EXTEND File may or may not existing
MOD
If file not existing then it will create
SHR/OLD If file is existing then it will append data
File should be existing. It appends data.

SHR/OLD File should be existing and records can be updated


I-O

57
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Different modes on VSAM KSDS


Input -- Read, Start, Read Next
Output -- Write
I-O -- Read/Write/Rewrite/Delete, Start, Read Next
OPEN in COBOL VS DISP in JCL on VSAM KSDS files

Open Mode DISP Action

INPUT SHR File should be existing and other jobs can read it
OLD File should be existing and other jobs cannot read it

OUPUT SHR/OLD File should be existing. Existing data is deleted and fresh data is
written.

I-O SHR/OLD
File should be existing and records can be read, updated,
inserted or deleted
EXTEND This mode is not allowed

Note: VSAM KSDS files should be created first, before they use in any mode.
Only allowed disp is SHR/OLD

Read Statement
Syntax:
Read Logical-file
Read Logical-file into ws-record
Read Logical-file at end imperative statement.

1. It reads physical records in the file and maps to layout.


2. First read statement reads first record from physical file to logical record.
3. Second read statement reads second record from physical file to logical record. And
first logical record refreshed with second record.
4. Reading last record returns '00' and reading after last record returns '10' into File status.
5. Keep this read statement in a loop until end of file to read all records of a file.
Note: 1. At any point, the last record that is read is available in logical record.
2. If you want to keep the current record then move current record into working storage
fields. Then go for Next Read.

Write Statement
Syntax:
Move identifier/literal to Logical-record
Write Logical-record
Write Logical-record from ws-record

Write statement writes records into a sequential file in a sequential order.

Close Statement
Close Logical-file1, Logical-file2.....
It closes file/files given in the statement.

58
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Exceptions of sequential files


Update (rewrite) is allowed but not recommended.
Delete is not allowed

Relation between Logical file and Physical File

Depends
1. DDNAME of COBOL and DDNAME of JCL should be same
2. File organization of logical file in Select statement and organization of
physical file should be same
3. File attributes of FD entry in COBOL and DCB parameters of JCL should be same
RECFM, LRECL, BLKSIZE
4. OPEN statement and DISP should be compatible
Don’t depend
Physical file name in DSN
UNIT
SPACE

COBOL vs JCL on a file

IN COBOL IN COBOL

IDENTIFICATION DIVISION. PROCEDURE DIVISION.


PROGRAM-ID. READ1.
AUTHOR. MADHU PADALA. OPEN INPUT IN-FILE
OUTPUT OUT-FILE.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION. PERFORM UNTIL WS-STATUS = '10'
FILE-CONTROL. READ IN-FILE
IF WS-STATUS = '00'
SELECT IN-FILE ASSIGN TO INFILE IF IN-EMP-STATUS = 'A'
FILE STATUS IS WS-STATUS. MOVE IN-REC TO OUT-REC
SELECT OUT-FILE ASSIGN TO OUTFILE. WRITE OUT-REC
END-IF
DATA DIVISION. END-IF
FILE SECTION. END-PERFORM

FD IN-FILE. CLOSE IN-FILE


01 IN-REC. OUT-FILE.
05 IN-EMP-NUM PIC X(04). STOP RUN.
05 IN-EMP-NAME PIC X(10).
05 IN-EMP-DOJ PIC 9(08). IN JCL
05 IN-EMP-STATUS PIC X(01).
05 IN-EMP-SAL PIC 9(08)V99. //STEP1 EXEC PGM=READ1
//INFILE DD DSN=USERID.FILE1,
FD OUT-FILE. // DISP=SHR
01 OUT-REC. //OUTFILE DD DSN=USERID.FILE2,
05 OUT-EMP-NUM PIC X(04). // DISP=(NEW,CATLG,DELETE),
05 OUT-EMP-NAME PIC X(10). // UNIT=SYSDA,
05 OUT-EMP-DOJ PIC 9(08). // SPACE=(CYL,(5,2),RLSE),
05 OUT-EMP-STATUS PIC X(01). // DCB=(RECFM=FB,LRECL=33,BLKSIZE=0)
05 OUT-EMP-SAL PIC 9(08)V99.

WORKING-STORAGE SECTION.
01 WS-STATUS PIC X(2) VALUE SPACES.

59
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

How many ways a file can be read from top to bottom

Method1 Method2

IDENTIFICATION DIVISION. IDENTIFICATION DIVISION.


PROGRAM-ID. READ1. PROGRAM-ID. READ1.
AUTHOR. MADHU PADALA. AUTHOR. MADHU PADALA.

ENVIRONMENT DIVISION. ENVIRONMENT DIVISION.


INPUT-OUTPUT SECTION. INPUT-OUTPUT SECTION.
FILE-CONTROL. FILE-CONTROL.

SELECT IN-FILE ASSIGN TO INFILE SELECT IN-FILE ASSIGN TO INFILE


FILE STATUS IS WS-STATUS. FILE STATUS IS WS-STATUS.
SELECT OUT-FILE ASSIGN TO OUTFILE. SELECT OUT-FILE ASSIGN TO OUTFILE.

DATA DIVISION. DATA DIVISION.


FILE SECTION. FILE SECTION.
FD IN-FILE. FD IN-FILE.
01 IN-REC. 01 IN-REC.
05 IN-EMP-NUM PIC X(04). 05 IN-EMP-NUM PIC X(04).
05 IN-EMP-NAME PIC X(10). 05 IN-EMP-NAME PIC X(10).
05 IN-EMP-DOJ PIC 9(08). 05 IN-EMP-DOJ PIC 9(08).
05 IN-EMP-STATUS PIC X(01). 05 IN-EMP-STATUS PIC X(01).
05 IN-EMP-SAL PIC 9(08)V99. 05 IN-EMP-SAL PIC 9(08)V99.

FD OUT-FILE. FD OUT-FILE.
01 OUT-REC. 01 OUT-REC.
05 OUT-EMP-NUM PIC X(04). 05 OUT-EMP-NUM PIC X(04).
05 OUT-EMP-NAME PIC X(10). 05 OUT-EMP-NAME PIC X(10).
05 OUT-EMP-DOJ PIC 9(08). 05 OUT-EMP-DOJ PIC 9(08).
05 OUT-EMP-STATUS PIC X(01). 05 OUT-EMP-STATUS PIC X(01).
05 OUT-EMP-SAL PIC 9(08)V99. 05 OUT-EMP-SAL PIC 9(08)V99.

WORKING-STORAGE SECTION. WORKING-STORAGE SECTION.


01 WS-STATUS PIC X(2) VALUE SPACES. 01 WS-STATUS PIC X(2) VALUE SPACES.

PROCEDURE DIVISION. PROCEDURE DIVISION.

OPEN INPUT IN-FILE OPEN INPUT IN-FILE


OUTPUT OUT-FILE. OUTPUT OUT-FILE.

PERFORM UNTIL WS-STATUS = '10' READ IN-FILE

READ IN-FILE PERFORM UNTIL WS-STATUS = '10


IF WS-STATUS = '00'
IF IN-EMP-STATUS = 'A'
IF IN-EMP-STATUS = 'A' MOVE IN-REC TO OUT-REC
MOVE IN-REC TO OUT-REC WRITE OUT-REC
WRITE OUT-REC END-IF
END-IF
READ IN-FILE
END-IF
END-PERFORM
END-PERFORM
CLOSE IN-FILE
CLOSE IN-FILE OUT-FILE.
OUT-FILE.
STOP RUN. STOP RUN.

60
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Method3 Method4

IDENTIFICATION DIVISION. IDENTIFICATION DIVISION.


PROGRAM-ID. READ3. PROGRAM-ID. READ4.
AUTHOR. MADHU PADALA. AUTHOR. MADHU PADALA.

ENVIRONMENT DIVISION. ENVIRONMENT DIVISION.


INPUT-OUTPUT SECTION. INPUT-OUTPUT SECTION.
FILE-CONTROL. FILE-CONTROL.
SELECT IN-FILE ASSIGN TO INFILE. SELECT IN-FILE ASSIGN TO INFILE.
SELECT OUT-FILE ASSIGN TO OUTFILE. SELECT OUT-FILE ASSIGN TO OUTFILE.

DATA DIVISION. DATA DIVISION.


FILE SECTION. FILE SECTION.
FD IN-FILE. FD IN-FILE.
01 IN-REC. 01 IN-REC.
05 IN-EMP-NUM PIC X(04). 05 IN-EMP-NUM PIC X(04).
05 IN-EMP-NAME PIC X(10). 05 IN-EMP-NAME PIC X(10).
05 IN-EMP-DOJ PIC 9(08). 05 IN-EMP-DOJ PIC 9(08).
05 IN-EMP-STATUS PIC X(01). 05 IN-EMP-STATUS PIC X(01).
05 IN-EMP-SAL PIC 9(08)V99. 05 IN-EMP-SAL PIC 9(08)V99.
FD OUT-FILE. FD OUT-FILE.
01 OUT-REC. 01 OUT-REC.
05 OUT-EMP-NUM PIC X(04). 05 OUT-EMP-NUM PIC X(04).
05 OUT-EMP-NAME PIC X(10). 05 OUT-EMP-NAME PIC X(10).
05 OUT-EMP-DOJ PIC 9(08). 05 OUT-EMP-DOJ PIC 9(08).
05 OUT-EMP-STATUS PIC X(01). 05 OUT-EMP-STATUS PIC X(01).
05 OUT-EMP-SAL PIC 9(08)V99. 05 OUT-EMP-SAL PIC 9(08)V99.
WORKING-STORAGE SECTION. WORKING-STORAGE SECTION.
01 WS-EOF-IN PIC X(1) VALUE 'N'. 01 WS-EOF-IN PIC X(1) VALUE 'N'.

PROCEDURE DIVISION. PROCEDURE DIVISION.


PERFORM 100000-INITIALIZATION PERFORM 100000-INITIALIZATION
THRU 100000-EXIT. THRU 100000-EXIT.
PERFORM 200000-PROCESS PERFORM 200000-PROCESS
THRU 200000-EXIT THRU 200000-EXIT
UNTIL WS-STATUS = '10'. UNTIL WS-EOF-IN = 'Y'.
PERFORM 300000-TERMINATION PERFORM 300000-TERMINATION
THRU 300000-EXIT. THRU 300000-EXIT.
STOP RUN. STOP RUN.

100000-INITIALIZATION. 100000-INITIALIZATION.
OPEN INPUT IN-FILE OPEN INPUT IN-FILE
OUTPUT OUT-FILE. OUTPUT OUT-FILE.
100000-EXIT. 100000-EXIT.
EXIT. EXIT.
200000-PROCESS. 200000-PROCESS.
READ IN-FILE. READ IN-FILE AT END
MOVE 'Y' TO WS-EOF-IN
IF WS-STATUS = '10' GO TO 200000-EXIT.
GO TO 200000-EXIT.
IF IN-EMP-STATUS = 'A'
IF IN-EMP-STATUS = 'A' MOVE IN-REC TO OUT-REC
MOVE IN-REC TO OUT-REC WRITE OUT-REC.
WRITE OUT-REC. 200000-EXIT.
200000-EXIT. EXIT.
EXIT. 300000-TERMINATION.
300000-TERMINATION. CLOSE IN-FILE
CLOSE IN-FILE OUT-FILE.
OUT-FILE. 300000-EXIT.
300000-EXIT. EXIT.
EXIT.

61
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Note: Out of these 4 methods the most common used one is Method 4. File status is not required
in this method. WS-FLAG is taken in the place of File Status and it is used for UNTIL condition.
End of file is checked with AT END clause of READ statement. When AT END is used with read
statement, it is mandatory to use period or END-READ as a scope terminator.

Common Mistakes in using sequential files


1. File attribute mismatch between COBOL and JCL -- fails with U4038
2. DDNAME missing
3. Incorrect field mapping from layout to the file -- Incorrect data
4. First record may not be processed
5. last record may be processed twice
6. Until condition may never satisfied -- Falls in infinite loop
7. AT END clause is not properly closed, so that all statements up to the period falls into
AT END case.
8. Taking non numeric data into numeric field which may cause S0C7 abend

File Status Codes


'00' -- Success
'10' -- end of file
'35' -- DD statement missing or DDNAME Misspelled
'39' -- file attribute mismatch
'41' -- Trying to open a opened file
'42' -- Trying to close a file which is not opened
'43' -- Using REWRITE but no prior READ
'44' -- writing a variable length records beyond maximum and minimum length
'46' -- Reading beyond end of file (After file status 10)
'47' -- Using READ but open mode is not compatible. Other than INPUT/I-O
'48' -- Using WRITE but open mode is not compatible. Other than
OUTPUT/I-O/EXTEND
'49' -- Using REWRITE but open mode is not compatible. Other than I-O

Common Abends in Files


1. U4038
It is generated for all file status codes except for 00 and 10.
File status code is converted into user abend U4038 by IBM.
U4038 has more information than file status
2. SB37
Space abend is generated while writing records
Primary and secondary space are coded but not sufficient
3. SD37
Space abend is generated while writing records
Primary coded but secondary is not coded and primary space is not sufficient
4. S0C7
File is having non numeric data on numeric field
File layout and data is mismatched
5. S0C4
File Organization in COBOL and File organization in JCL are not matching
6. S0C1 DD statement missing

62
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Sorting Files
Internal Sort
Sort is used to sort a sequential file and also to apply different conditions before it is copied into
output file. There are two types of sorts, Internal Sort and External Sort. SORT used in the
COBOL program is called Internal Sort and SORT used in JCL is called External Sort.

How SORT is executed


SORT process is executed in three stages.

Stage1: Read all records of input file and release it to SORT work file
Stage2: After all records are released into sort work file, these records are sorted on the key field
based on Ascending or Descending order.
Stage3: After all records are sorted in the sort work file, these records are returned and written
into output file.

Different types of internal sort

Internal sort is of two types.


Type 1: Simple SORT with USING and GIVING options.
In this simple sort all 3 stages of sort process is done by SORT verb.
Syntax: SORT SORT-FILE ON ASCENDING KEY /DESCENDING KEY IS SORT-KEY-FIELD1
[ASCENDING KEY /DESCENDING KEY IS SORT-KEY-FIELD2]...
USING IN-FILE GIVING OUT-FILE.

In a simple sort the below activities are done by SORT verb.


1. Open in-file and out-file
2. Read all records from in-file and release these to sort-file.
3. Sort all records in the sort-file based on the key fields given in SORT verb.
4. Return sorted records from sort-file and writes into out-file
5. Close in-file and out-file

Note: 1. In simple sort, SORT verb opens In-file and out-file and explicit open statement should
not be given by programmer.
2. Layout of all in-file, sort-file and out-file should be same.

Type2: Complex SORT with input procedure and output procedure


Syntax: OPEN INPUT IN-FILE
OUTPUT OUT-FILE.

SORT SORT-FILE ON ASCENDING KEY /DESCENDING KEY IS SORT-KEY-FIELD1


[ASCENDING KEY /DESCENDING KEY IS SORT-KEY-FIELD2]...

INPUT PROCEDURE IS INPUT-PROC


OUTPUT PROCEDURE IS OUTPUT-PROC.

CLOSE IN-FILE
OUT-FILE.

63
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

In this sort the below activities are done by the programmer.


1. Open in-file and out-file before SORT statement.
2. Read all records of in-file and move these into sort-rec and release it to sort-file.
This should be done in the paragraph input-proc.
INPUT-PROC.
READ IN-FILE AT END MOVE ‘Y’ TO WS-EOF-IN
PERFORM UNTIL WS-EOF-IN = ‘Y’
MOVE IN-REC TO SORT-REC
RELEASE SORT-REC
READ IN-FILEAT END MOVE ‘Y’ TO WS-EOF-IN
END-READ
END-PERFORM
3. After input-proc is completed, SORT verb keeps all records of the sort-file in the given
sort order.
4. Read all sorted records of sort-file and move these into out-rec and write into out-file.
This should be done in the paragraph ouput-proc.
OUTPUT-PROC.
RETURN SORT-FILEAT END MOVE ‘Y’ TO WS-EOF-SORT
PERFORM UNTIL WS-EOF-SORT = 'Y'
MOVE SORT-REC TO OUT-REC
WRITE OUT-REC
RETURN SORT-FILEAT END MOVE ‘Y’ TO WS-EOF-SORT
END-RETURN
END-PERFORM
5. Close in-file and out-file after SORT statement.
Note: 1. Explicit open statement should be given for both in-file and out-file.
2. Writing into a sort-file is called RELEASE and reading from sort-file is called
RETURN.
3. SORT verb sorts all records after completion of input-proc and before execution of
output-proc.
4. SORT verb opens and closes sort-file

How to apply different conditions in complex sort


Complex internal sort gives more flexibility to the programmer to apply different selection
criteria’s as explained below.
If include/omit conditions are required along with sort criteria then apply those in Input-proc.
If only few fields are required into out-file then release few fields of in-rec to sort-rec in the
input-proc and move sort-rec to out-rec in the output-proc
If some more fields are required from VSAM file other than in-file fields, then read that VSAM
file in the input-proc and move required fields from in-file and from VSAM file to sort-file and
release sort-file. If more files are to be created from sort-file based on different conditions, then
apply these in output-proc. Note: Sort-file should not be opened in both internal sort types.

How to declare sort work file in the program and in the JCL
In COBOL
SELECT SORT-FILE ASSIGN TO SORTWK01.

DATA DIVISION.
FILE SECTION.
FD IN-FILE.
01 IN-REC.
...
...

64
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

FD OUT-FILE.
01 OUT-REC.
...
...
SD SORT-FILE.
01 SORT-REC.
05 SRT-FIELD-1 PIC X(04).
05 SRT-FIELD-2 PIC X(04).
05 SRT-FIELD-3 PIC X(08).

In JCL
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(10,5),RLSE)

Sample programs to show two types of internal sorts

Sort in-file on Agent-Id and copy all records into Sort in-file on Agent-Id and copy Arizona state (Stat-
out-file code ='AR') records into out-file

SORT card in JCL SORT card in JCL


**************************** **********************************
* //SYSIN DD * * * //SYSIN DD * *
* SORT FIELDS=(1,4,CH,A) * * SORT FIELDS=(1,4,CH,A) *
* /* * * INCLUDE COND=(5,2,CH,EQ,C'AR')*
**************************** * /* *
**********************************

COBOL program for the above sort card COBOL program for the above sort card
IDENTIFICATION DIVISION. IDENTIFICATION DIVISION.
PROGRAM-ID. INTSORT1. PROGRAM-ID. INTSORT2.
AUTHOR. MADHU PADALA. AUTHOR. MADHU PADALA.

ENVIRONMENT DIVISION. ENVIRONMENT DIVISION.


INPUT-OUTPUT SECTION. INPUT-OUTPUT SECTION.
FILE-CONTROL. FILE-CONTROL.

SELECT IN-FILE ASSIGN TO INFILE. SELECT IN-FILE ASSIGN TO INFILE.


SELECT OUT-FILE ASSIGN TO OUTFILE. SELECT OUT-FILE ASSIGN TO OUTFILE.
SELECT SORT-FILE ASSIGN TO SORTWK01. SELECT SORT-FILE ASSIGN TO SORTWK01.

DATA DIVISION.
FILE SECTION.

DATA DIVISION. FD IN-FILE.


FILE SECTION. 01 IN-REC.
05 IN-AGENT-NUM PIC X(04).
FD IN-FILE. 05 IN-STATE-CODE PIC X(02).
01 IN-REC. 05 IN-SALES-DATE PIC 9(08).
05 IN-AGENT-NUM PIC X(04). 05 IN-PROD-ID PIC X(02).
05 IN-STATE-CODE PIC X(02). 05 IN-PROD-PRICE PIC 9(06)V99.
05 IN-SALES-DATE PIC 9(08). 05 IN-PROD-QTY PIC 9(04).
05 IN-PROD-ID PIC X(02). 05 IN-SALES-AMT PIC 9(08)V99.
05 IN-PROD-PRICE PIC 9(06)V99.
05 IN-PROD-QTY PIC 9(04).
05 IN-SALES-AMT PIC 9(08)V99.

65
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

FD OUT-FILE. FD OUT-FILE.
01 OUT-REC. 01 OUT-REC.
05 OUT-AGENT-NUM PIC X(04). 05 OUT-AGENT-NUM PIC X(04).
05 OUT-STATE-CODE PIC X(02). 05 OUT-STATE-CODE PIC X(02).
05 OUT-SALES-DATE PIC 9(8). 05 OUT-SALES-DATE PIC 9(8).
05 OUT-PROD-ID PIC X(02). 05 OUT-PROD-ID PIC X(02).
05 OUT-PROD-PRICE PIC 9(06)V99. 05 OUT-PROD-PRICE PIC 9(06)V99.
05 OUT-PROD-QTY PIC 9(04). 05 OUT-PROD-QTY PIC 9(04).
05 OUT-SALES-AMT PIC 9(08)V99. 05 OUT-SALES-AMT PIC 9(08)V99.

SD SORT-FILE. SD SORT-FILE.
01 SORT-REC. 01 SORT-REC.
05 SRT-AGENT-NUM PIC X(04). 05 SRT-AGENT-NUM PIC X(04).
05 SRT-STATE-CODE PIC X(02). 05 SRT-STATE-CODE PIC X(02).
05 SRT-SALES-DATE PIC 9(08). 05 SRT-SALES-DATE PIC 9(08).
05 SRT-PROD-ID PIC X(02). 05 SRT-PROD-ID PIC X(02).
05 SRT-PROD-PRICE PIC 9(06)V99. 05 SRT-PROD-PRICE PIC 9(06)V99.
05 SRT-PROD-QTY PIC 9(04). 05 SRT-PROD-QTY PIC 9(04).
05 SRT-SALES-AMT PIC 9(08)V99. 05 SRT-SALES-AMT PIC 9(08)V99.

WORKING-STORAGE SECTION.

01 WS-EOF-IN PIC X(1) VALUE ‘N’.


01 WS-EOF-SORT PIC X(1) VALUE ‘N’.

PROCEDURE DIVISION. PROCEDURE DIVISION.

SORT SORT-FILE ON ASCENDING KEY OPEN INPUT IN-FILE


SRT-AGENT-NUM USING IN-FILE GIVING OUTPUT OUT-FILE.
OUT-FILE.
STOP RUN. SORT SORT-FILE ON ASCENDING KEY
SRT-AGENT-NUM
INPUT PROCEDURE IS INPUT-PROC
OUTPUT PROCEDURE IS OUTPUT-PROC.

CLOSE IN-FILE
OUT-FILE.
STOP RUN.

INPUT-PROC.

READ IN-FILE AT END MOVE ‘Y’ TO WS-EOF-IN.


PERFORM UNTIL WS-EOF-IN= 'Y'
IF IN-STATE-CODE = 'AR'
MOVE IN-REC TO SORT-REC
RELEASE SORT-REC
END-IF
READ IN-FILE AT END MOVE ‘Y’ TO WS-EOF-IN
END-READ
END-PERFORM.

OUTPUT-PROC.
RETURN SORT-FILE AT END
MOVE ‘Y’ TO WS-EOF-SORT.
PERFORM UNTIL WS-EOF-SORT= 'Y'
MOVE SORT-REC TO OUT-REC
WRITE OUT-REC
RETURN SORT-FILE AT END
MOVE ‘Y’ TO WS-EOF-SORT
END-RETURN
END-PERFORM.

66
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Variable Length Records

Disadvantages of Fixed length records


When records with different layouts and with different lengths are to be stored in the same file
then create a fixed length file with maximum record length.
Ex: A transaction file that is allowed to write 3 different transaction types with three different
lengths as shown below.
1. Deposit transaction with length 500
2. Withdrawal transaction with length 1000
3. Transfer transaction with length 2000

In this case if a fixed length file is to be created then it has to be created with 2000 length.
Pad a filler in the end of the layout for smaller lengthen records to make it 2000 length.
If the above file is having 3 different transactions it will take a memory of 6000 bytes. Total
memory wasted in these 3 records are 2500 bytes i.e. 1500 bytes from Deposit and 1000 bytes
from withdrawal transaction.

FB Declaration in COBOL program

SELECT TRX-FILE ASSIGN TO TRXFLE.


FD TRX-FILE.
01 DEPOSIT-REC.
05 DEPOSIT-TRX PIC X(02).
05 DEPOSIT-ACCT PIC X(10).
05 DEPOSITEE-NAME PIC X(10).
05 DEPOSIT-BANK PIC X(10).
.
.
05 DEPOSITOR-PAN-NUM PIC X(10).
05 FILLER PIC X(1500).
01 WITHDRAWL-REC.
05 WITHDRAWL-TRX PIC X(02).
05 WITHDROYEE-NAME PIC X(20).
05 WITHDRAWL-CHECK-NUM PIC X(06).
05 WITHDRAWL-BANK PIC X(10).
.
.
05 WITHDRAWL-BRANCH PIC X(03).
05 FILLER PIC X(1000).
01 TRANSFER-REC.
05 TRANSFER-TRX PIC X(02).
05 FROM-ACCOUNT PIC X(10).
05 FROM-BANK PIC X(10).
05 TO-ACCOUNT PIC 9(09)V99 COMP-3.
05 TRANSFER-AMOUNT
.
.
05 PAYEE-NAME PIC X(30).

Move values to corresponding records and write it.


MOVE VALUES TO THE FIELDS OF DEPOSIT-REC
WRITE DEPOSIT-REC.

MOVE VALUES TO THE FIELDS OF WITHDRAWL-REC


WRITE WITHDRAWL-REC.

MOVE VALUES TO THE FIELDS OF TRANSFER-REC


WRITE TRANSFER-REC.

67
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Declaration in JCL
//TRXFLE DD DSN=TSO.USERID.DLYTRX,
// DISP=(NEW,CATLG,DELETE),
// UNIT=SYSDA,
// SPACE=(CYL,(10,5),RLSE)
// DCB=(RECFM=FB,LRECL=2000,BLKSIZE=0)
In this situation Variable length records are used to save the memory effectively.

How the memory is effectively saved from Variable length records


For the above case create a VB file instead of FB file. It should have record varying and
depending clause in FD entry. It varies from minimum to maximum length depending on length
field declared in working storage. Move exact length of the record to the length field before
writing a record.
Variable length records takes 4 extra bytes than the actual length that is moved. These extra 4
bytes in every record is reserved to capture the length of the record.
LRECL in the JCL should be given 4 extra bytes than the maximum record length.
LRECL in JCL = Maximum record length in COBOL + 4

1. Deposit transaction with length 500 takes 504 bytes in JCL


2. Withdrawal transaction with length 1000 takes 1004 bytes in JCL
3. Transfer transaction with length 2000 takes 2004 bytes in JCL
Total length for 3 records = 504 + 1004 + 2004 = 3512
Total memory saved for 3 records from FB to VB = 6000 - 3512 = 2488

VB Declaration in COBOL program

SELECT TRX-FILE ASSIGN TO TRXFLE.


FD TRX-FILE
RECORDING MODE IS V
RECORD VARYING FROM 500 TO 2000 CHARACTERS
DEPENDING ON OUTFILE-LENGTH.

01 DEPOSIT-REC.
05 DEPOSIT-TRX PIC X(02).
05 DEPOSIT-ACCT PIC X(10).
05 DEPOSITEE-NAME PIC X(10).
05 DEPOSIT-BANK PIC X(10).
.
05 DEPOSITOR-PAN-NUM PIC X(10).
01 WITHDRAWL-REC.
05 WITHDRAWL-TRX PIC X(02).
05 WITHDROYEE-NAME PIC X(20).
05 WITHDRAWL-CHECK-NUM PIC X(06).
05 WITHDRAWL-BANK PIC X(10).
.
05 WITHDRAWL-BRANCH PIC X(03).
01 TRANSFER-REC.
05 TRANSFER-TRX PIC X(02).
05 FROM-ACCOUNT PIC X(10).
05 FROM-BANK PIC X(10).
05 TO-ACCOUNT PIC 9(09)V99 COMP-3.
05 TRANSFER-AMOUNT
.
05 PAYEE-NAME PIC X(30).

WORKING-STORAGE SECTION.
01 OUTFILE-LENGTH PIC 9(4) COMP.

68
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Move values to corresponding records and also move its length before you write it.
MOVE VALUES TO THE FIELDS OF DEPOSIT-REC
MOVE 500 TO OUTFILE-LENGTH
WRITE DEPOSIT-REC.

MOVE VALUES TO THE FIELDS OF WITHDRAWL-REC


MOVE 1000 TO OUTFILE-LENGTH
WRITE WITHDRAWL-REC.

MOVE VALUES TO THE FIELDS OF TRANSFER-REC


MOVE 2000 TO OUTFILE-LENGTH
WRITE TRANSFER-REC.

Declaration in JCL

//TRXFLE DD DSN=TSO.USERID.DLYTRX,
// DISP=(NEW,CATLG,DELETE),
// UNIT=SYSDA,
// SPACE=(CYL,(10,5),RLSE)
// DCB=(RECFM=VB,LRECL=2004,BLKSIZE=0)

Variable lengthen records with OCCURS DEPENDING clause

If record of the file contains OCCURS with DEPENDING clause then it will become a variable
lengthen record.

FD EMP-FILE
RECORDING MODE IS V
RECORD VARYING FROM 48 TO 228 CHARACTERS
DEPENDING ON OUTFILE-LENGTH.

01 EMP-REC.
05 EMP-NUM PIC X(4).
05 EMP-NAME PIC X(20).
05 EMP-DOJ PIC X(8).
05 EMP-CHILD-STATUS PIC X(1).
05 EMP-CHILDREN-NUM PIC 9(1).
05 EMP-CHILDREN-INFO OCCURS 1 TO 10 TIMES DEPENDING ON EMP-CHILDLREN-NUM.
10 CHILD-NAME PIC X(20).
10 CHILD-AGE PIC 9(2).
10 CHILD-DOB PIC X(8).

WORKING-STORAGE SECTION.
01 OUTFILE-LENGTH PIC 9(4) COMP.

Here the number of occurrences in EMP-CHILDREN-INFO are created based on the value
another field EMP-CHILDLREN-NUM in the same record. Length of one record varies from
another record based on the value stored in the field EMP-CHILDREN-NUM.

Some employees may not have children but still one occurrence should be created with
spaces filled into it. For this exception, check the value of the field EMP-CHILD-STATUS. If it
is 'N', then don't consider the EMP-CHILDREN-INFO.

Record with occurs depending clause becomes a variable lengthen record. In the above example,
record length varies from minimum length 48 (28 + 20) to maximum length 228 (28 + 20 * 10).
LRECL in JCL should have 228 + 4 = 232.

69
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

COBOL COMPILATION

PARM (Compiler Options)


SYSPRINT (Compiler listing)

SYSIN
IGYCRCTL
SRCLIB(pgm1),disp=shr (COBOL COMPILER)

SYSLIN (Object Module)


SYSLIB (Copybook Library) &&obj,disp=(new,pass)

SYSLIN(Object Module)
&&obj,disp=(old,delete)

SYSLMOD IEWL PARM (Link edit options)


LOADLIB(pgm1),disp=shr (Link Editor)

SYSLIB
(Subprogram load Library)
SYSPRINT
(Link edit messages)

COMPILATION JCL
//TESTCOMP JOB,'COMPILATION JCL',MSGCLASS=X,MSGLEVEL=(1,1),CLASS=C
//COMPILE1 EXEC PGM=IGYCRCTL,PARM=(DYNAM,XREF,SSRANGE,MAP,OFFSET..)
//STEPLIB DD DSN =SYS1.COB2LIB,DISP=SHR
//SYSIN DD DSN =USERID.SRCLIB(PGM1),DISP=SHR  SOURCE PROGRAM
//SYSLIB DD DSN =UERID.COPYLIB,DISP=SHR  COPY LIBRARY
//SYSPRINT DD SYSOUT =*
//SYSLIN DD DSN =&&OBJ,DISP=(MOD,PASS),
// DCB=(RECFM=FB,LRECL=80,BLKSIZE=0),
// UNIT=SYSDA,SPACE=(CYL,(10,5),RLSE)
//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))  CODE SYSUT1 TO UT7
//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//LINKEDT1 EXEC PGM=IEWL,COND=(4,LT)
//SYSLIN DD DSN=&&OBJ, DISP=(OLD,DELETE)  OBJECT MODULE FROM
//SYSLMOD DD DSN=USERID.LOADLIB(PGM1),DISP=SHR  LOAD MODULE
//SYSLIB DD DSN=USERID.LOADLIB,DISP=SHR  SUBPROGRAM LOADLIBRARY
//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSPRINT DD SYSOUT=*

Different actions of COMPILE step


1. Expands copybooks declared in the program from the copy library given in SYSLIB.
2. Checks syntax errors of COBOL code.
3. Generates compile listing where errors are generated.
4. Generates object code which will be given to LINK EDIT.

70
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Action of LINK EDIT step


Expands load module of the sub-program given in the SYSLIB and generates load module for the
main program.

RUN JCL
//TESTRUN1 JOB ,'RUN JCL', MSGCLASS=X,MSGLEVEL=(1,1),CLASS=C
//STEP1 EXEC PGM=PGM1
//STEPLIB DD DSN=TSO.LOADLIB,DISP=SHR  LOAD LIBRARY
//INFILE DD DSN=TSO.INFILE,DISP=SHR  INPUT FILE
//OUTFILE DD DSN=TSO.OUTFILE,DISP=(NEW,CATLG,DELETE),  OUTPUT FILE
// DCB=(RECFM=FB,LRECL=80,BLKSIZE=0),
// UNIT=SYSDA,SPACE=(CYL,(10,5),RLSE)
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*

Compiler Options

The default options that were set up when your compiler was installed are in effect for your
program unless you override them with other options. To check the default compiler options
your installation, do a compile and check in the compilation listing.

Ways of overriding the default options


1. Compiler options can be passed to COBOL Compiler Program (IGYCRCTL) through the
PARM in JCL.
2. PROCESS or CBL statement with compiler options, can be placed before the identification
division.
3. If the organization uses any third party product or its own utility then these options can be
coded in the pre-defined line of the utility panel.

ADV
It is meaningful if your program has any printer files with WRITE..ADVANCING keyword.
Compiler adds one byte prefix to the original LRECL of printer file for printing The control
purpose. If you are manually populating printing control character in the program, then you can
compile your program with NOADV.

DYNAM
Use DYNAM to cause separately compiled programs invoked through the CALL literal statement
to be loaded dynamically at run time. DYNAM causes dynamic loads (for CALL) and deletes
(for CANCEL) of separately compiled programs at object time. Any CALL identifier statements
that cannot be resolved in your program are also treated as dynamic calls. When you specify
DYNAM, RESIDENT is also put into effect.

LIST/OFFSET
LIST and OFFSET are mutually exclusive. If you use both, LIST will be ignored. LIST is used
to produce listing a listing of the assembler language expansion of your code.
OFFSET is used to produce a condensed Procedure Division listing. With OFFSET, the procedure
portion of the listing will contain line numbers, statement references, and the location of the first
instruction generated for each statement. These options are useful for solving system ABENDS.

MAP
Use MAP to produce a listing of the items you defined in the Data Division.

71
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

SSRANGE
If the program is compiled with SSRANGE option, then any attempt to refer an area outside the
region of the table will abnormally terminate with protection exception, usually S0C4.It also
avoids any meaningless operation on reference modification like negative number in the starting
position of reference modification expression. If the program is compiled with
NOSSRANGE, then the program may proceed further with junk or irrelevant data. So usually the
programs are compiled with SSRANGE during development and testing.

RENT
A program compiled as RENT is generated as a re-entrant object module. CICS program should
be compiled with RENT option to share the same copy of the program by multiple
transactions (Multithreading)

RESIDENT
Use the RESIDENT option to request the COBOL Library Management Feature. (The COBOL at
Library Management Feature causes most COBOL library routines to be located dynamically
run time, instead of being link-edited with the COBOL program.).CICS Programs should be
compiled with RESIENT option.

XREF
Use XREF to get a sorted cross-reference listing. EBCDIC data-names and procedure-names will
be listed in alphanumeric order. It also includes listing, where all the data-names that are
referenced within your program and the line number where they are defined. This is useful for
identifying the fields that are defined but not used anywhere after the development of new.

72
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

Different ways to pass data from JCL to COBOL

SYSIN DD * JCL Parm File

In JCL In JCL In JCL

//STEP1 EXEC PGM=PGM1 //STEP1 EXEC PGM=PGM1,PARM=(VALUE) //STEP1 EXEC PGM=PGM1


//SYSIN DD * //DD1 DD DSN=OZA183.AGT.SALES,
20111125 // DISP=SHR
/*

In COBOL In COBOL In COBOL


Accept WS-DATE
LINKAGE-SECTION. Select logical-file ASSIGN to DD1.
01 LS-VARIABLES.
one line in SYSIN DD * is 05 LS-LEN PIC S9(4) COMP. DATA DIVISION.
accepted into single Accept 05 LS-VAR1 PIC X(N) FILE SECTION.
PROCEDURE DIVISION USING FD logical-file.
statement LS-VARIABLES. 01 logical-rec.
05 FIELD1 PIC X(N).
maximum 80 chars can be maximum 100 chars can be passed 05 FIELD2 PIC X(M).
passed into single line .
from PARM .
.
Zoned numeric with V, S Zoned numeric with V, S PROCEDURE DIVISION.
Compressed formats are Compressed formats are not OPEN logical-file.
not recommonded READ logical-file.
recommended

It is used to pass control It is used to pass control It is common procedure to pass


information to COBOL information to COBOL processing data from JCL to program.

It is rare used in real progs It is commonly used in real programs Single record is received into logical-rec
repeat read process until end of file.
If procs used, then use
Control member to pass it.

73
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL

74
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

JCL

1
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

2
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

JCL
JCL is a Job Control language to submit a job that is executed in the operating system.

Purpose
JCL is used for the below activities
1. To compile COBOL, COBOL+DB2, COBOL+DB2+CICS programs
2. To execute both user defined and utility programs
3. To supply load libraries of user defined COBOL/COBOL DB2 programs
4. To supply input files and output files that is required for a step

Types of JCLs

Compile JCL Run JCL

To compile COBOL To run COBOL program


COBOL + DB2 COBOL + DB2 programs
COBOL + CICS Utility programs
COBOL + DB2 + CICS Combination of all above
BMS Maps

Different Fields in JCL

Name Operation Operand


Jobname JOB Position parameters
Stepname EXEC Keyword parameters
DDname DD

Coding Rules
Cols
1234----10 72

First two characters should be two forward slashes //

Third character should be name filed or a comment or space for a continuation


Name field Comment Continuation
//JOBNAME //* This is a comment //JOB1 JOB ACTG(8012T),'SAMPLE JOB’,
//STEPNAME // CLASS=A, PRTY=9,...
//DDNAME Continuation should start between 4 and 16

Null statement
//

How to code name, operation and operand fields


//NAMEFLD OPERATION OPERAND1,OPERAND2,
// OPERNAD3,OPERAND4...

3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

JOB STATEMENT

//JobName JOB ACTG(xyz),'PROGRAMER NAME',CLASS=A,PRTY=9,


// MSGCLASS=A,MSGLEVEL=(1,1),TIME=(MM,SS),
// NOTIFY=USERID,REGION=0M,RESTART=STEPNAME,
// COND=(0,NE),OUTLIM=8M,TYPERUN=SCAN
JobName
It is required to identify this job from other jobs in the SPOOL
1. 1 to 8 characters. Minimum is 1 character and maximum is 8 character
2. 1st character must be alphabet
3. Other characters can be alphabets or numerics or $, @, #
Common naming convention of jobs that are migrated to production
ABCDEFGH
A - Is environment. T/I/M/P
BCD - Is system name. To identify system name from other system jobs
E - Occurrence . D/W/M/Q/Y/S
Daily
Weekly
Monthly
Quarterly
Yearly
Special
FGH - Unique name of the job within the system

Sample jobnames: TACSD010 TACSDASR TL70DBKB


IACSD010 IACSDASR IL70DBKB
MACSD010 MACSDASR ML70DBKB
PACSD010 PACSDASR PL70DBKB
Job names for personal jobs or lab sessions
Userid+1/2 chars
OZA183C1 -- Userid is OZA183
OZA184R1 -- Userid is OZA184

Accounting info
It is a positional parameter and codes it after JOB statement.
It is used to capture the CPU time for the billing purpose.
It is installation defined. Use a ',' if it is not coded
Real time Examples: (8012T)
(8012I)
(8012M)
(8012P)
Lab: OZA

Programmer name
It is used to identify the programmers name. It can be maximum of 20 chars
Though it is a programmer name but it is used to give a brief description of the job.
Ex1: //TACSDASR JOB (99324T),'MADHU PADALA'
Ex2: //TACSDASR JOB (99324T),'AGENT SALES REPORT'
ASR Cannot give brief information.

4
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Class
It is a keyword parameter. It has single character from A-Z
It says about the JOB queue that this job is routed.
It says about maximum time a job can be executed in the class.

Each class has priorities on resources over the other classes


Real time Examples: CLASS=P -- Production class
CLASS=M -- Model/UAT class
CLASS=I -- SIT Class
CLASS=A/B/C -- Test Class
A - Short Running Class
B - Long waiting class
C - Long Running Class
In test region more users submit their jobs, so more classes required.
In SIT/UAT/PROD most of jobs are submitted one after the other.

PRTY
It is a keyword parameter.
It increases the priority when the job is waiting in a Queue.
It has no effect on the jobs that are already executing.
It has a range of values from 1 to 15. 1 is least and 15 is highest.
In most of installations, permission are not given to the users to code it.
Because everyone submits their jobs with highest priority. So the purpose of this
parameter is misused.
Session jobs execute with 15 and all other jobs execute with 9.

MSGCLASS
It is a keyword parameter.
It says about the device name where the job output messages are written.
It has valid values from A to Z.
Real time examples: MSGCLASS=X -- Spool
MSGCLASS=L -- SAR
Lab: MSGCLASS=A

MSGLEVEL
It is a keyword parameter.
It has two positional sub parameters. One is statements and another is Messages.
Ex: MSGLEVEL= (1,1)
Statements indicates which job control statements to be printed
0 The system prints the JOB statement and all comments and JECL
statements up to the first EXEC statement.
1 The system prints all JCL statements, JES2 or JES3 control statements,
the procedure statements, and IEF653I messages, which give the values
assigned to symbolic parameters in the procedure statements.
2 The system prints only JCL statements and JES2 or JES3 control statements

Messages indicates which system messages is to be printed


0 The system prints only JCL messages. It prints JES and operator messages only if
the job abnormally terminates, and prints SMS messages only if SMS fails the job.
1 The system prints JCL, JES, operator, and SMS messages.

5
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

NOTIFY
It is a key word parameter.
It is required to notify to the user when the job successfully executes or fails.
If it is not coded, then user has to check the status of the job from the spool.
It has two methods.
NOTIFY=USERID . When userid is given then it will notify to the given user.
NOTIFY=&SYSUID. When &SYSUID is given then it will notify to the user whoever
submits it.

REGION
It is a keyword parameter.
It allocates address space required to execute a job.
If the address space is not sufficient then job fails with S804 abend.
REGION=8M -- It allocates 8 Million bytes address space.
REGION=0M -- It allocates maximum address space required for the job.

TIME
It is a key word parameter.
It is used to change the default time set by the CLASS
It has two positional sub parameters as shown below.
TIME=(MM,SS) -- MM is minutes and SS is seconds.
Ex: TIME=(10,20) -- Job executes 10 minutes and 20 seconds
TIME=10 -- Job executes 10 minutes
TIME=(,15) -- Job executes 15 seconds
If the time is not sufficient then job fails with S322 abend.

TYPRUN
This parameter requests special processing for the job.
General Syntax
TYPRUN={HOLD/SCAN}
HOLD - Job will held (and not executed temporarily) until the operator uses a command to
release.
SCAN – Job will be scanned for all syntactical JCL errors but will not execute.
In many installations, the below commands are used to find the syntactical JCL errors. With these
commands errors can be checked without submitting JCL.
!JCK
JSCAN
JEM

Restart
It is used to start the job from the required step of the job. I.e. Skip the initial steps.

Method1:
RESTART=JOBSTEP  Execute the job from the jobstep
//JOB1 JOB (8012T),'MADHU PADALA',RESTART=JS30
//JS10 EXEC PGM=PGM1
//JS20 EXEC PGM=PGM2
//JS30 EXEC PGM=PGM3
//JS40 EXEC PGM=PGM4
It will restart the job from JS30

6
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Method2:
RESTART=JOBSTEP.PROCSTEP -- Execute the job from the jobstep

//JOB1 JOB (8012T),'MADHU PADALA', //PROC1 PROC ENV=T


// RESTART=JS10.PS20 //*
//JOBLIB DD DSN=USERID.LOADLIB,DISP=SHR //PS10 EXEC PGM=PGM1
//* //INFILE DD DSN=&ENV.ABC.PSEQ.FILE1,DISP=SHR
//PROCCALL JCLLIB ORDER=USERID.PROCLIB1 //OUTFILE DD DSN=&ENV.ABC.PSEQ.FILE1,
//* // DISP=(NEW,CATLG,DELETE),
//JS10 EXEC PROC1 // ..
// ENV=T //PS20 EXEC PGM=PGM2
//INFILE DD DSN=&ENV.ABC.PSEQ.FILE2,DISP=SHR
//OUTFILE DD DSN=&ENV.ABC.PSEQ.FILE3,
// DISP=(NEW,CATLG,DELETE),
// ..
//PS30 EXEC PGM=PGM3
//INFILE DD DSN=&ENV.ABC.PSEQ.FILE3,DISP=SHR
//OUTFILE DD DSN=&ENV.ABC.PSEQ.FILE4,
// DISP=(NEW,CATLG,DELETE),
//

EXEC STATEMENT

PGM
Syntax: PGM=programname
It is used to tell about the program that executes.It may be utility or user defined program.
Loadlib or Steplib are required to execute user defined programs.
Loadlib or Steplib are not required for Utility programs, because these are executed
from the system library.
Subprograms never coded on PGM parameter. These are executed as a part of main program.
Ex1:
//JOBLIB DD DSN=USERID.LOADLIB1,DISP=SHR
//STEP1 EXEC PGM=PGM1

Ex2:
//STEP1 EXEC PGM=PGM1
//STEPLIB DD DSN=USERID.LOADLIB1,DISP=SHR

Ex3:
//STEP1 EXEC PGM=SORT

PARM
Syntax: PARM='value' or PARM=(value)
It is a keyword parameter. It is used to pass control data from JCL to program. Maximum of 100
characters can be passed from JCL to cobol program.
Different parm values can be passed from JCL to program in different runs.
Without changing the program, the program can be controlled from JCL.

Example:
JCL to execute PGM1
//STEP1 EXEC PGM=PGM1,PARM='IND'

7
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Code in PGM1
Linkage-section.
01 ls-var.
05 ls-len pic s9(4) comp.
05 ls-country pic x(3).
procedure division using ls-var.
.
.
Read emp-file.
if emp-country = ls-country
perfrom process-data.

If the PARM='USA' is used, then it will process file for USA country code.

Time, Cond, Region parameters

The above parameters can be coded both in Job and Step Level

Cond Parameter
Job Level Step Level

Condition applied for all steps of the job. Condition is applied only on single step.
When return code of any step in the job When return code of prior step is true
is true with condition code on Job then then this step is bypassed
all other steps are bypassed

Syntax:

Method1
COND=(CC,RO,STEPNAME)
CC -- Condition code to be checked
RO -- Relation operation
Stepname -- Return code of Prior step Name

//STEP1 EXEC PGM=PGM1


//STEP2 EXEC PGM=PGM2,COND=(4,LT,STEP1)
Step2 executes only when Step1 is returning <= 4

Method2
COND=(CC,RO)
Stepname is optional. When omitted, it takes maximum return code of the prior steps.

//STEP1 EXEC PGM=PGM1


//STEP2 EXEC PGM=PGM2
//STEP3 EXEC PGM=PGM3
//STEP4 EXEC PGM=PGM4,COND=(0,NE)
Step4 executes when maximum return code of the prior steps is zero.

8
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Method3
COND=EVEN/ONLY
It is used to execute steps based on abends on prior steps. It don't depend on Return codes.
COND=EVEN It executes even if the prior step abends
COND=ONLY It executes only of the prior step abends

These are used at step level but not job level.


System Abends S122 and S222 has no effect on COND=ONLY or COND=EVEN

Important points:
JOBLIB with COND=ONLY
If the job contains a JOBLIB DD statement and ONLY is specified in a job step, the
JOBLIB unit and volume information are not passed to the next step; when the next
step is executed, the system searches the catalog for the JOBLIB data set.
Few examples on condition code
//JOB1 JOB .....
//..
//STEP1 EXEC PGM=PGM1
//STEP2 EXEC PGM=PGM2
//STEP3 EXEC PGM=PGM3

Condition at step level for the above code

Case1: Execute STEP2 only when STEP1 Case2: Execute STEP2 only when STEP1
Returns zero. Returns <= 4
//STEP2 EXEC PGM=PGM2,COND=(0,NE,STEP1) //STEP2 EXEC PGM=PGM2,COND=(4,LT,STEP1)

Case3: Execute STEP3 only when prior steps Case4: Execute STEP2 only when STEP1
Return zero. Returns >= 4
//STEP3 EXEC PGM=PGM3,COND=(0,NE) //STEP2 EXEC PGM=PGM2,COND=(4,GT,STEP1)

Case5: Never execute STEP3 Case6: Execute STEP3 only when prior steps
abend
//STEP3 EXEC PGM=PGM3,COND=(0,LE) //STEP3 EXEC PGM=PGM3,COND=ONLY
OR
//STEP3 EXEC PGM=PGM3,COND=(4095,GE)

Case7: Execute STEP3 when prior steps


abends or not
//STEP3 EXEC PGM=PGM3,COND=EVEN

Condition at job level for the above code

Case1: Execute job when prior step Case2: Execute only STEP2
returns <= 4
//JOB1 JOB .....,COND=(4,LT) //JOB1 JOB .....,RESTART=STEP2,COND=(0,LE)

9
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Condition at both job level and step level

//JOB1 JOB ...,COND=(4,LT)


//..
//STEP1 EXEC PGM=PGM1
//STEP2 EXEC PGM=PGM2,COND=(0,NE)
//STEP3 EXEC PGM=PGM3

Case1: If step1 returns 4


Condition on step2 overrides condition on JOB so STEP2 bypassed

Case2: If step1 returns 8


Condition on step2 overrides condition on JOB but job is stopped before condition on
step2 is checked.

Conclusion
Condition on step overrides condition on Job. But condition on JOB is checked before
condition on step is checked. If a job level condition is true then all successive
steps are bypassed.

Q: There are 6 steps in a JCL. Execute 4, 5, 6 only when first 3 steps executes with 0.
//JOB1 JOB .....
//STEP1 EXEC PGM=PGM1
//STEP2 EXEC PGM=PGM2
//STEP3 EXEC PGM=PGM3
//STEP4 EXEC PGM=PGM4,COND=(0,NE)
//STEP5 EXEC PGM=PGM5,COND=((0,NE,STEP1),(0,NE,STEP2),(0,NE,STEP3))
//STEP6 EXEC PGM=PGM6,COND=((0,NE,STEP1),(0,NE,STEP2),(0,NE,STEP3))

Time Parameter
//JOB1 JOB ........,TIME=3
// .
// .
//STEP1 EXEC PGM=PGM1,TIME=2
//STEP2 EXEC PGM=PGM2,TIME=2

Case1: If step1 executes more than 2 min Case2: If step1 executes 2 min
and step3 exceeding 1 min
Job abends at STEP1 with S322 Job abends at STEP2 with S322

Conclusion: Time at step overrides Job but overall time is considered from JOB

Region Parameter
//JOB1 JOB ........,REGION=8M
// .
// .
//STEP1 EXEC PGM=PGM1,REGION=6M
//STEP2 EXEC PGM=PGM2
Both STEP1 and STEP2 takes 8M address space.

10
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

DD STATEMENT

It is important operation in JCL.


It is used to provide
1. Input and output files to the program given in EXEC statement.
2. System defined ddnames which prints output messages to the spool.
SYSOUT, SYSPRINT, SYSDUMP, SYSABEND
3. loadlibraries to execute user defined programs with Joblib/Steplib.
4. Instream data to the user defined programs with SYSIN.
5. Control information to the utility programs with SYSIN.

Syntax:
//ddname DD operand1,operand2....

Ex1: For input files


//INFILE DD DSN=FILE1,DISP=SHR

Ex2: For output files


//OUTFILE DD DSN=FILE2,
// DISP=(NEW,CATLG,DELETE),
// UNIT=SYSDA,
// SPACE=(CYL,(5,2),RLSE),
// DCB=(RECFM=FB,LRECL=50,BLKSIZE=0,DSORG=PS)

Different operands in DD statement


DSN -- To provide the dataset name
DISP -- To provide the status of the dataset
UNIT -- To provide device name where the dataset is created
VOL=SER -- To provide volume and serial for the tape datasets
SPACE -- To provide the space required for the disk datasets
DCB -- To provide the attributes of dataset

DSN
It is a keyword parameter. It is used to provide the dataset name
Syntax: DSN=AAA.BBB.CCC -- It is dataset name. maximum Len of name is 40

E.g.1 //DDDNAME DD DSN=OZA183.SMF.EMPFILE


Identifies file OZA183.SMF.EMPFILE

E.g.2 //DDNAME DSN=OZA183.SMF.PDS(MEM1)


Identifies a member of a PDS

E.g.3 //DDNAME DD DSN=&&TEMP


It is a temporary dataset that is created in a step and passed to the other steps of the JCL. It is
deleted on normal or abnormal completion of JCL
When a physical existence of the file is not required to pass the data from one step of JCL to
another step of the JCL then temporary dataset is used.

E.g.4 //DDNAME DD
If the DSN name is omitted from a DD statement (except DD * , SYSOUT and DUMMY)
also indicates a temporary dataset.

11
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

E.g.5 //DDNAME DD DSN=NULLFILE


//DDNAME DD DUMMY
If you don’t want to supply a file to the program then use DUMMY or NULLFILE. If it is coded
then all the I/O statements against this file are ignored.

DISP
It is a keyword parameter. It has 3 sub positional parameters
Syntax: DISP=(status,normal-termination,abnormal-termination)
Status -- It says about the initial status of the dataset
Normal-termination -- Action on normal completion
abnormal-termination -- Action on abnormal completion

Possible values on these three sub positional parameters.


Status Normal-Termination Abnormal-Termination
NEW CATLG CATLG
SHR UNCATLG UNCATLG
OLD DELETE DELETE
MOD KEEP KEEP
PASS

NEW -- File is not existing, create it.


SHR -- File is existing, use a dataset in a share mode. Others can use this dataset in SHR mode.
OLD -- Use a dataset in exclusive mode. Others cannot use this dataset.
MOD -- File may or may not be existing.
CATLG -- Catalog dataset in system cataloged entries.
UNCATLG -- Uncatalog dataset from the system cataloged entries. But the file is not
deleted. If it is to be used then use volume and serial information of the file.
DELETE -- Delete system cataloged entry and also dataset.
KEEP -- Keep the dataset in the same cataloged entry along with volume and serial.
PASS -- It is used to pass the dataset to the subsequent steps of the JCL. It is used on datasets
which are created but not cataloged. i.e. for the temporary datasets.

Default disp parameters


If DISP is not coded -- It takes DISP=(NEW,DELETE,DELETE)
DISP=(NEW) -- It takes DISP=(NEW,DELETE,DELETE)
DISP=(NEW,CATLG) -- It takes DISP=(NEW,CATLG,CATLG)
If the third sub parameter is not coded then it takes second parameter as third parameter.
DISP=SHR/OLD -- It takes DISP=(SHR/OLD,KEEP,KEEP)
It keeps the dataset on the same volume and serial
DISP=(NEW,PASS) -- It takes DISP=(NEW,PASS,DELETE)
It is used on temporary datasets. Pass is not allowed in the
abnormal- termination with that reason it takes Delete.

Disp for input files


DISP=SHR -- File should be existing and other users can also use it in SHR
DISP=OLD -- File should be existing and use it in exclusive mode.
Others cannot use it in SHR/OLD mode.
DISP=(OLD,DELETE,KEEP) -- File should be existing and use it in exclusive mode.
-- Delete it on normal completion and keep it on
abnormal completion.

12
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Disp for Output files


DISP=(NEW,CATLG,DELETE) -- Create a new file, catalog it on normal termination
delete it on abnormal termination.
-- It is a common DISP parameters used for output
DISP=(MOD,CATLG,DELETE) -- If the file is existing then appends data
-- If the file is not existing then create it
-- On normal completion catalog it
-- On abnormal completion delete it
DISP=SHR/OLD -- It deletes existing data and writes new data

Disp on files to update


DISP=SHR/OLD -- Update is done only on KSDS VSAM files
-- Existing data can be read, write, update, delete

Disp on Temporary output files


DISP=(NEW,PASS) -- It takes DISP=(NEW,PASS,DELETE)
-- Temporary files are not cataloged.
-- These are created and passed to the next steps in the same JCL.

Disp on Temporary input files


DISP=(OLD,DELETE) -- Use temporary datasets created by the previous steps of the JCL
-- Delete it after using
DISP=(OLD,PASS) -- Use temporary datasets created by the previous steps of the JCL
-- Pass it to next steps of the JCL

Possible Disp parameters for VSAM files


DISP=SHR/OLD -- Existing VSAM datasets can be used in any step
-- These cannot be created with disp parameter
-- These files should be created with IDCAMS utility

Disp to delete output files before these are created


DISP=(MOD,DELETE,DELETE) -- If the file is existing then opens in append mode
otherwise it creates it.
-- File is deleted after use.

Ex: Delete a file before it is created.


//step1 EXEC PGM=IEFBR14  It is a NULL program
//dd1 DD DSN=FILE2,DISP=(MOD,DELETE,DELETE)
//step2 EXEC PGM=PGM1
//infile DD DSN=FILE1,DISP=SHR
//outfile DD DSN=FILE2,DISP=(NEW,CATLG,DELETE),
// UNIT=SYSDA,
// SPACE=(CYL,(10,5),RLSE),
// DCB=(RECFM=FB,LRECL=50,BLKSIZE=0)

13
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

UNIT
It is a keyword parameter. It says about where the dataset is created.
Syntax: UNIT=SYSDA -- Disk
UNIT=TAPE/CART -- Tape or cartridge
Space is required for the Disk file.
Ex: UNIT=SYSDA,SPACE=(CYL,(10,5),RLSE)
UNIT=SYSALLDA,SPACE=(CYL,(10,5),RLSE)
UNIT=3390,SPACE=(CYL,(10,5),RLSE)

VOL=SER
It is used for the tape files.
Volume and serial are required for TAPE/CART files. Huge files file are written on the tape.
Tape files cannot be viewed or edited in ISPF 3.4.These can be processed only in JCL. If you
want to browse data of tape files, then copy into disk file and then browse it.

Ex: UNIT=TAPE,VOL=SER=(,,,9)
UNIT=CART,VOL=SER=(,,,9)

SPACE
It is a keyword parameter. It has sub positional parameters. Space parameter is required on output
files that are created on DISK.

Syntax: SPACE=(Unit-size,(primary-space,secondary-space,directory-blocks),rlse,contig)
Unit-size -- CYL/TRK
Primary-size -- numeric value -- Initially System allocates primary space.
Secondary-size -- numeric value -- If the primary space is not sufficient, then system
will create 15 extents of secondary space.
Directory-blocks -- Numeric value -- It is required only for PDS. It tells about the
maximum number of members required.
maximum number of members = (num of directory blocks * 6) - 1
Rlse -- Release excess memory that is allocated but not utilized.
Contig -- Allocate continuous memory in the tracks.

Ex1: SPACE=(CYL,(10),RLSE)
It allocates maximum of 10 cyls. If it is not sufficient then it abends with SD37.
Code secondary space if it abends.

Ex2: SPACE=(CYL,(10,5),RLSE)
It allocates maximum of 85 cyls. If it is not sufficient then it abends with SB37.
Increase primary and secondary space.
It allocates 10 cylinders of primary space. If it is not sufficient then it allocates 5 cylinders of
secondary space and it allocates 15 times.Maximum space allocated = 10 + 15 * 5 = 85 cylinders.
SPACE=(CYL,(10,5),RLSE) -- It allocates maximum of 85 cyls

Ex3: SPACE=(CYL,(10,5,10),RLSE)
It allocates maximum of 85 cyls.Maximum 59 members can be created.
If the above space is not sufficient then it abends with SE37.If it abends then first compress
dataset by using Z infront of the PDS.
In general, PDS is not created with BATCH JCL. It is created with ISPF 3.2.

14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

DCB
It is a keyword parameter. It has sub positional key word parameters.
Syntax: DCB=(RECFM=Record-format,LRECL=number,BLKSIZE=number/0,DSORG=PS/PO)

RECFM sub parameter


Record-format -- F/FB/V/VB/U
F -- Fixed length.
FB -- Fixed length blocked. I-O device reads block full of records at a time and keeps it
into main memory. It improves the performance of I-O operation.
In both F and FB, every record of the file has same length.
On F, I-O device reads one record and returns to program.
On FB, it reads block full of records and are kept in main memory. It improves
the performance of the I-O operations.LRECL in JCL = record length in COBOL

V -- Variable length. I-O device reads one record at a time.


VB -- Variable length blocked-O device reads block full of records at a time and keeps it
into main memory. It improves the performance of I-O operation
In both V and VB, each record may have different length.
On V, I-O device reads one record and returns to program.
On FB, it reads block full of records and are kept in main memory. It improves the performance
of the I-O operations. LRECL in JCL = Length of longest record in COBOL + 4 .
U -- Undefined length.

LRECL sub parameter


It is logical record length.

BLKSIZE sub parameter


BLKSIZE=Lrecl * n -- If it is coded then code it multiples of LRECL
BLKSIZE=0 -- If zero is coded then system uses the best blksize. Usually it is 32760.
It is always recommended to code BLKSIZE=0

DSORG sub parameter


It says about the dataset type.
DSORG=PS/PO -- PS is used for physical sequential files
-- PO is used for PDS
-- If it is omitted it takes PS.

How to supply a dummy dataset


//ddname dd DUMMY
If DUMMY is used, then other operands should not be coded. All I-O operations
on this DDNAME are ignored.

Job stream input


To include input data as part of a job stream, code the following
//DDNAME DD *
. (actual data/source data set)
.
.
/*
//  The NULL statement is the default end of input data

15
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

• DATA parameter
DATA parameter should be specified if you want to include // in the input data stream
//DDNAME DD DATA
.
.
//
/*
The last statement specifies the end of input data and should be coded without fail.

• DLIM parameter
When you want to enter /* in the input stream,then code a delimiter statement
to indicate the end of a input stream.
//DDNAME DD *,DLM=XX or //DDNAME DD DATA,DLM=XX
.
.
//XX

Printer statements
//DDNAME DD SYSOUT=CLASS,OUTLIM=5000,COPIES=2
The sysout parameter is used to direct output to a printer
When * is coded for sysout class(backward reference),the dataset is automatically sent to the
same output class as in the MSGCLASS parameter of the JOB statement
OUTLIM parameter controls the number of lines printed in the output.

Concatenation of datasets
Data set concatenation allows several physical datasets to be treated as a single logical dataset
for input.
Concatenated datasets are requested by coding a DD statement for each dataset to be
concatenated,and placing the DD statements in the order in which the datasets are to be processed
Only the first DD statement has a ddname The datasets that are to be concatenated should have
same DCB parameters
Ex: //JOBLIB DD DSN=ENDVR.TEST.ACS.LOADLIB,DISP=SHR
// DD DSN=ENDVR.INTG.ACS.LOADLIB,DISP=SHR
// DD DSN=ENDVR.MODL.ACS.LOADLIB,DISP=SHR
// DD DSN=ENDVR.PROD.ACS.LOADLIB,DISP=SHR

In the above example, Load libraries of Test, Integration, UAT/Model and Production
environments are concatenated.
1.16 PDS OR 255 sequential datasets can be concatenated.
2 .Lrecl and record format should be same.
3. If the block size is different, then largest block size dataset should be first.
4. Datasets may reside on different devices and device types.

16
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Special ddnames

SYSOUT
Syntax:
//SYSOUT DD SYSOUT=*
This ddname is required to print the output messages of the program. Display statements given in
the program are routed SYSOUT. Brief information of the user abends are routed to SYSOUT

SYSIN
Syntax:
//SYSIN DD *
Data
/*
It is used to pass the instream data to the cobol program. One line is accepted to one accept
statement. Maximum of 80 characters can be passed in a single line. It is also used to pass the
control information to utility program.

How to pass data from SYSIN to COBOL


Code in JCL
//STEP1 EXEC PGM=PGM1
.
. .
//SYSIN DD *
20120129
/*
In program
01 ws-date pic x(8).
procedure division.
.
.
ACCEPT WS-DATE.

SYSPRINT
Syntax: //SYSPRINT DD SYSOUT=*
It is used for utility programs to route utility execution or error messages.

SYSABEND:
Syntax: //SYSABEND DD SYSOUT=*
This system dd name identifies the dataset for formatted dump of control blocks and program,
used if the program fails.

SYSDUMP
Syntax: //SYSDUMP DD SYSOUT=*
It is used to route dump messages on abends.

JOBLIB: It follows the job statement.loadmodules of any steps(EXEC) that don't have
respective steplib will be looked into this PDS. If not found, it will be checked against system
libraries. if it is not found there also, then the job would abend with s806. It is only DDNAME
used without a EXEC statement.

STEPLIB: It follows exec statement.loadmodules will be checked first in this library and then in
the system libraries. if it is not found in both places, then the job would abend with S806 code.

17
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Referback
Referback permits to obtain information from previous JCL statements in the job stream. It can be
used for DSN, DCB, PGM parameters. ‘*’ is a referback operator.

Referback on PGM.
//STEP2 EXEC PGM=*.STEP1

Referback on DD statement
It has three formats
1. Referback dataset name of a DDNAME from the prior step.
*.stepname.ddname
Ex :DSN=*.STEP1.DD1

2. Referback dataset name of another DDNAME from the same step.


*.ddname
Ex :DSN=*.DD1

3. Referback dataset name of a DDNAME from the prior step of prior proc.
*.procstep-in-JCL.stepname-in-PROC.ddname
Ex :DSN=*.js10.step1.dd1
Same as DSN, DCB can also be coded in three different formats.

Note: Referback is not recommended because it reduces readability.

System abends
SOC7

What are the situations to soc7?


1. Uninitialized numeric items (mostly comp-3 items) in the working storage.
2. Non numeric data in the file is mapped to a numeric data item and it is used in either MOVE or
COMPUTE statements.
It is most common abend in the production support

How to find statement and record?


1. How to find statement?
1. Take the offset from SYSOUT of RUNJCL in spool
2. Find the offset in the SYSPRINT of compile job in the spool. Program should be compiled
With compile parameters LIST or OFFSET
3. See the line number and verb that is having this offset number
4. Find the line number in the same compile listing from the top. That line will have statement
that is causing the SOC7.

2. How to find the record?


1. Change the program to put a display statement after reading the input file, compile and run
it. This time it will abend again with SOC7 at same location and record.

Now find the last record that is displayed in the spool. That is the record causing the SOC7.

18
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Solution
1. correcting the program
a) If SOC7 is with un initialized comp-3 variables, then initialize it in the working storage or
initialize it in the procedure division before using it in the computation or move statement
b) If it is from file ,then use the business rule whether to write the record into a error file or
move zeros to non-numeric data by validating ‘IS NUMERIC’ class condition.

2. Skip the bad record from input file and restart the program.
a) Find the current record from the AbendAid and skip the record from the input file.
i.e by copying all other records except the abend causing record into a TSO file then
override TSO file and then restart the job.
b) Send the skipped record to the onsite team.

If this program is abending frequently then it is suggested to for a permanent solution by fixing
the program. But it is a user’s decision on how to fix it.

Note: If the job abends with S0C7 in the production then oncall programmer (person who is
working in the production support) will go the with the second solution.

SOC1
1. Misspelled DD name in RUN JCL
DD name not defined in RUN JCL
2. When a correct processor group is not supplied while adding it to the endevor.
3. Subprogram called dynamically and it is not found in the supplied load libraries.
Solution:
1. Correct the DD name
2. Add it with correct processor group
3. Supply the correct load libraries. Most of the cases we forget to give production load libraries
after the personal load libraries.

SOC4
1. Trying to refer an element of occurs beyond max limitation and the program is compiled with
SSRANGE.
2. Trying to open a VSAM file which is not available.
3. Trying to open a VSAM file in I-O mode which is created and no records are written into it.
Solution
1. Correct the program and make sure that it is not going beyond the maximum occurrence.
2. Make sure that the VSAM file is available in the JCL.
3. Write at least one record just before use it.
When a VSAM file is created in the step1 and it is used in the step2 in I-O mode, then insert
one more step in between step1 and step2 to load a sequential file that has two records one
with low values and one with high values. Most of the installations use this solution.

S322
Time out abend
Solution:
1. Check the class parameter, if it is a short running class then change it to long running class
2. If it is already a long running class, then check whether it is in infinite loop or not.
a) If it is in infinite loop then fix the program and rerun it.
b) If it is not in infinite loop then give the time parameter to 1440.

19
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

How to find the job is in infinite loop or not.


While job is running, Go to DA in the spool and the see the CPU % and Exception Count
If a job is running in the infinite loop then it takes more CPU and Exception count is not going to
be changed.

For the confirmation debug the program either with XPEDITER or with display statements.

S806
Load module not found in the load library
Possible reasons:
1. Load library is not supplied in JOBLIB or STEPLIB
2. Main program is not compiled
3. STEPLIB is given and the load module is not found in the STEPLIB, but it is found in the
JOBLIB. when a STEPLIB is given, system will not check the load module in the JOBLIB.
Solution
Supply load module (or) compile the program to correct load library

S913
Authorization failure to read or update a dataset.
Solution:
Run the job by the ZEKE scheduler, so that it will run without any problem.

S013
Source program is not found for the compilation.
Solution
Give the correct library and source name.

Space Abends

SE37
Space not available for new member in PDS
Solution
1. Compress the PDS with line command Z. If it is still abending go for the second solution.
2. Create a new PDS more cylinders and more directory blocks, move all elements from existing
to new PDS,delete old PDS and rename the new PDS to old PDS.

SB37
primary, secondary are declared but not sufficient
Solution
Increase primary and secondary appropriately.

SD37
No secondary space is given
Solution
Give secondary cylinders.

20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Procedures

A procedure is a set of standard JOB step definitions that can be used repeatedly to perform a
FUNCTION. Procedures are invoked by EXEC statements

Rules:
Procedures begin with proc or EXEC statements.
Only statements allowed in a procedure are EXEC, DD & comment.
Cannot have instream data statements in a procedure.
A procedure cannot invoke another procedure.
Cannot contain joblib&jobcatDDnames

Types of PROCS

Instream Proc Cataloged Proc

1. Proc is coded within the JCL 1. Proc is coded in a separate member


2. It can be executed from the same jcl where it 2. It can be executed from any JCL
is coded
3. It has PROC and PEND 3. It has PROC but PEND is not required
4. It is rarely used in personal JCLs 4. It is almost used in every JCL that is
executed from different environment
5. First two chars of every statement in proc is 5. It is expanded as XX
expanded as ++ in JESJCL
6. Override on any statement expands as +/ in 6. On overrides, It is expanded as X/
JESJCL
7. It can be executed 15 times from 7. There is no such a limitation
the same JCL

Ex: Instream proc and its execution


Note: It can be executed 15 times from the same JCL but it cannot be executed from
different JCL.

//JCL1 JOB ....


//..
//PROC1 PROC
//PS10 EXEC PGM=PGM1
//INFILE DD DSN=&ENV.ACS.PSEQ.FILE1,
// DISP=SHR
//OUTFILE DD DSN=&ENV.ACS.PSEQ.FILE2,
// DISP=(NEW,CATLG,DELETE),
//..
//..
// PEND
//*
//JS10 EXEC PROC1,
// ENV=T

21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Ex: Cataloged proc and its JCLs from different environments


Note: When a new JCL is required in production environment, then create 4 JCLs.
1. Test JCL 2. Integration JCL 3. Model JCL 4. Prod JCL
In general, all steps are coded into a cataloged proc with symbolic parameter for High level
qualifier of the file name. Then execute this proc from above 4 JCLs.

//PROC1 PROC ENV=


//PS10 EXEC PGM=PGM1
//INFILE DD DSN=&ENV.ACS.PSEQ.FILE1,
// DISP=SHR
//OUTFILE DD DSN=&ENV.ACS.PSEQ.FILE2,
// DISP=(NEW,CATLG,DELETE),
//..
//..

//TJCL //IJCL
//... //...
//PROCCALL JCLLIB ORDER=PROCLIB1 //PROCCALL JCLLIB ORDER=PROCLIB1
//JS10 EXEC PROC1, //JS10 EXEC PROC1,
// ENV=T // ENV=I

//MJCL //PJCL
//... //...
//PROCCALL JCLLIB ORDER=PROCLIB1 //PROCCALL JCLLIB ORDER=PROCLIB1
//JS10 EXEC PROC1, //JS10 EXEC PROC1,
// ENV=M // ENV=P

Advantage of PROCs

1. Reduced coding with reusable code


2. JCL errors are not promoted to Integration, Model and Prod JCLs
3. Number of steps and ddnames used in the steps will be same for all JCLs
4. Reduced maintenance on below situations
a. When a new step is introduced into existing proc
b. When a new file is introduced into an existing step
c. When an existing file attributes are changed
In all the above cases PROC is impacted but not the JCLS.
PROC is used to execute steps from the different JCLs from different environments.

Proc Overrides

EXEC operands DD operands

PGM DSN
PARM DISP
TIME UNIT
REGION SPACE
COND DCB

Cond Override
1. Make a step not to execute
2. Change the existing cond

22
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

DD override
1. Supply prod file as input instead of test file
2. Change space/DCB parameters of an existing file
3. Override 2nd file of 3 concatenated file
4. Make a file dummy
5. Supply a new DDNAME to an existing step

Test JCL PROC

//JOB1 JOB ...... //PROC1 PROC ENV=


//.. //*
//PROCCALL JCLLIB ORDER=(PROCLIB1, //PS10 EXEC PGM=PGM1,PARM=(IND)
// PROCLIB2) //INFILE DD DSN=&ENV.ACS.PSEQ.FILE1,DISP=SHR
// //OUTFILE DD DSN=&ENV.ACS.PSEQ.FILE2,
//JS10 EXEC PROC1, // UNIT=SYSALLDA,
// ENV=T // DCB=(RECFM=FB,LRECL=22,BLKSIZE=0)
// SPACE=(CYL,(10,5),RLSE)
//PS20 EXEC PGM=PGM2
//INFILE DD DSN=&ENV.ACS.PSEQ.FILE2,DISP=SHR
// DD DSN=&ENV.ACS.PSEQ.FILE2A,DISP=SHR
// DD DSN=&ENV.ACS.PSEQ.FILE2B,DISP=SHR
//OUTFILE DD DSN=&ENV.ACS.PSEQ.FILE3,
// DISP=(NEW,CATLG,DELETE),
//..
//*
//PS30 EXEC PGM=PGM3
//INFILE DD DSN=&ENV.ACS.PSEQ.FILE3,DISP=SHR
//OUTFILE DD DSN=&ENV.ACS.PSEQ.FILE4,
// DISP=(NEW,CATLG,DELETE),
//..
//*
//PS40 EXEC PGM=PGM4
//INFILE DD DSN=&ENV.ACS.PSEQ.FILE4,DISP=SHR
//OUTFILE DD DSN=&ENV.ACS.PSEQ.FILE5,
// DISP=(NEW,CATLG,DELETE),
//..
//*
//PS50 EXEC PGM=PGM5
//INFILE DD DSN=&ENV.ACS.PSEQ.FILE5,DISP=SHR
//OUTFILE DD DSN=&ENV.ACS.PSEQ.FILE6,
// DISP=(NEW,CATLG,DELETE),
//..

23
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Override operands on EXEC statement

Case1: Make PS40 never execute Case4: Restart job from PS30 of PROC1
//JS10 EXEC PROC1, //JOB1 JOB ....RESTART=JS10.PS30
// COND.PS40=(0,LE), //..
// ENV=T //JS10 EXEC PROC1,
// ENV=T

Case2: Change PARM in PS10 to USA Case5: Execute PS30 only


//JS10 EXEC PROC1, //JOB1 JOB ....RESTART=JS10.PS30,
// PARM.PS10=(USA), // COND=(0,LE)
// ENV=T //..
//JS10 EXEC PROC1,
// ENV=T

Case3: Add TIME=10 in PS10 Case6: Execute PS30 and PS50 only
//JS10 EXEC PROC1, //JOB1 JOB ....RESTART=JS10.PS30
// TIME.PS10=10, //..
// ENV=T //JS10 EXEC PROC1,
// COND.PS40=(0,LE),
// ENV=T

Override operands on DD statement

Case1: Override INFILE of PS10 with production file Case2: Override second concatenated file in INFILE of PS20 with
production file

//JS10 EXEC PROC1, //JS10 EXEC PROC1,


// ENV=T // ENV=T
//PS10.INFILE DD DSN=PACS.PSEQ.FILE1, //PS20.INFILE DD
// DISP=SHR // DD DSN=PACS.PSEQ.FILE2A,DISP=SHR
// DD

Case3: Override OUTFILE of PS50 with DUMMY Case4: Supply a new DDNAME INFILE1 in PS10
//JS10 EXEC PROC1, //JS10 EXEC PROC1,
// ENV=T // ENV=T
//PS50.OUTFILE DD DUMMY //PS10.INFILE1 DD DSN=&ENV.ACS.PSEQ.FILE1A,
// DISP=SHR

Case6: Override space parameter to increase space of OUTFILE in


Case5: Concatenate one more file to INFILE of PS30 PS10
//JS10 EXEC PROC1,
//JS10 EXEC PROC1,
// ENV=T
// ENV=T
//PS30.INFILE DD
//PS10.OUTFILE DD SPACE=(CYL,(50,25),RLSE)
// DD DSN=&ENV.ACS.FILE3A,
// DISP=SHR

24
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

GDG (Generation Data Group)


Q: Why is GDG required?
A: When a back dated files are to be retained then use GDG

Q: What are different real situations where GDG is required?


A: Daily Transaction files
Daily backup files
Monthly backup files
Interface files

Q: Steps to use GDG?


A: 1. Create GDG Base with IDCAMS in Batch or in a foreground with 3.2 option in
File Aid
2. Create/use the generations in any JCL

Q: How to create GDG?


A: //STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//SYSOUT DD SYSOUT=*
//SYSIN DD *
DEFINE GDG (NAME(USERID.FILE1.BKP) -
LIMIT(N) -
NOEMPTY/EMPTY -
SCRATCH/NOSCRATCH
/*
N is number from 1 to 255
NOEMPTY - Uncataloged oldest generation when a new generation is created and
limit is already reached
EMPTY - Uncataloged all generation for the above situation
SCRATCH - Delete that uncataloged generation
NOSCRATCH - Do not delete that uncataloged generation
Common used options are NOEMPTY and SCRATCH

Q: How to create a new generation of a GDG?


A: //STEP1 EXEC PGM=IEBGENER
//SYSPRINT DD SYSOUT=*
//SYSOUT DD SYSOUT=*
//SYSUT1 DD DSN=USERID.FILE1,DISP=SHR
//SYSUT2 DD DSN=USERID.FILE1.BKP(+1),
// DISP=(NEW,CATLG,DELETE),
// UNIT=SYSDA,
// SPACE=(CYL,(10,5),RLSE),
// DCB=(RECFM=FB,LRECL=100,BLKSIZE=0)
//SYSIN DD DUMMY

Q: How to use current generation of a GDG as input?


A: //INFILE DD DSN=USERID.FILE1.BKP(0),DISP=SHR

Q: How to use previous generation of a GDG as input?


A: //INFILE DD DSN=USERID.FILE1.BKP(-1),DISP=SHR

Q: How to use all generations of a GDG as input?


A: //INFILE DD DSN=USERID.FILE1.BKP,DISP=SHR

25
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Q: How to delete all generations of a GDG?


A://STEP1 EXEC PGM=IEFBR14
//DD1 DD DSN=USERID.FILE1.BKP,DISP=(MOD,DELETE,DELETE)

Q: How to delete all generations and also GDG base?


A://STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//SYSOUT DD SYSOUT=*
//SYSIN DD *
DELETE USERID.FILE1.BKP FORCE
/*

Q: How to use a new generation created from step1 into step2?


A://STEP1 EXEC PGM=IEBGENER
//SYSPRINT DD SYSOUT=*
//SYSOUT DD SYSOUT=*
//SYSUT1 DD DSN=USERID.FILE1,DISP=SHR
//SYSUT2 DD DSN=USERID.FILE1.BKP(+1),
// DISP=(NEW,CATLG,DELETE),
// UNIT=SYSDA,
// SPACE=(CYL,(10,5),RLSE),
// DCB=(RECFM=FB,LRECL=100,BLKSIZE=0)
//SYSIN DD DUMMY
//*
//STEP2 PGM=PGM1
//INFILE DD DSN=USERID.FILE1.BKP(+1),DISP=SHR
While the job is executing the generations are not upgraded, so use (+1) as input
If STEP2 abends and if you want to restart from STEP2 then make file in step2 as
below

//STEP2 PGM=PGM1
//INFILE DD DSN=USERID.FILE1.BKP(0),DISP=SHR
When the job is abended in step2 the generations are upgraded and (+1) becomes (0)

Q: Current generation on the file is FILE1.G9999.V00. If I create a new generation


with (+1) what happens?
A: FILE1.G0001.V00

Q: On what situation you cannot give GDG base as input?


A: When different generations are created with different lengths

Q: Is it possible to create different generations with different lengths?


A: It is possible but it is not recommended in normal situations.
It is required when the existing file length is increase for future maintenance
From the last 3 months, (+1) generations are created on FILE1 with length 100.
For a new requirement, it is requested to increase from 100 to 110.
In this case old generations will have 100 length and for the new generations it
will create 110.

26
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Q: //JOB1 JOB ......


//..
//STEP1 EXEC PGM=PGM1
//INFILE DD DSN=FILEX,DISP=SHR
//OUTFILE DD DSN=FILEY(+1),DISP=(NEW,CATLG,DELETE),..
//*
//STEP2 EXEC PGM=PGM2
//INFILE DD DSN=FILEZ,DISP=SHR
//OUTFILE DD DSN=FILEY(+2),DISP=(NEW,CATLG,DELETE),..
//*
//STEP3 EXEC PGM=PGM3
//INFILE DD DSN=FILEY(+1),DISP=SHR
//*
//STEP4 EXEC PGM=PGM4
//INFILE DD DSN=FILEY(+2),DISP=SHR

In the above example if Job fails In the above example if Job fails
at Step3 then how do you restart? at Step2 then how do you restart?
Ans: Ans:
//JOB1 JOB ......RESTART=STEP3 //JOB1 JOB ......RESTART=STEP2
//.. //..
//STEP1 EXEC PGM=PGM1 //STEP1 EXEC PGM=PGM1
//INFILE DD DSN=FILEX,DISP=SHR //INFILE DD DSN=FILEX,DISP=SHR
//OUTFILE DD DSN=FILEY(+1), //OUTFILE DD DSN=FILEY(+1),
// DISP=(NEW,CATLG,DELETE),.. // DISP=(NEW,CATLG,DELETE),..
//* //*
//STEP2 EXEC PGM=PGM2 //STEP2 EXEC PGM=PGM2
//INFILE DD DSN=FILEZ,DISP=SHR //INFILE DD DSN=FILEZ,DISP=SHR
//OUTFILE DD DSN=FILEY(+2), //OUTFILE DD DSN=FILEY(+1),
// DISP=(NEW,CATLG,DELETE),.. // DISP=(NEW,CATLG,DELETE),..
//* //*
//STEP3 EXEC PGM=PGM3 //STEP3 EXEC PGM=PGM3
//INFILE DD DSN=FILEY(-1),DISP=SHR //INFILE DD DSN=FILEY(0),DISP=SHR
//* //*
//STEP4 EXEC PGM=PGM4 //STEP4 EXEC PGM=PGM4
//INFILE DD DSN=FILEY(0),DISP=SHR //INFILE DD DSN=FILEY(+1),DISP=SHR

Change generation on step3 as (-1) Change generation on step2 as (+1),


and step4 as (0) step3 as (0) and step4 as (+1)

Spool (Simultaneous peripherals objects online)

When do you go to spool?


To check the below items
1. Job execution status
2. Steps execution status
3. Displayed statements of a program
4. JCL errors on submitted jobs
5. Return code of each step
6. Information about the abended steps
7. Infinite loop
8. Reports written into spool

How to go to the SPOOL?


9;S;ST From ISPF primary option menu

27
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

What are different options in SPOOL?


1. ST -- To check the status of the jobs
2. I -- To check the jobs in Input queue
3. O -- To check the jobs in Output queue
4. H -- To check the held output queue
5. DA -- To check the status of the jobs that are running now.

What are different messages of a job in a SPOOL?


Spool Messages

Job Level Messages Step Level Messages

1. JESMSGLG 1. SYSOUT
It is used to find It is used to find
Start time and end time Display statements of COBOL
Return code or abend code of each step Abend code and offset of variable
CPU and elapsed time of job and step used in abend step
File name on which job is waiting Complete information about U4038
Authorization failures

2. JESJCL 2. SYSPRINT
It is used to find It is used to find
All JCL statements Statistics of Utility program
Proc Expansion statements Number of records read and write
Expansion of symbolic parameters Error messages on utility programs
Overrides given from JCL to PROC

3. JESYSMSG 3. SYSUDUMP
It is used to find It is used find
JCL errors on line numbers in JESJCL Dump information on abends
Allocation failure messages

How to correct JCL errors when a job is failed with JCL errors?
1. Go to JESYSMSG and get the statement number that is causing error
2. Go to JESJCL and find the statement and find the mistake
3. Go to JCL member in PDS and correct it

How to check whether the job is in infinite loop or not?


1. Go to DA in the Spool while the job is running
2. Check the EXCP-CNT and CPU% of the job
If the EXCP-CNT is constant and CPU% is high then a step of job is in the
infinite loop
3. Correct until condition of the program to fix infinite loop

28
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

How to check JCL errors without submitting for execution?


1. SUBMIT it to check JCL errors with TYPRUN=SCAN in JOB card.
2. Use below commands in view or edit mode. No need to SUBMIT the job.
!JCK
JSCAN
JEM
Here errors statistics are shown on the top of the member and errors are shown on error line of the
JCL.

How to Submit a JCL which is logged in the SPOOL?


Use Command SJ infront of the Jobname in the spool. It will show JCL in the spool.
Then submit it for execution.

If a Job is waiting for a file which is used by another user, then how to find the user?
1. Go to JESMSGLG and see the file name that is waiting for
2. Press F1 twice on the file name in 3.4. It gives user id with whom this file is used

Why to capture spool job into a file? How to capture it?


Why to Capture?
Job written in the spool will be deleted after certain period. To put this job for review, capture this
job into a sequential file. Otherwise this job may be deleted before the job is reviewed by peer
reviewer

How to Capture it?


1. XDC Jobname
2. Give file name, disp, Lrecl and press enter

How to see the jobs submitted by all users?


Use below Command level command in ST.
Owner *; Pre *

How to see all jobs submitted by user id?


Use below Command level command in ST.
Owner Userid; Pre *

How to see all jobs submitted by users with job name starts with TAS?
Use below Command level command in ST.
Owner Userid; Pre TAS*

How to release a job submitted with Typrun=hold?


Go to SPOOL and use a line command A in front of the jobname.
Developer may not have this facility but operator can have such a facility.
Jobname status
A job1 hold

29
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

JCL Utilities
IEFBR14
It is a Null program used to create, catalog, delete a file. A DD statement cannot be used without
a EXEC statement, with this reason this Null program is used.
Even though the files can be created with this utility, it is highly recommended to delete an output
file before it is created.

Create a physical sequential file (PS)


//STEP1 EXEC PGM=IEFBR14
//DD1 DD DSN=OZA183.SMF.FILE1,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=100,BLKSIZE=1000)

Create a Partition dataset file (PDS)


//STEP1 EXEC PGM=IEFBR14
//DD1 DD DSN=OZA183.SMF.FILE1,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1,10),RLSE), Directory blocks 10 are used.
// UNIT=SYSDA, Maximum number of members =(10 * 6) -1 =59
// DCB=(RECFM=FB,LRECL=80,BLKSIZE=800,DSORG=PO) Mostly, PDS is
created with Lrecl=80

Delete a file before it is created in the subsequent steps of the same JCL
//STEP1 EXEC PGM=IEFBR14
//DD1 DD DSN=OZA183.SMF.FILE2,
// DISP=,DISP=(MOD,DELETE,DELETE),  If the file is existing then it opens in
// SPACE=(TRK,(1,1),RLSE), append mode it creates. In both the
//* cases it deletes after execution.
//STEP2 EXEC PGM=PGM1
//INFILE DD DSN=OZA183.SMF.FILE1,DISP=SHR
//OUTFILE DD DSN=OZA183.SMF.FILE2,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=50,BLKSIZE=0)

Note: If STEP1 is not coded then OUTFILE has to be deleted manually before you submit JOB.
Otherwise it fails with JCL error 'OZA183.SMF.FILE2 already exists'.
Note: One IEFBR14 step is enough to delete all output files before these are created in the other
steps.

How to delete multiple files in a single IEFBR14 step


//STEP1 EXEC PGM=IEFBR14
//DD1 DD DSN=OZA183.SMF.OUTFILE1,
// DISP=(MOD,DELETE,DELETE),
// SPACE=(TRK,(1,1),RLSE)
//DD2 DD DSN=OZA183.SMF.OUTFILE2,  Note: Same DDname cannot be used
// DISP=(MOD,DELETE,DELETE), more than once
// SPACE=(TRK,(1,1),RLSE)

30
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

How to delete all generations of a GDG base


//STEP1 EXEC PGM=IEFBR14
//DD1 DD DSN=OZA183.SMF.GDGBASE,  It deletes all generations of
// DISP=(MOD,DELETE,DELETE) a GDG but not GDG base

IEBGENER
It is mainly to used to copy a file into another file. i.e. to take a backup.
It is also used to send a mail from Batch JCL

Copy one file into another file


//STEP2 EXEC PGM=IEBGENER
//SYSPRINT DD SYSOUT=*
//SYSUT1 DD DSN=OZA183.SMF.FILE1,DISP=SHR
//SYSUT2 DD DSN=OZA183.SMF.FILE2,
// DISP=(NEW,CATLG,DELETE),
// UNIT=SYSDA,
// SPACE=(CYL,(10,5),RLSE),
// DCB=(RECFM=F,LRECL=100,BLKSIZE=0)  Input and output should have
same length
//SYSIN DD DUMMY  DUMMy is used because a control info is not required for a
simple copy

General syntax of Email with IEBGENER


//STEP1 EXEC PGM=IEBGENER
//SYSPRINT DD SYSOUT=*
//SYSUT2 DD SYSOUT=(B,SMTP)
//SYSUT1 DD *  It is a simple mail transfer protocol
HELO <SYSTEMID>  It is installation defined
MAIL FROM:<mailid1>  From Mail id
RCPT TO:<mailid2>  To Mail id
DATA
FROM: mailid1  From Mail id
TO: mailid2  To Mail id
SUBJECT: TEST MAIL  Subject in the mail

This is my first mail sent from mainframes  Message part of the mail

QUIT  End of message


/*

A Sample situation to generate an Email


//PABCDACT JOB (8012P),'ACCOUNT BALANCE JOB',CLASS=P
//*
//STEP1 EXEC PGM=BALANCE1  It is a file balancing program to check both the files are
//SYSPRINT DD SYSOUT=* balanced or not This program generates return code 4000
//* if the files are not balanced
//FILE1 DD DSN=PABC.PSEQ.ACCT1,DISP=SHR
//FILE2 DD DSN=PABC.PSEQ.ACCT2,DISP=SHR
//REPORT1 DD SYSOUT=(*,$001)  It is a report. Report name is PABCDACT001
//*
//STEP2 EXEC PGM=IEBGENER,COND=(4000,NE,STEP1)  It executes only when step1
//SYSPRINT DD SYSOUT=* returns 4000
//SYSUT2 DD SYSOUT=(B,SMTP)

31
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

//SYSUT1 DD *
HELO ABCCOMPANY
MAIL FROM:<TECH_SUPPORT@ABC.COM>  This step generates mail
RCPT TO:<ACCOUNT_DEPT@ABC.COM> from TECH_SUPPORT@ABC.COM
DATA to ACCOUNT_DEPT@ABC.COM
FROM: TECH_SUPPORT@ABC.COM
TO: ACCOUNT_DEPT@ABC.COM
SUBJECT: ACCOUNTING FILES ARE OUT OF BALANCE

Accounting files are out of balance

Check the balancing report :PABCDACT001

QUIT
/*

IEBCOPY
It is used create a backup of a PDS.
It is used to copy few members of a PDS1 to PDS2.
It is used to compress a PDS to reclaim the unused space from deleted members..

Copy all members of PDS1 to PDS2


//STEP1 EXEC PGM=IEBCOPY
//SYSPRINT DD SYSOUT=*
//DD1 DD DSN=OZA183.SMF.PDS1,DISP=SHR
//DD2 DD DSN=OZA183.SMF.PDS2,DISP=SHR
//SYSIN DD *
COPY INDD=DD1,OUTDD=DD2
/*

Copy few members of PDS1 to PDS2 by using SELECT/EXCLUDE


//STEP1 EXEC PGM=IEBCOPY
//SYSPRINT DD SYSOUT=*
//DD1 DD DSN=OZA183.SMF.PDS1,DISP=SHR
//DD2 DD DSN=OZA183.SMF.PDS2,DISP=SHR
//SYSIN DD *
COPY INDD=DD1,OUTDD=DD2
SELECT MEMBER=(mem1,mem2,mem3)/ EXCLUDE MEMBER=(mem5,mem6)
/* Select list is used to include Exclude list is used to omit

Compress PDS1
//STEP1 EXEC PGM=IEBCOPY
//SYSPRINT DD SYSOUT=*
//DD1 DD DSN=OZA183.SMF.PDS1,DISP=SHR
//DD2 DD DSN=OZA183.SMF.PDS1,DISP=SHR  Input and output are same
//SYSIN DD *
COPY INDD=DD1,OUTDD=DD2
/*

32
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

IEBCOMPR
It is used to compare two sequential files or Members of two PDS.
It halts after 10 differences.
Column comparison is not possible with this.
It does not say about where differences.
ISRSUPC Utility is used in place of IEBCOMPR.

Compare two PS files


//STEP1 EXEC PGM=IEBCOMPR
//SYSPRINT DD SYSOUT=*  Output is written into SYSPRINT
//SYSUT1 DD DSN=OZA183.SMF.FILE1,DISP=SHR  PS File
//SYSUT2 DD DSN=OZA183.SMF.FILE2,DISP=SHR  PS File
//SYSIN DD *
COMPARE TYPORG=PS
/*

Compare two PDS and all its members


//STEP1 EXEC PGM=IEBCOMPR
//SYSPRINT DD SYSOUT=*  Output is written into SYSPRINT
//SYSUT1 DD DSN=OZA183.SMF.PDS1,DISP=SHR  PDS
//SYSUT2 DD DSN=OZA183.SMF.PDS2,DISP=SHR  PDS
//SYSIN DD *
COMPARE TYPORG=PO
/*

ISRSUPC
It is used to compare two sequential files
It is used to compare all members of PDS1 to PDS2
It is used to compare selected members of PDS1 with the same names in PDS2
In all above cases, column comparison is possible

Compare two sequential files


//SUPERC EXEC PGM=ISRSUPC,PARM=(DELTAL,LINECMP,'','')
//NEWDD DD DSN=OZA183.SMF.FILE1,DISP=SHR
//OLDDD DD DSN=OZA183.SMF.FILE2,DISP=SHR
//OUTDD DD SYSOUT=*

Compare two sequential files on specified columns


//SUPERC EXEC PGM=ISRSUPC,PARM=(DELTAL,LINECMP,'','')
//NEWDD DD DSN=OZA183.SMF.FILE1,DISP=SHR
//OLDDD DD DSN=OZA183.SMF.FILE2,DISP=SHR
//OUTDD DD SYSOUT=*
//SYSIN DD *
CMPCOLM 1:3 5:6  Compare first 3 bytes and then 5th and 6th bytes
/*

Compare all members of PDS1 with same names in PDS2


//SUPERC EXEC PGM=ISRSUPC,PARM=(DELTAL,LINECMP,'','')
//NEWDD DD DSN=OZA183.SMF.PDS1,DISP=SHR
//OLDDD DD DSN=OZA183.SMF.PDS2,DISP=SHR
//OUTDD DD SYSOUT=*

33
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Compare selected members of PDS1 with same names in PDS2


//SUPERC EXEC PGM=ISRSUPC,PARM=(DELTAL,LINECMP,'','')
//NEWDD DD DSN=OZA183.SMF.PDS1,DISP=SHR
//OLDDD DD DSN=OZA183.SMF.PDS2,DISP=SHR
//OUTDD DD SYSOUT=*
//SYSIN DD *
SELECT MEM1,MEM2,MEM3
/*

IEBEDIT
It is used to execute required steps, omit steps not required and restart from a job step.
To execute the required steps
//STEP1 EXEC PGM=IEBEDIT
//SYSPRINT DD SYSOUT=*
//SYSUT1 DD DSN=PDS1(JCL1),DISP=SHR  Keep the JCL in a member of a PDS/PS
//SYSUT2 DD SYSOUT=(*,INTRDR)
//SYSIN DD *
EDIT TYPE=INCLUDE,STEPNAME=(STEP10,STEP5,STEP15) Use Include to execute
/* required steps

To omit the steps that are not required


//STEP1 EXEC PGM=IEBEDIT
//SYSPRINT DD SYSOUT=*
//SYSUT1 DD DSN=PDS1(JCL1),DISP=SHR  Keep the JCL in a member of a PDS/PS
//SYSUT2 DD SYSOUT=(*,INTRDR)
//SYSIN DD *
EDIT TYPE=EXCLUDE,STEPNAME=(STEP1,STEP6,STEP12) Use exclude to omit
/* the steps

To restart from the required steps


//STEP1 EXEC PGM=IEBEDIT
//SYSPRINT DD SYSOUT=*
//SYSUT1 DD DSN=PDS1(JCL1),DISP=SHR  Keep the JCL in a member of a PDS/PS
//SYSUT2 DD SYSOUT=(*,INTRDR)
//SYSIN DD *
EDIT TYPE=POSITION,STEPNAME=(STEP6) Use Position to restart job from
/* required steps

IDCAMS
Create GDG base
//STEP1 EXEC PGM=IDCAMS
//SYSIN DD *
DEFINE GDG(NAME(OZA183.SMF.GDGBASE) -
LIMIT(5) -
NOEMPTY -
SCRATCH)
/*

Delete GDG base


//STEP1 EXEC PGM=IDCAMS
//SYSIN DD *
DELETE OZA183.SMF.GDGBASE FORCE -
LIMIT(5) -
NOEMPTY -
SCRATCH)
/*

34
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Define KSDS VSAM file


//STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
DEFINE CLUSTER (NAME(OZA183.SMF.EMPMST) -
CYL(5 5) -
FSPC(10 10) -
KEYS(7 0) -
RECSZ(31 31) -
SHR(2 3) -
RESUE -
INDEXED -
CISZ(2048)) -
DATA (NAME(OZA183.SMF.EMPMST.DATA)) -
INDEX (NAME(OZA183.SMF.EMPMST.INDEX) -
CISZ(512))

/*

Define AIX
//DEFALTIX EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
DEFINE AIX (NAME (OZA183.SMF.EMPAIX) -
RELATE (OZA183.SMF.EMPMST) -
RECORDSIZE (22 22) -
CYL (10 5) -
KEYS (10 17) -
UNIQUE/NONUNIQUE -
UPGRADE)
/*

Default is unique
Record size = 5+alt key size + n (primary key size)

Define PATH
//DEFPATH EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
DEFINE PATH (NAME (OZA183.SMF.EMPMST.PATH) -
PATHENTRY (OZA183.SMF.EMPAIX) -
UPDATE)
/*

Build Alternate Index


//BLDINDEX EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//BASEDD DD DSN=OZA183.SMF.EMPMST,DISP=SHR
//AIXDD DD DSN=OZA183.SMF.EMPAIX,DISP=SHR
//IDCUT1 DD UNIT=SYSDA,SPACE=(CYL,55)
//IDCUT2 DD UNIT=SYSDA,SPACE=(CYL,55)
//SYSIN DD *
BLDINDEX INFILE (BASEDD) -
OUTFILE (AIXDD)
/*

35
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Unload a VSAM file into PS in Method1


//STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//INDD1 DD DSN=OZA183.SMF.EMPMST,DISP=SHR
//OUTDD1 DD DSN=OZA183.SMF.EMPMST.BKUP,DISP=SHR
//*
//SYSIN DD *
REPRO -
INFILE (INDD1) -
OUTFILE (OUTDD1)
/*

Unload a VSAM file into PS in Method2


//STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//*
//SYSIN DD *
REPRO -
INDATASET (OZA183.SMF.EMPMST) -
OUTDATASET (OZA183.SMF.EMPMST.BKUP)
/*

Delete a VSAM file


//STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//*
//SYSIN DD *
DELETE OZA183.SMF.EMPMST PURGE  if dataset not found it returns maxcc=8
SET MAXCC=0  here maxcc sets to zero
/*

Sort

Different uses of SORT


1. To take a back up of a file
2. To skip first few records and copy other few records
3. To Sort a file before generate a report
To sort a trx file that reduces number of hits to master file
4. To sort a file on key in ascending order and eliminate duplicates before load a
VSAM KSDS file
5. To copy records conditionally
6. To split a file into multiple files based on different conditions to input to different
programs or jobs or different interface systems
7. To summarize records before generating summary reports
8. To eliminate duplicates on entire record or single field or multiple fields
9. To restructure input into output without writing a program
10. To join two files to generate matched records or unmatched records
11. To convert VB to FB and FB to VB
12. To include a new field in an existing file with a default value
13. To change the value of a field with another value on a condition

36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Different SORT options


Simple Backup
Data and layout of the file OZA183.SMF.SORTIN are shown below

A003TNP10500000 01 sales-rec.
A002KAP10700000 05 agent-id pic x(4).
A002APP10500000 05 state-code pic x(2).
A001APP10500000 05 product-code pic x(2).
A001TNP20600000 05 sales-amt pic 9(5)v99.
A002TNP10500000
A003KAP20600000
A001KAP10500000
A003APP10700000

//STEP1 EXEC PGM=SORT


//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR
//SORTOUT DD DSN=OZA183.SMF.SORTIN.BKUP1,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=15,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
/*
Skip first 4 recs and copy next 5 recs
//STEP1 EXEC PGM=SORT Output
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* A001TNP20600000
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A002TNP10500000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A003KAP20600000
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, A001KAP10500000
// DISP=(NEW,CATLG,DELETE), A003APP10700000
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=15,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY,
SKIPREC=4,
STOPAFT=5
/*
Copy last 5 recs first and first 4 recs last
//STEP1 EXEC PGM=SORT Intermediate Output
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* A001TNP20600000
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A002TNP10500000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A003KAP20600000
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, A001KAP10500000
// DISP=(NEW,CATLG,DELETE), A003APP10700000
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY,
SKIPREC=4,
STOPAFT=5
/*

37
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

//STEP2 EXEC PGM=SORT Output


//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* A001TNP20600000
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A002TNP10500000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A003KAP20600000
//SORTOUT DD DSN=OZA183.SMF.SOROUT1, A001KAP10500000
// DISP=(MOD,CATLG,CATLG), --> append A003APP10700000
// SPACE=(CYL,(1,1),RLSE), A003TNP10500000
// UNIT=SYSDA, A002KAP10700000
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0) A002APP10500000
//SYSIN DD * A001APP10500000
SORT FIELDS=COPY,
SKIPREC=0,
STOPAFT=4
/*

Sort on agent-id in asc order


//STEP1 EXEC PGM=SORT Output
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* A001APP10500000
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A001TNP20600000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A001KAP10500000
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, A002KAP10700000
// DISP=(NEW,CATLG,DELETE), A002APP10500000
// SPACE=(CYL,(1,1),RLSE), A002TNP10500000
// UNIT=SYSDA, A003TNP10500000
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0) A003KAP20600000
//SYSIN DD * A003APP10700000
SORT FIELDS=(1,4,CH,A)
/*

Sort on agent-id in asc order and then on State-code in asc order


//STEP1 EXEC PGM=SORT Output
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* A001APP10500000
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A001KAP10500000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A001TNP20600000
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, A002APP10500000
// DISP=(NEW,CATLG,DELETE), A002KAP10700000
// SPACE=(CYL,(1,1),RLSE), A002TNP10500000
// UNIT=SYSDA, A003APP10700000
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0) A003KAP20600000
//SYSIN DD * A003TNP10500000
SORT FIELDS=(1,4,CH,A,5,2,CH,A)
/*

Sort on agent-id in asc order and on sales-amount in Desc order


//STEP1 EXEC PGM=SORT Output
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* A001TNP20600000
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A001APP10500000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A001KAP10500000
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, A002KAP10700000
// DISP=(NEW,CATLG,DELETE), A002APP10500000
// SPACE=(CYL,(1,1),RLSE), A002TNP10500000
// UNIT=SYSDA, A003APP10700000
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0) A003KAP20600000
//SYSIN DD * A003TNP10500000
SORT FIELDS=(1,4,CH,A,9,5,ZD,D)
/*

38
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Copy records only when state code is AP


//STEP1 EXEC PGM=SORT Output
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* A002APP10500000
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A001APP10500000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A003APP10700000
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
INCLUDE COND=(5,2,CH,EQ,C'AP')
/*

Copy records only when state code is not AP


//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=* Output
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A003TNP10500000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A002KAP10700000
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, A001TNP20600000
// DISP=(NEW,CATLG,DELETE), A002TNP10500000
// SPACE=(CYL,(1,1),RLSE), A003KAP20600000
// UNIT=SYSDA, A001KAP10500000
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
OMIT COND=(5,2,CH,EQ,C'AP')
/*

Split AP records into 1st file and non AP records into 2nd file
//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=* Sortof1
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A002APP10500000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A001APP10500000
//SORTOF1 DD DSN=OZA183.SMF.SORTOUT1, A003APP10700000
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA, Sortof2
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0)
//SORTOF2 DD DSN=OZA183.SMF.SORTOUT2, A003TNP10500000
// DISP=(NEW,CATLG,DELETE), A002KAP10700000
// SPACE=(CYL,(1,1),RLSE), A001TNP20600000
// UNIT=SYSDA, A002TNP10500000
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0) A003KAP20600000
//SYSIN DD * A001KAP10500000
SORT FIELDS=COPY
OUTFIL FILES=1,INCLUDE=(5,2,CH,EQ,C'AP')
OUTFIL FILES=2,OMIT=(5,2,CH,EQ,C'AP')
/*

39
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Copy few fields of input to output with OUTREC FIELDS Agent-id, product-code sales-
amount only
//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=* Output
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) A003P10500000
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR A002P10700000
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, A002P10500000
// DISP=(NEW,CATLG,DELETE), A001P10500000
// SPACE=(CYL,(1,1),RLSE), A001P20600000
// UNIT=SYSDA, A002P10500000
// DCB=(RECFM=FB,LRECL=11,BLKSIZE=0) A003P20600000
//SYSIN DD * A001P10500000
SORT FIELDS=COPY A003P10700000
OUTREC FIELDS=(1:1,4,5:7,2,7:9,5)
/*

Find total number of records on each product-code


//STEP1 EXEC PGM=SORT Intermediate output
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* P10001
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) P10001
//SORTIN DD DSN=OZA183.SMF.SORTIN,DISP=SHR P10001
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, P10001
// DISP=(NEW,CATLG,DELETE), P20001
// SPACE=(CYL,(1,1),RLSE), P10001
// UNIT=SYSDA, P20001
// DCB=(RECFM=FB,LRECL=06,BLKSIZE=0) P10001
//SYSIN DD * P10001
SORT FIELDS=COPY
OUTREC FIELDS=(1:7,2,3:C'0001')  Include 0001 in every record
/*
//STEP4 EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* Final Output
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD DSN=OZA183.SMF.SORTOUT1,DISP=SHR P10007
//SORTOUT DD DSN=OZA183.SMF.SORTOUT2, P20002
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=06,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=(1,2,CH,A)  Summary records on product
SUM FIELDS=(3,4,ZD)
/*
Eliminate duplicates on entire rec
//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* Output
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD * AAAAA
CCCCC BBBBB
AAAAA CCC
BBBBB CCCCC
AAAAA
CCCCC
BBBBB
CCC

40
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

//SORTOUT DD DSN=OZA183.SMF.SORTOUT1,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=06,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=(1,5,CH,A)
SUM FIELDS=NONE
/*

Eliminate duplicates on first 3 characters and capture eliminated duplicates in another file

//STEP1 EXEC PGM=SORT


//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* SORTOUT SORTXSUM
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD * AAAAA AAAAA
CCCCC BBBBB BBBBB
AAAAA CCC CCCCC
BBBBB CCCCC
AAAAA
CCCCC
BBBBB
CCC
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=06,BLKSIZE=0)
//SORTXSUM DD DSN=OZA183.SMF.SORTOUT2,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=06,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=(1,3,CH,A)
SUM FIELDS=NONE,XSUM
/*

Summarize records on number field (4th to 7th position), if the first 3 chars are same
//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* SORTOUT
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD * AAA30000
CCC10000 BBB30000
AAA20000 CCC30000
BBB10000 DDD10000
AAA10000
CCC20000
BBB20000
DDD10000
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=06,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=(1,3,CH,A)
SUM FIELDS=(4,5,ZD)
/*

41
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Change the values at 4th and 5th col from '11' to '33'
//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=* Output
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) AAA33
//SORTIN DD * BBB22
AAA11 DDD33
BBB22 CCC22
DDD11
CCC22
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=05,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
OUTREC FIELDS=(1:1,3,4:4,2,CHANGE=(2,C'11',C'33'),NOMATCH=(4,2))
/*

Reverse records based on its position


Input Output
AAA CCC
BBB DDD
DDD BBB
CCC AAA

//STEP1 EXEC PGM=SORT Intermediate output


//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=* AAA0001
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) BBB0002
//SORTIN DD * DDD0003
AAA CCC0004
BBB
DDD
CCC
//SORTOUT DD DSN=&&TEMP1,  It shows how to create temporary dataset and
// DISP=(NEW,PASS), how to pass to the next steps of jcl
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=17,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
OUTREC FIELDS=(1:1,3,4:SEQNUM,4,ZD,START=1,INCR=1)Include a record number
/*
//STEP2 EXEC PGM=SORT
//SYSOUT DD SYSOUT=* Final Output
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) CCC
//SORTIN DD DSN=&&TEMP1,DISP=(OLD,DELETE) DDD
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, BBB
// DISP=(NEW,CATLG,DELETE), AAA
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=13,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=(4,4,ZD,D)  Sort rec num in reverse order
OUTREC FIELDS=(1:1,3)  do not include record number
/*

42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Merge records of two files alternative


File1 File2 Output
AAA XXX AAA
BBB YYY XXX
CCC ZZZ BBB
YYY
CCC
ZZZ

//STEP1 EXEC PGM=SORT


//SYSOUT DD SYSOUT=* Intermediate output
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) AAA0001
//SORTIN DD * BBB0003
AAA CCC0005
BBB
CCC
/*
//SORTOUT DD DSN=&&TEMP1,  Shows about how to create temporary dataset
// DISP=(NEW,PASS),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=7,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
OUTREC FIELDS=(1:1,3,4:SEQNUM,4,ZD,START=1,INCR=2)
/*
//STEP2 EXEC PGM=SORT
//SYSOUT DD SYSOUT=* Intermediate Output
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE) XXX0002
//SORTIN DD * YYY0004
XXX ZZZ0006
YYY
ZZZ
/*
//SORTOUT DD DSN=&&TEMP2,
// DISP=(NEW,PASS),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=7,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
OUTREC FIELDS=(1:1,3,4:SEQNUM,4,ZD,START=2,INCR=2)
/*
//STEP3 EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD DSN=&&TEMP1,DISP=(OLD,DELETE)  Shows about how to concatenate
// DD DSN=&&TEMP2,DISP=(OLD,DELETE) two files
//SORTOUT DD DSN=OZA183.SMF.SORTOUT1, Final output
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE), AAA
// UNIT=SYSDA, XXX
// DCB=(RECFM=FB,LRECL=3,BLKSIZE=0) BBB
//SYSIN DD * YYY
SORT FIELDS=(4,4,ZD,A) CCC
OUTREC FIELDS=(1:1,3) ZZZ
/*

43
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Match two files to generate mached recs and unmatched from 1st file

Product file Forex file Matched recs Unmatched recs from 1st file
P1IND01000 AUD000900 P1IND01000000020 P7EUR05000
P2JPY02000 CHD000100 P2JPY02000000300 P8RUR05000
P3GBP02000 GBP001500 P3GBP02000001500 P9EUR05000
P4JPY05000 IND000020 P4JPY05000000300
P5IND06000 JPY000300 P5IND06000000020
P6USD05000 USD001000 P6USD05000001000
P7EUR05000
P8RUR05000
P9EUR05000

Layout of product File Layout of Forex File


01 Product-Rec. 01 Forec-Rec.
05 product-code pic x(2). 05 curr-code pic x(3).
05 curr-code pic x(3). 05 conv-rate-in-usd pic 9(3)v9(3).
05 product-price pic 9(5).

Layout of matched file (Layout of unmatched file is same as Product file)


01 Product-Rec.
05 product-code pic x(2).
05 curr-code pic x(3).
05 product-price pic 9(5).
05 conv-rate-in-usd pic 9(3)v9(3).

//STEP1 EXEC PGM=SORT


//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTJNF1 DD DSN=OZA183.SMF.PRODUCT,DISP=SHR
//SORTJNF2 DD DSN=OZA183.SMF.FOREX,DISP=SHR
//SORTOUT DD DSN=OZA183.SMF.PRODUCT.VALID,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=16,BLKSIZE=0)
//SYSIN DD *
JOINKEYS FILES=F1,FIELDS=(3,3,A)
JOINKEYS FILES=F2,FIELDS=(1,3,A)
JOIN PAIRED
REFORMAT FIELDS=(F1:1,10,F2:4,6)  Matched records
SORT FIELDS=COPY
/*
//STEP2 EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTJNF1 DD DSN=OZA183.SMF.PRODUCT,DISP=SHR
//SORTJNF2 DD DSN=OZA183.SMF.FOREX,DISP=SHR
//SORTOUT DD DSN=OZA183.SMF.PRODUCT.ERROR,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=10,BLKSIZE=0)

44
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

//SYSIN DD *
JOINKEYS FILES=F1,FIELDS=(3,3,A)
JOINKEYS FILES=F2,FIELDS=(1,3,A)
JOIN UNPAIRED,F1,ONLY
REFORMAT FIELDS=(F1:1,10)  UnMatched records from file1
SORT FIELDS=COPY
/*

Sort a variable length file on its first 4 bytes


//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD DSN=OZA183.SMF.FILE1,DISP=SHR
//SORTOUT DD DSN=OZA183.SMF.FILE2,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=06,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=(5,4,CH,A)  First 4 bytes of Variable length files
/* So take the offset from 5 instead of 1.

Convert a FB file into VB file


//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD DSN=OZA183.SMF.FBIN,DISP=SHR  FB with lrecl=20
//VBOUT DD DSN=OZA183.SMF.VBOUT,  VB with lrecl=24
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=VB,LRECL=24,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
OUTFIL FNAMES=VBOUT,FTOV,VLTRIM=C' '  Remove trailing spaces and create VB
/*

FBIN Length of record VBOUT Length of record

AAAAAAAA 20 AAAAAAAA 4+8 = 12


BBBBBBBBBBB 20 BBBBBBBBBBB 4+11 = 15
CC 20 CC 4+2 = 06
---- ----
Total bytes 60 Total bytes 33
---- ----

45
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL

Convert a VB file into FB file


//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD DSN=OZA183.SMF.VBOUT,DISP=SHR  Output from above step
//FBOUT DD DSN=OZA183.SMF.FBOUT1,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=20,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
OUTFIL FNAMES=FBOUT,VTOF,OUTREC=(1:5,20)  It pads smaller records with trialing
/* spaces
VBOUT Length of record FBOUT Length of record

AAAAAAAA 4+8 = 12 AAAAAAAA 20


BBBBBBBBBBB 4+11 = 15 BBBBBBBBBBB 20
CC 4+2 = 06 CC 20
---- ----
Total bytes 33 Total bytes 60
---- ----

Convert a VB file into FB file and pad trailing chars in smaller records with '*'
//STEP1 EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,(1,1),RLSE)
//SORTIN DD DSN=OZA183.SMF.VBOUT,DISP=SHR
//FBOUT DD DSN=OZA183.SMF.FBOUT2,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(1,1),RLSE),
// UNIT=SYSDA,
// DCB=(RECFM=FB,LRECL=20,BLKSIZE=0)
//SYSIN DD *
SORT FIELDS=COPY
OUTFIL FNAMES=FBOUT,VTOF,OUTREC=(1:5,20),VLFILL=C'*'  It pads smaller
/* records with trialing '*'

VBOUT Length of record FBOUT Length of record

AAAAAAAA 4+8 = 12 AAAAAAAA************ 20


BBBBBBBBBBB 4+11 = 15 BBBBBBBBBBB********* 20
CC 4+2 = 06 CC****************** 20
---- ----
Total bytes 33 Total bytes 60
---- ----

46
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

VSAM

1
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

2
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

VSAM

VSAM - Virtual Storage Access Method is a high performance access method used in MVS and
DOS operating system. It is superior to other access methods.

These are used to store master data. And it is updated by the transactions.
It is used as a database in 70% mainframe systems.
It is extensively used in online applications.
These are used as a direct access files in COBOL.

Advantages of VSAM
1. One method that support all types of data retrieval. Sequential/Random/Dynamic
2. Can be used as database that stores the master information in many systems
3. Inserting a record is easy because of embedded space is available with free space option
4. Records can be deleted physically and that space can be used for inserting records without
reorganizing records.
5. AMS (Access method service) takes care of reading with index and writing in the order and
reorganizing records on splits.
6. Supports fixed and Variable Records
7. One utility, IDCAMS, to manage everything (IEBGENER for sequential files, IEBCOPY for
PDS, IEBISAM for ISAM files)
8. Supports alternate index

Disadvantages of VSAM
1. Require lot of DASD space
2. For KSDS, primary key cannot be changed
3. Performance is lower than QSAM files because of complexity of Index
4 .Only resides on DISK and cannot be created on Tape files

Different types of VSAM files


There are 4 types of VSAM files.

1. ESDS - Entry Sequence Dataset


2. KSDS - Key Sequence Dataset
3. RRDS - Relative Record Dataset
4. LDS - Linear Dataset

Usage of these files in real applications

KSDS file are used extensively in most of the applications.


. These are mostly used files used in both batch and online applications
. Master data is recorded into these files
. These are used to browse or edit data in online applications
. Transactions are entered online or collected through another sub system are processed in batch
system.
. These transactions insert, update, and delete records into KSDS master files.

3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

ESDS file are rarely used in online applications to write transactions sequentially.
. In batch applications, QSAM (flat files) are used to sequentially read or write the data. So
ESDS files are not used in batch applications.
. In online applications, flat files cannot be used. So ESDS files are rarely used to sequentially
write transactions. These online transactions are unloaded to flat files and processed in batch
applications.

RRDS
. These files are not used in both batch and online applications.

LDS
. These are used to store physical data of DB2 tables.
. These are not used in application programs.
Conclusion:
There is no difference in using ESDS files and QSAM files. One should know about using KSDS
files only in the batch applications. Only KSDS files are explained throughout this material.

How to use VSAM file in COBOL


There is no extra preparation required to use VSAM files in COBOL because these can be used as
a Direct access files.

How to use KSDS in the Select statement


Syntax of KSDS file in COBOL.
SELECT FILE-NAME ASSIGN TO DDNAME
ORGANIZATION IS INDEXED
ACCESS MODE IS SEQUENTIAL/RANDOM/DYNAMIC
RECORD KEY IS KEY-FIELD
{ALTERNATE RECORD KEY IS ALTERNATE-KEY-FIELD1}
{ALTERNATE RECORD KEY IS ALTERNATE-KEY-FIELD2}...
FILE STATUS IS WS-STATUS.

Organization says about type of the VSAM file.


Indexed - KSDS
Relative - RRDS
Sequential - ESDS

Different access modes available for KSDS files


All these access modes are shown with an example of employee file and the layout is given
below.

FD EMP-MASTER.
01 E-REC.
05 EMP-KEY.
10 EMP-COUNTRY-CODE PIC X(03).
10 EMP-ID PIC X(04).
05 EMP-NAME PIC X(20).
05 EMP-DOJ PIC X(08).
05 EMP-STATUS PIC X(01).
05 EMP-BASIC-SAL PIC S9(07)V99 COMP-3.
05 EMP-HRA PIC S9(03)V99 COMP-3.
05 EMP-ALLOW PIC S9(03)V99 COMP-3.

4
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Sequential Access mode


This access mode is used when partial key or full key of the master file is not known. It is used to
read the file from top to bottom.

Example: Situation to use EMP-MST with sequential access mode

To get the terminated employee details into output file.

In environment division
SELECT EMP-MASTER ASSIGN TO EMPMST
ORGANIZATION IS INDEXED
ACCESS MODE IS SEQUENTIAL --> IMPORTANT
RECORD KEY IS EMP-KEY
FILE STATUS IS WS-EMP-STATUS.

FD EMP-MASTER.
01 EMP-REC.
05 EMP-KEY.
10 EMP-COUNTRY-CODE PIC X(03).
10 EMP-ID PIC X(04).
.
.

PERFORM 200000-PROCESS THRU 200000-EXIT


UNTIL WS-EOF = 'Y'.
200000-PROCESS.

READ EMP-MASTER AT END MOVE 'Y' TO WS-EOF


GO TO 200000-EXIT.

IF EMP-STATUS = 'T'
MOVE IN-REC TO OUT-REC
WRITE OUT-REC.
200000-EXIT.
EXIT.

Random Access mode


This access mode is used to read master file random when a full key of the master file is known.
To read the master file random, one should get the key from another sequential file or another
master file.

Example: Situation to use EMP-MST with random access mode

Get the details of employees of the employee numbers given in another sequential file.
SELECT IN-FILE ASSIGN TO INFILE.

SELECT EMP-MASTER ASSIGN TO EMPMST


ORGANIZATION IS INDEXED
ACCESS MODE IS RANDOM --> important
RECORD KEY IS EMP-KEY
FILE STATUS IS WS-EMP-STATUS.
.
.
.

5
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

FD IN-FILE.
01 IN-REC.
05 IN-KEY PIC X(07).
.
.
FD EMP-MASTER.
01 EMP-REC.
05 EMP-KEY.
10 EMP-COUNTRY-CODE PIC X(03).
10 EMP-ID PIC X(04).
.
.

PERFORM 200000-PROCESS THRU 200000-EXIT


UNTIL WS-EOF = 'Y'.
200000-PROCESS.

READ IN-FILE AT END MOVE 'Y' TO WS-EOF


GO TO 200000-EXIT.
MOVE IN-KEY TO EMP-KEY IN EMP-MASTER --> Populate full key
READ EMP-MASTER
IF WS-EMP-STATUS = '23' --> Check status
DISPLAY 'EMP-KEY NOT FOUND:' EMP-KEY
GO TO 200000-EXIT
END-IF
.
.
200000-EXIT.
EXIT.

Dynamic access mode


This access mode is used to position file at a given point and read sequential until certain
condition is matched or end of file. This is called skip sequential method. i.e. skip initial records
and read sequentially.
It is achieved with two I/O statements 'START' and 'READ NEXT'.

General Syntax for START

START FILENAME KEY is EQUAL TO/NOT LESS THAN/GREATER THAN key-name


[INVALID KEY imperative statement1]
END-START.

START positions file for a condition on partial key or full key.


Places a pointer at the required record but the record is not retrieved.
If the required partial key or full key is not found, it will execute imperative statement
given in the INVALID KEY phrase.

General Syntax for READ NEXT


READ FILE-NAME NEXT RECORD

The First record that is positioned is retrieved into program with first read next statement. Keep
this Read next statement in a loop until a condition is matched or end of file is reached.

6
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Example: Situation to use EMP-MST with dynamic access mode. Generate bonus for the country
code given through PARM.
SELECT EMP-MASTER ASSIGN TO EMPMST
ORGANIZATION IS INDEXED
ACCESS MODE IS DYNAMIC  Important
RECORD KEY IS EMP-KEY
FILE STATUS IS WS-EMP-STATUS.
.
.
FD EMP-MASTER.
01 EMP-REC.
05 EMP-KEY.
10 EMP-COUNTRY-CODE PIC X(03).
10 EMP-ID PIC X(04).
.
.
LINKAGE SECTION.
01 LS-VARIABLES.
05 LS-PARM-LEN PIC S9(4) COMP.
05 LS-COUNTRY-CODE PIC X(3).
05 LS-BONUS-PERCENT PIC 9(3)V99.
.
.
MOVE LS-COUNTRY-CODE TO EMP-COUNTRY-CODE  Populate
partial/full key
START EMP-MASTER KEY IS EQUAL TO EMP-COUNTRY-CODE  Cursor
positioned here
INVALID KEY DISPLAY 'COUNTRY KEY NOT FOUND'  invalid key
executes when country code
not available in EMP-MST
MOVE 'Y' TO WS-EOF.
PERFORM 200000-PROCESS THRU 200000-EXIT UNTIL WS-EOF = 'Y'.
.
200000-PROCESS.

READ EMP-MST NEXT RECORD AT END MOVE 'Y' TO WS-EOF  Stop process
when end of file is reached.
GO TO 200000-EXIT.
IF EMP-COUNTRY-CODE > LS-COUNTRY-CODE  Stop process when country
MOVE 'Y' TO WS-EOF code is changed.
GO TO 200000-EXIT
END-IF
.
.
.
200000-EXIT.
EXIT.

Note: Keep this read next statement in the loop until country code changes or end of file is
reached. Imperative statements given in INVALID KEY clause executes when the given country
code is not available in the EMP-MASTER.

7
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Different Open modes


In VSAM use input,output,and I-O modes
INPUT : File can be used only for READ.
OUTPUT : File can be used only for WRITE.
I-O : File can be used for READ, WRITE, REWRITE and DELETE.

Note: EXTEND mode is not allowed in KSDS files because the records are inserted but not
appended. I-O is used only on VSAM. It can be used on Flat files but not recommended.

Different disp parameters in JCL


SHR : It is used for read access
OLD : It is used for write/rewrite/delete access
Note: Disp parameter NEW cannot be used for VSAM files because these cannot be created with
DD statement Disp parameter MOD cannot be used on KSDS files because data is inserted in
appropriate record location but it is not appended in the end.

Different I/O statements

READ Statement
READ statement is used to read the record from the file.
Syntax: READ FILENAME [NEXT] RECORD[KEY IS FILE-KEY1]
[AT END/INVALID KEY imperative statement1]
[NOT AT END/NOT INVALID KEY imperative statement2]
END-READ

Specify NEXT on the READ statement to retrieve records sequentially on DYNAMIC access
mode. KEY IS clause is used while accessing a record randomly using primary/alternate record
key. AT END and NOT AT END are used during sequential READ or READ NEXT of the file.
INVALID KEY and NOT INVALID KEY are used during START or Random READ.

Exception conditions
1. Record not found on random read
2. End of file on Read next
3. File not opened in INPUT or I-O mode

WRITE Statement
Write statement is used to write a new record in the file. It is inserted in the appropriate place.
Syntax: WRITE FILE-RECORD [INVALID KEY imperative statement1]
END-WRITE

Exception conditions
1. No space to write new record.
2. Trying to insert a duplicate key
3. File not opened in OUTPUT or I-O mode

REWRITE Statement
REWRITE is used to update a read record. To update a record in a file, the file should be opened
in I-O mode.
Syntax: REWRITE FILE-RECORD [INVALID KEY imperative statement1]
END-REWRITE

8
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Except key field, any field can be updated.


Exception conditions
1. Trying to update key
2. Prior read statement is not issued
3. File not opened in I-O mode

START Statement
START is used with dynamic access mode of indexed files. It establishes the current location in
the cluster for READ NEXT statement. START itself does not retrieve any record.
Syntax: START FILENAME KEY is EQUAL TO/NOT LESS THAN/GREATER THAN key-name
[INVALID KEY imperative statement1]
END-START.
Exception conditions
1. Prior read statement is not issued
2. File not opened in I-O mod

DELETE Statement
DELETE is used to delete the most recently read record in the file. To delete a record, the file
should be opened in I-O mode.
Syntax: DELETE FILENAME RECORD
[INVALID KEY imperative statement1]
END-DELETE.
Exception conditions
1. File not opened in I-O mode.

How to update record in dynamic access mode


Use one more start and read next statements after update statement. Because the cursor pointer is
lost when a update statement is used.

PERFORM START-PARA THRU START-EXIT.


PERFORM PROCESS-PARA THRU PROCESS-EXIT UNTIL WS-EOF = 'Y'

START-PARA.
MOVE IN-KEY TO FILE-KEY
START FILE-NAME KEY IS EQUAL TO FILE-KEY.
START-EXIT.
EXIT.

PROCESS-PARA.
READ FILE-NAME NEXT RECORD AT END MOVE 'Y' TO WS-EOF
GO TO PROCESS-EXIT.
CHANGE THE VALUE OF ANY FIELD
REWRITE FILE-REC
START FILE-NAME KEY IS EQUAL TO FILE-KEY.  EXTRA START STMT WITH FULL KEY
READ FILE-NAME NEXT RECORD.  EXTRA READ NEXT STATEMENT
PROCESS-EXIT.
EXIT.

What is importance of Low values and High values?


Low-values is X'00'
High-values is X'FF'
These are the least record and highest records in the file. It is always better to keep these records
in the file.

9
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

How to update key field of VSAM file?


It is not possible to rewrite a record by changing the key value. But there is alternate approach for
this. Follow the below steps to update key.
READ FILE-NAME
MOVE FILE-REC TO WS-REC  SAVE RECORD INTO WORKING STORAGE VARIABLES
DELETE FILE-NAME  DELETE ORIGINAL RECORD
MOVE NEW-KEY TO KEY-FIELD IN WS-REC  CHANGE KEY VALUE IN THE SAVED RECORD
MOVE WS-REC TO FILE-REC  MOVE BACK TO FILE RECORD
WRITE FILE-REC.  INSERT RECORD WITH NEW KEY

Extra care required for update of VSAM


Step1: Execute the Update job. Take a back up of master file that is being updated in update job.
This should be done before the update step.
Step2: When the update step abends execute a special job called restores job. This restores job
contains the below steps.
Step A. Delete and define the updated VSAM file with IDCAMS
Step B. Load the defined VSAM file from the backup file created in STEP1. With this the
VSAM file is brought to its original state.
Step3: Delete the abend causing record from the input file.
Step4: Restart update job from the abended step.

Different file status codes


00 -- Successful read. For all access modes.
02 -- Successful read but warning. It is received when a random read is done on alternate key
which is having duplicates.
10 -- At end. This is received both in sequential and dynamic reads.
20 -- Invalid Key on start
21 -- Sequence error. Trying to update a key (primary key) field after read statement.
22 -- Duplicate key. Trying to insert a duplicate key.
23 -- Record not found. It is received in random access mode.
24 -- Out of space
35 -- DD statement missing or DDNAME Misspelled
39 -- file attribute mismatch
41 -- Trying to open a opened file
42 -- Trying to close a file which is not opened
43 -- Using REWRITE but no prior READ
44 -- writing a varaible length records beyond maximum and minimum length
46 -- Reading beyond end of file (After file status 10)
47 -- Using READ but open mode is not compatible. Other than INPUT/I-O
48 -- Using WRITE but open mode is not compatible. Other than OUTPUT/EXTEND
49 -- Using REWRITE but open mode is not compatible. Other than I-O
90 -- Unknown operation
91 -- VSAM password failure
92 -- VSAM Logic error
Trying to write input file. Trying to read output file.
Trying to update with I-O mode. Trying to rewrite but no prior read.
93 -- Resource not available
94 -- Sequential read after end of file . No prior start for read next
95 -- Open file input or I-O that never contain data
96 -- Missing DD name in JCL

10
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Alternate Index
Importance of Alternate key
Alternate key is used to retrieve the record faster from a KSDS file other than primary key.
Alternate key can be unique or non-unique. Alternate key can be updated whereas primary key
cannot be updated.

Few examples of real applications

1. SSN-NUMBER
2. TAX-NUMBER
3. PAN-NUMBER
4. PASSPORT-NUMBER

Few situations where AIX can be used


1. When a multiple policies are taken by single SSN number, and it is needed to search the
policies taken by SSN number.
2. When multiple bank accounts are taken by single PAN or TAX number and to find number of
accounts for a PAN or TAX number.
3. When Employee file needs to be searched based on SSN number or Tax numbers. This is more
useful when cross systems are communicating.

4. In Policy and its writing agent file the key is Policy + Writing agent. If the file needs to be
searched on policy number then it can be done with Primary key. If the file needs to searched
on writing agent to see how many policies a writing agent has written, then Alternate key has
to be generated on Writing agent.

Procedure to use Alternate keys


1. Identify Alternate key in the base cluster
2. Define AIX
3. Define path
4. Build index  In this process Alternate keys and its primary keys are loaded in AIX.
5. Changes in the COBOL program
a. Use 'alternate record key is' clause in Select statement
b. Move value to alternate key
c. Use key is clause in read statement
6. Changes in the JCL
Give path name in the JCL along with base DDNAME by suffixing 1.If Base DDNAME is
EMPMST then Path DDNAME name should be EMPMST1. If there are more than one
alternate indexes built and are used in the program then use EMPMST1, EMPMST2,
EMPMST3.. for the corresponding paths.

Accessing file on Alternate Keys


The Select statement.
SELECT file-name ASSIGN TO ddname-in-jcl
ORGANIZATION IS INDEXED
ACCESS MODE IS RANDOM / DYNAMIC / SEQUENTIAL
RECORD KEY IS key-filed
ALTERNATE RECORD KEY IS alternate-key-field
[WITH DUPLICATES]
FILE STATUS IS ws-file-status.

11
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

If the file is having more than one alternate key and it is used in the program then code more than
one ‘ALTERNATE RECORD KEY IS’ phrase. If the alternate key is created as non-unique then
use it in the program with ‘WITH DUPLICATES’ phrase.
Read unique alternate key on random access and non-unique alternate key on dynamic access.
Random read on non-unique alternate key returns file status ‘02’ if there are duplicate records.

Random processing on alternate key


The format of the READ statement for random processing of a KSDS with an alternate index is

READ file-name
KEY IS Alternate-key-field

Through Rewrite statement, changing primary key is not allowed but changing alternate key is
allowed.

Dynamic processing on alternate key


Move in-field to alternate-key-field/partial-alternate-key-field
START FILE-NAME KEY IS EQUAL TO alternate-key-field/
partial-altrenate-key-field
INVALID KEY IMPERETIVE STATEMENT.
READ FILE-NAME NEXT RECORD

Example 1: Unique AIX

One person (SSN-NUM) can work with one EMP-NUM. If a record is to be read on SSN-NUM
then create a unique AIX on SSN-NUM. In the employee file, Emp-Number is a Primary key and
SSN-NUM (Social Security Number) is an alternate key. In the base cluster, records are sorted on
primary key and in AIX, records are sorted on alternate key.

Record Size of AIX = 5 + Alt key size + primary key size


13 = 5 + 4 + 4

Base Cluster AIX


Primary key Alternate Alternate key Primary
key key
5
EMP-NUM NAME SSN NUM Bytes SSN NUM EMP-NUM

E001 MADHU S011 S001 E007


E002 HITHA S012 S002 E006
E004 RAVI S005 S003 E005
E005 JAITRI S003 S005 E004
E006 JOHN S002 S007 E008
E007 WILLIAMS S001 S010 E012
E008 PEARS S007 S011 E001
E011 DAVID S013 S012 E002
E012 VILAS S010 S013 E011
E014 SUSZAN S017 S017 E014

12
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Example 2: Non Unique AIX

A person (SSN-NUM) can take more than one policy. If it is needed to find the policies taken by
a person (SSN-NUM) then it is required to create alternate key on SSN number.

In this case AIX should be created with option NONUNIQUEKEY.


In the program select clause should have “Alternate record key is SSN-NUM with duplicates”.
And also access mode should have Dynamic.

Policy file has primary key as Policy number and alternate key as SSN number with duplicates.
AIX record size is 5 + 4 + 10 (4) = 49

Base Cluster AIX

Pri key St Name Alt key 5 Alt Pr Pr Pr Pr Pr Pr Pr Pr Pr Pr


policy ssn B key key1 key2 key3 key4 key key key ke key key
yt ssn 5 6 7 y8 9 10
es
P001 A JOHNSON S001 S001 P001 P005 P006
P002 A WILSHARE S002 S002 P002
P003 T SAMUEL S003 S003 P003 P007 P011
P004 A MELENIE S004 S004 P004
P005 A JOHNSON S001 S007 P008
P006 A JOHNSON S001 S008 P009
P007 A SAMUEL S003 S009 P010
P008 A MARK W S007
P009 A DONNA S008
P010 A SEETHAL S009
P011 A SAMUEL S003

13
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Internal representation of KSDS files


CLUSTER
All the VSAM data set types are defined as clusters.
A cluster can be thought of as a logical data set consisting of two separate physical datasets.
1. Data component -> contains actual data
2. Index component ->contains actual index

Data component

Control Interval (CI)


VSAM stores its data records in units called control interval. A CI is VSAM’s equivalent of a
block.
CI is the unit of data that is actually transmitted when records are read / written.
The size of a control interval is defined in the DEFINE CLUSTER command.

There are four distinct areas in a control interval

1. Logical Record Area (LRA)


It contains Data Records.
2. Control Interval Free Space (FSPC)
This is the space that does not contain records and goes on reducing as records are inserted into
a CI.
3. Unused Space (US)
•There is some space in a CI that is never used
•The size of a CI, may not be an integral multiple of data records size.
•This leaves a gap that can never be used.
4. The Control Fields comprise of
One Control Interval Definition Field (CIDF) per CI, and one or more Record Definition Fields
(RDF) per logical record.
The RDF’s are inserted from right to left as records get inserted from left to right.
. CIDF is a 4-byte field. It contains information about the length of data in the CI and the
amount and location of free space.
. RDF is a 3-byte field. It describes the length of records and how many adjacent records are of
the same length
Data records that occupy more than one Control Interval are called Spanned Records.

R R R C
LR1 LR2 … LRn FREE UNUSED D …….. D D I
SPACE SPACE Fn F2 F1 D
F

Control Information Fields


LR = Logical record
FSPC = Free space
RDF = Record definition field
CIDF = Control interval definition field

14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

CIDF and RDF examples

A B C Free RDF RDF CIDF


150 150 150 Space 3 150 150

A B C RDF RDF RDF CIDF


80 100 200 200 100 80 0

A B C D RDF RDF RDF CIDF


80 80 80 150 150 3 80
0

Read RDF backwards, from right to left

Control Areas (CA)


Control Area is a fixed length unit of contiguous DASD storage. It consists of many Control
Intervals. It is VSAM’s internal unit for allocating space within a cluster.
The Control Area size can vary from one track to one cylinder depending on unit of allocation.
There is no way a Control Area size can be defined but VSAM computes it internally.

Determining no. of C.I’s per C.A point of C.A size = 1 cylinder


Table showing no of C.I’s per cylinder

C.I size No of C.I's per cylinder


512 690
1024 465
2048 270
4096 150

Control Interval Splits


When there is no room to insert a record C.I. Splits at the point of insertion. The record is added
at this point of split. The remaining records after the point of insertion are written into another
free C.I.There are always some percentages of free C.I.’s kept in a C.A.
Control Interval Splits are possible only in case of KSDS.

Control Area Splits


When there is no room to insert further records and no free C.I.’s left, a Control Area Splits.
Control Area Split is performed in the same way as C.I. Split.
VSAM continues C.A. Splits until space allocation limits are exceeded.

15
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Before control interval split


Sequence
Set I 0 M 100
Record
C

0
Data
Record A Record B Record F Record G U CF
Component S
100
Record J Record K FSPC U CF
S
200
FSPC U CF
S

After control interval split


Sequence
Set E 0 I 200 M 100

0
Data Record A Record B Record C FSPC U CF
Component S
100
Record J Record K FSPC U CF
S
200
Record F Record G FSPC U CF
S

Index Component

VSAM creates an index component to maintain index for a KSDS. Index component has a
Hierarchical Structure consisting of
• One or more of index sets
• Several sequence sets

Sequence Set
It is the lowest level of index.
Every index entry of a sequence set consists of
• A primary record key of a data record contained in the Control Interval which it points to
• A pointer to the Control Interval containing this data record
• The pointer is actually the Relative Byte Address (RBA) of the C.I. from the beginning of the
dataset.
• The Control Interval may not be in sequential order
• However, the sequence set is always sorted in sequential order of record keys.

16
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Index Set
This is the second level of index.
Every entry of an index set consists of a Primary key.
A pointer to sequence set that contains the primary key.
Index sets can have one or more levels.
The highest level has only one record

Index & Sequence Set

Index
Key Ptr Key Ptr ... Set

Index
Component Sequence Set 1 Sequence Set 2 Sequence
...
Key Ptr Key Ptr Key Ptr Key Ptr Key Ptr Key Ptr Set

...
Data CI 1 CI 2 CI 3 CI 4 CI 5 CI 6 Control
Component Areas
Control Area 1 Control Area 2

Index Set Find rec 33

29 63 88 99
Sequence Set

17 29 42 63 76 88

Data CI

8 13 16 17 31 33 35 42

17
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

IDCAMS
AMS is used to perform various functions on VSAM datasets and catalogs.
AMS has got a utility program called IDCAMS (integrated data cluster access method
service).The functions of AMS are performed using the different functional commands of
IDCAMS.

Important functional commands of IDCAMS

On Base cluster
1. DEFINE -> To create objects-KSDS/ESDS/RRDS/GDG/VSAM SPACE etc
2. ALTER -> To alter the parameters of the object already exists.
3. PRINT -> To print and view the selected records of dataset
4. DELETE -> Delete the objects.
5. LISTCAT-> View the complete information about any object.
6. REPRO -> Copy/restore/merge utility for vsam and non-vsam files.
7. VERIFY -> To verify the physical existence of a VSAM file.

On AIX
1. DEFINE -> To define AIX
2. PATH -> To define Path
3. BUILDINDEX -> To build index from the base cluster

IDCAMS Return Codes

0 Command executed with no errors


4 Warning - execution may go successful
8 Serious error - execution may fail.
12 Serious error - execution impossible.
16 Fatal error - job step terminates.

Using IDCAMS to Define KSDS cluster:(KEY sequenced dataset)


//DEFCLUST JOB ‘8012T’,’MADHU’, MSGCLASS=X,CLASS=A
//JS10 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//*
//SYSIN DD *
DEFINE CLUSTER (NAME(FILENAME) -
CYL(5 5) -
FSPC(10 10) -
KEYS(7 0) -
RECSZ(31 31) -
SHR(2 3) -
CISZ(2048))
DATA (NAME(FILENAME.DATA)) -
INDEX (NAME(FILENAME.INDEX) -
CISZ(512))
/*

18
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

NAME
To give the name of the cluster
KEYS
Keys (length offset) e.g. key (8 1) starting from 2nd byte to 9th byte
Keys parameter defines the length and offset of the primary key in a KSDS record.

RECORDSIZE
RECORDSIZE (AVG, MAX)
The record size parameters specify VSAM what records to expect. The AVG and MAX are the
average and maximum values for variable length records. If records are fixed length , AVG and
MAX can be same. Record size can be assigned at the cluster or data level.

FREESPACE
This parameter allocates some percentage of both the CI and CA for planned free space,
It can be used for adding new records or expanding existing variable records.
This parameter is coded as follows

FREESPACE (CI% CA%)


FREESPACE (0 0) ->Default
Recommended CI and CA % are 10 10

SPACE PARAMETER
A VSAM dataset can have 123 extents (Primary+122*secondary) in a volume. primary space is
allocated initially when the dataset is created and based on request secondary space will be
allocated.
Syntax:
UNIT (primary secondary)

EX:
Cylinders (primary secondary)
Tracks (primary secondary)

SHARE OPTIONS (cr-value cs-value)


By default SHR (2 3)
2 says that in cross region one job can update it and multiple jobs can read this.
3 says that in cross system jobs can also update this file.

CISZ
It is a I-O buffer area which is compatible to BLKSIZE in sequential file.
When a record is read then it will get the entire CI and keeps into main memory and from there it
will get the required record into program.

If the file is used most of the times in sequential and dynamic modes then give More CISZ. If it is
used random then give less CISZ.

19
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

Using IDCAMS to delete a file


//* DELETE WITH IDCAMS
//DELETE EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
DELETE FILENAME PURGE
SET MAXCC=0  IF THE FILE NOT FOUND THEN IT GIVES RETURN
CODE 8. THIS MAKES IT TO ZERO.
/*

REPRO

Copy one dataset to another dataset. Copy can be done in below ways
VSAM-VSAM
VSAM-PSEQ
PSEQ-VSAM  Extra care is required. Physical sequential file should be sorted on key and
and there shouldn't be duplicates on key.
PSEQ-PSEQ
Copying data into VSAM is called Load.
Copying data from VSAM to PSEQ is called unload.

Method1
//LOADVSAM EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//INDD1 DD DSN=FILENAME1,DISP=SHR
//OUTDD1 DD DSN=FILENAME2,DISP=SHR
//*
//SYSIN DD *
REPRO -
INFILE (INDD1) -
OUTFILE (OUTDD1)
/*
Method2
//LOADVSAM EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//*
//SYSIN DD *
REPRO -
INDATASET (FILENAME1) -
OUTDATASET (FILENAME2)
/*

PRINT A VSAM DATASET


This is used to print vsam and non vsam datasets and catalogs. This is written in to sysout of the
spool.
To print records 21 and 22 in character format
//PRNTVSAM EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//INDD1 DD DSN=FILENAME,DISP=SHR
//*
//SYSIN DD *
PRINT INFILE (INDD1) -
CHARACTER -
SKIP(20) -
COUNT(2)
//*

20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

To check empty file or not


If the file is empty, PRINT COUNT(1) ends with return-code as 4.

//CHKEMPTY EXEC PGM=IDCAMS


//SYSPRINT DD SYSOUT=*
//INDD1 DD DSN=FILENAME,DISP=SHR
//*
//SYSIN DD *
PRINT INFILE (INDD1) CHARACTER COUNT(1)
//*

ALTER PROPERITIES OF VSAM DATASET


It is used to alter attributes of datasets and catalog that have already been defined.

Change VSAM dataset name


//ALTRVSAM EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//INDD1 DD DSN=FILENAME,DISP=SHR
//*
//SYSIN DD *
ALTER -
FILENAME1 -
NEWNAME(FILENAME2)

//*

Change Free space of VSAM dataset


//SYSIN DD *
ALTER -
FILENAME -
FREESPACE(30 30)
/*

LISTCAT
This is used to list the contents of a master or user catalog.

The syntax is
LISTCAT CATALOG (NAME)
ENTRIES (NAME - OF - ENTRIES)
LEVEL (GENERIC-LEVEL-NAMES)

CATALOG('catname/password') Specifies the name of the catalog containing the entries to be


listed.'catname' - Name of the catalog containing the entries to be listed.
'password' - Password of the catalog containing the entries to be listed.
Required - 'catname'

LEVEL('level') specifies the level of entry names to be listed.


'level' - level of entry names to be listed.

ENTRIES('entryname/password' ...) The names of the individual entries to be listed.


'entryname' Name of the object whose entry is to be listed.
'password' Password of password-protected cluster or component or object

21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM

The other parameters that can be provided are:


ALL - All the fields are to be listed for each catalog entry.
NAME - The name and entry type of the cataloged objects are to be listed.
HISTORY - The information provided by specifying name and owner identification, creation
date, expiration date and catalog recovery information for the objects is to be listed.
VOLUME - The information provided by specifying HISTORY and volume serial numbers and
device types allocated to the objects is to be listed.
ALLOCATION - The information provided by specifying VOLUME and detailed information
about the allocation are to be listed.

VERIFY
This parameter is used to verify the physical existence of a VSAM file and close the file if it is
not previously closed successfully.

Syntax : VERIFY FILE (<DDNAME>) OR


VERIFY DATASET (<DATASETNAME>)

This can be issued from TSO or from a JCL. This verifies the catalog HURBA (High Used
Relative Byte Address) field and stores the true values from the control block HURBA field.
It should be used against cluster name only and not against data or index components. This is
used to rectify some of the problems due to data corruption.

Define AIX/PATH/BUILDINDEX

//DEFALTIX EXEC PGM=IDCAMS


//SYSPRINT DD SYSOUT=*
//SYSIN DD *
DEFINE AIX (NAME (OZA183.SMF.EMPAIX) -  AIX NAME
RELATE (OZA183.SMF.EMPMST)-  BASE CLUSTER NAME
RECORDSIZE (22 22) -  5 + ALTKEY SIZE + (1 * PRIMARY
KEY SIZE) 5 + 10 + 1 * 7 = 22
CYL (10 5) -
KEYS (10 17) -  ALTERNATE KEY DETAILS
UPGRADE)  AIX UPDATES IF BASE CLUSTER
UPDATES
/*
//DEFPATH EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
DEFINE PATH (NAME (OZA183.SMF.EMPMST.PATH) -  PATH NAME
PATHENTRY (OZA183.SMF.EMPAIX) -  AIX NAME
UPDATE)  PATH UPDATES IF AIX UPDATES
/*
//BLDINDEX EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=*
//BASEDD DD DSN=OZA183.SMF.EMPMST,DISP=SHR  BASE CLUSTER
//AIXDD DD DSN=OZA183.SMF.EMPAIX,DISP=OLD  AIX
//IDCUT1 DD UNIT=SYSDA,SPACE=(CYL,55)
//IDCUT2 DD UNIT=SYSDA,SPACE=(CYL,55)
//SYSIN DD *
BLDINDEX INFILE (BASEDD) -
OUTFILE (AIXDD)
/*

22
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

DB2

1
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

2
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Data
Data consists of facts and Information about people, objects, events or any other items.

Database
A database is a tool for storing and organizing information (data).
Ex of database is Retail, Insurance, Banking and Financial.

DBMS
A Database Management System (DBMS) is software packages designed to store and manage
databases and also a computerized record-keeping system.

Types of Databases (or Models)

1. Hierarchical Model
2. Network Model
3. Relational Model

Hierarchical Model
Relation between entities is established using parent-child relationship inverted tree structure.
This is the first logical model of DBMS. Data stored in the form of segments.
Example - IMS

Network Model
Any entity can be associated with any other entity. So distinguishing between parent and child is
not possible. This is a linked structure model. Data stored in record and different record types are
linked by SETS.
Example - IDMS

Relational Model
Data stored in the form of tables consists of multiple rows (Tuples) and columns (Attributes).
Examples - DB2, Oracle, Sybase, Ingres etc.

Relational Concepts

Relation: A table or File


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

3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Advantages of DB2 over VSAM

Feature DB2 VSAM

1.Hardware Independence PC to mainframe Only Mainframe

2.Security High degrees of security at table and views Only at region level

3.Concurrency Multiple programs or users can update a table It is possible in online but not in
both in online and batch batch

4.Referential constraints Set Null, Restrict, Cascade is possible No such a facility. It is developers
cannot insert a foreign key if that has no responsibility
reference in parent

5.Independency When a new column is added to a table no Recompile all the programs if the
change in the program when the views are used filler is not there for the new field

6.Restart, in the abend time Program can be restarted from the last Bring corrupted files to original state
commit record. by del/def and load from backup.
Then Restart from the top.

7.Backup Incremental backup No incremental backup


Parallel backup Downtime needed

8.Disaster Recovery Supported by DB2 Part of DASD recovery

9.Improved performance Indexes can be used for the faster retrieval No such a facility

10.Data retrieval Selection criteria on different tables and on One record at a time, one file at a
different columns time.

11.Column functions Group Average, sum, min max, group by, having No such a facility
Functions

12.Program Preparation Extra preparation is required. Extra procedure It is native to COBOL, easy to write,
is required to run no extra coding is required, no extra
preparation is required

13.Occurs on repeated fields Occurs cannot be declared Occurs can be used and it reduces
coding

Variable length records are created


14.Variable length records Variable length fields are available but when different layouts are stored or
Variable length records are not available When occurs depending clause is
used

15.Different layouts It is not possible to store different layouts It is possible to store different layouts in a
in a single table single table

16.Maintenance Cost Costly cheaper

4
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

VSAM vs DB2

Object Creation

VSAM DB2
1.Create in Batch with IDCAMS 1.It is never created in batch
Create in foreground with FILE AID Create in SPUFI/QMF with SQL Query
Create in foreground with FILE AID DB2
2.Specify keys, space, cisz.... 2.No need to specify space
but no need to specify its layout But specify its columns and attributes

Copybook Creation

VSAM DB2
1.Create a copybook manually and 1.Create copybook with DCLGEN option
use it in the program with COPY. in DB2I and declare it with INCLUDE
(or)
Write its layout in the program
2.Supply copy library in the SYSLIB 2.Supply copy library in the SYSLIB of
of compile step Precompile step

How to use in program

VSAM DB2
1. Declare file in Select statement 1/2. Include copybook for table declaration
2. Declare layout in FD entry as well as host variable declaration
3. Declare status in WS 3. Include SQLCA for SQLCODE in WS
4. Open file with mode in PD 4. No need to open tables
5. Read/write/rewrite/start/read next 5. Use embedded sql statements for
file in PD select, insert, update, delete in PD
6. Close file in PD 6. No need to close table
7. Check status code after I-O operation 7. Check SQLCODE after execution of SQL Query
8. Direct relation is available between 8. Columns has to be mapped into host variables
file and its layout in the SQL statement

Program Preparation

VSAM DB2
1. VSAM files are native to COBOL 1. DB2 tables are not native to COBOL program.
programs. So it can be compiled So extra compilation procedure is required.
as a normal COBOL compilation.
2. Compile COBOL + VSAM program 2. Compile COBOL + DB2 program with the
with below steps. below steps.
Step1: Compile Step1: Precompile
Step2: Link Edit Step2: Compile
Step3: Link Edit
Step4: Bind package
Step5: Bind plan

5
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Test data preparation

VSAM DB2
1. Foreground 1. Foreground
a. File Aid for files a. File Aid for DB2
b. DITTO b. DB2 manager
2. Batch 2. Batch
Copy test data by using batch utility Copy test data by using batch utility
program IDCAMS From VSAM to VSAM program DSNUTILB from PS to DB2
From PS to VSAM
3. No such a facility 3. By executing Insert/Update from
SPUFI/QMF

Program execution with RUN JCL

VSAM DB2
//step1 exec pgm=PGM1 //step1 exec pgm=IKJEFT01
//steplib dd dsn=userid.loadlib1,disp=shr //*
//infile dd dsn=userid.infile,disp=shr //infile dd dsn=userid.infile,disp=shr
//agtmst dd dsn=userid.agtmst,disp=shr //outfile dd dsn=userid.outfile,
//outfile dd dsn=userid.outfile, // disp=(new,catlg,delete)
// disp=(new,catlg,delete), // unit=sysda,
// unit=sysda, // space=(cyl,(5,2),rlse),
// space=(cyl,(5,2),rlse), // dcb=(recfm=fb,lrecl=100,blksize=0)
// dcb=(recfm=fb,lrecl=100,blksize=0) //systsin dd *
DSN System(DB2T) -
Run Program(PGM1) Plan(PLAN1) -
Library(Userid.loadlib1)
/*

1.Program name is specified in PGM parameter 1. IKJEFT01 is specified in PGM parameter


2.VSAM file AGTMST is specified under program 2. No need to specify the tables in JCL

Normalization (1NF - 5NF)

It is done to bring the design of database to a standardized mode or (form)

1NF: All entities must have a unique identifier, or key, that can be composed of one or more
attributes. All attributes must be atomic and none repeating.
2NF: Partial functional dependencies removed - all attributes that are not a part of the key must
depend on the entire key for that entity.
3NF: Transitive dependencies removed - attributes that are not a part of the key must not depend
on any non-key attribute.
4NF: Multi valued dependencies removed.
5NF: Remaining anomalies removed.

6
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

STRUCTURE OF DB2

The elements of DB2 are divided into two broad categories.


1. Data structures
2. System structures

Data structures
Data structures contain user data and are accessed under user’s direction.
It consist of Databases,Db2 storage groups, Table spaces, Tables, Index spaces, indexes, Views,
Synonyms, Aliases.

System structures
System structures are controlled and accesses by DB2.
It consists of Db2 Catalog, Db2 Directory, Active and Archive logs, Buffer pools.

Databases:
DATABASE1

TABLESPACE 1

INDEX 1 TABLE 1 TABLE 2

INDEX 2

TABLESPACE 2

Database is a collection of a number of table spaces along with a set of index spaces.
A stored table and all it’s associated indexes must be in a single database.
When you create a table space or table and do not specify the database the object will be created
in the default database DSNDB04.

Db2 storage groups:


STORAGE GROUP 1
VOLUME 1 VOLUME 2

User and System Databases are physically stored in the datasets of specified storage groups.
Storage group is a set of volumes of direct access storage devices (DASD).Parts of single
database can be stored in different storage groups. Default storage group is SYSDEFLT.

7
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Table spaces:
Table space is made up of one or more VSAM linear datasets (LDS).where one or more tables are
stored. A table space is divided into 4k or 32k pages. A page is a unit of I/O transmission. A page
may contain one or more rows (max 127). A row must lie within a page.

TABLESPACE 1

TABLE 1

TABLE 2

SIMPLE SEGMENTED PARTITIONED

Simple Table space


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.

Simple tablespace
Page1 Page2
-------------- --------------
| TBL1 ROW1 | | TBL1 ROW4 |
| TBL2 ROW1 | | TBL2 ROW3 |
| TBL3 ROW1 | | TBL3 ROW3 |
| TBL1 ROW2 | | TBL1 ROW5 |
| TBL1 ROW3 | | TBL2 ROW3 |
| TBL2 ROW2 | | TBL3 ROW4 |
| TBL3 ROW2 | | TBL3 ROW5 |
-------------- --------------

Segmented Table spaces


An 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. 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.
Segmented Tablespace
Segment1 Segment2
------------------------------------- -------------------------------------
| Page1 Page2 | | Page1 Page2 |
| ------------ ------------ | | ------------ ------------ |
| | TBL1 ROW1 | | TBL1 ROW8 | | | | TBL2 ROW1 | | TBL2 ROW8 | |
| | TBL1 ROW2 | | TBL1 ROW9 | | | | TBL2 ROW2 | | TBL2 ROW9 | |
| | TBL1 ROW3 | | TBL1 ROW10| | | | TBL2 ROW3 | | TBL2 ROW10| |
| | TBL1 ROW4 | | TBL1 ROW11| | | | TBL2 ROW4 | | TBL2 ROW11| |
| | TBL1 ROW5 | | TBL1 ROW12| | | | TBL2 ROW5 | | TBL2 ROW12| |
| | TBL1 ROW6 | | TBL1 ROW13| | | | TBL2 ROW6 | | TBL2 ROW13| |
| | TBL1 ROW7 | | TBL1 ROW14| | | | TBL2 ROW7 | | TBL2 ROW14| |
| ------------ ------------ | | ------------ ------------ |
------------------------------------- -------------------------------------

8
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

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.
Partitioned Tablespace
Page1 Page2 Page3 Page4
------------ ------------ ------------ ------------
| TBL1 ROW1 | | TBL1 ROW8 | | TBL1 ROW15| | TBL1 ROW22|
| TBL1 ROW2 | | TBL1 ROW9 | | TBL1 ROW16| | TBL1 ROW23|
| TBL1 ROW3 | | TBL1 ROW10| | TBL1 ROW17| | TBL1 ROW24|
| TBL1 ROW4 | | TBL1 ROW11| | TBL1 ROW18| | TBL1 ROW25|
| TBL1 ROW5 | | TBL1 ROW12| | TBL1 ROW19| | TBL1 ROW26|
| TBL1 ROW6 | | TBL1 ROW13| | TBL1 ROW20| | TBL1 ROW27|
| TBL1 ROW7 | | TBL1 ROW14| | TBL1 ROW21| | TBL1 ROW28|
------------ ------------ ------------ ------------
One segmented tablespace is created for each table in many real applications.

Tables:
A relational database stores data in the form of tables. Table consists of a number of records.
Record contains Columns, Rows, Keys etc. Each record should be contained in a single page but
a table can be spread over pages.
For example SUPPLIER table looks like:
Each COLUMN contains some specific information about suppliers and each ROW contains all
the information about a particular supplier.
KEY COLUMNS

SNO SNAME STATUS CITY

ROWS S1 SMITH 20 LONDON


S2 JONES 10 PARIS
S3 BLAKE 30 PARIS
S4 CLARK 20 LONDON
S5 ADAMS 30 ATHENS

Views:
What is a View
• View is a subset of a table and it is created with a select query on a table
• View does not occupy any memory to store the data
Syntax:
CREATE VIEW view_name AS
SELECT columns
FROM table
WHERE predicates;

DROP VIEW view_name;

Ex:
Create View EMP_2011 as
SELECT * from emp
where emp_doj >= 20110101
and emp_doj <= 20111231;

9
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SELECT *
from EMP_2011
where emp_status = 'A';

DROP VIEW EMP_2011;

Advantages of View
1. It is mainly used to restrict the table data from different users.
Views can limit the degree of exposure of a table or tables to the outer world.
Ex: Employee salary details can be hide from departments other than HR
2. Views can hide the complexity of data;
Ex: for example a view could appear as Sales2000 or Sales2001
3. Views can join and simplify multiple tables into a single virtual table
4. Views take very little space to store view definition
5. Views reduce future maintenance of the program when new fields are added in the
base table and those fields are not required in the program.

Disadvantages of View
1. When a query is executed on view, then it executes twice.
First time to execute view and second time to execute query on view.
2. When a table is dropped, then view becomes inactive
3. Some situations unnecessary data is retrieved from base table and a less data is
required from this view then it degrades the performance
4. DML(Insert, Update, delete) is not allowed when it is declared on multiple tables
with join

Non updatable views/Read only views


1. DISTINCT is used in the view definition
2. Aggregate function is used on columns
3. Join used on view definition
4. Group by and having clause is used
5. View is created with sub-queries

Index Spaces:
Only one index is stored in an indexed space.
An Index space is automatically created when the corresponding index is created.
Pages in an index space are 4k bytes in size.
Index space for partitioned table space is partitioned.

Index:
An index contains values from one or more of a table’s columns and a pointer to the record in a
data which matches the index value. DB2 will find data more efficiently by scanning the index
and following the pointer than by scanning the entire tablespace.

Index consists of two parts, Record id (RID) and Indexed value.


Record ID of index has two parts. First part is to identify the page where the record lies and the
second part is the byte offset from the bottom of the page identifying the record. Index is
structured in ascending or descending sequence on one or more columns. A given value of
interest can be located quickly in the index because of their ascending or descending structure.

10
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

In the example, Index is used to find a Record (T) in Page P.


INDEX 1

RID VALUE

PAGE P

An index created on a table in a partitioned table space is a partitioned index and is divided into
multiple index spaces.
Indexes are of two types, unique and non unique indexes. A non unique index can reference
duplicate values, a unique index will not. You can create an index any time after you create the
table. But creating an index before loading the data provides significant performance advantages.
Indexes can be clustered or non clustered. A clustering index is one in which the records are
physically stored in data pages in the sequential order of their index values. The index is used to
control physical placement of the indexed records. Newly inserted records are physically stored
such that the physical sequence of those records in storage closely approximates the logical
sequence as defined by the index. In a non clustered index the records will not be in the order of
index values.
A table can have any number of indexes but it can have only one clustered index.
Clustering is extremely important for optimization purpose. The optimizer will try to choose an
access path based on the clustering index .

Table Data and Index Data


EMP Table Index on Emp_num Index on Salary
E001 20000.00 E001 Row1 10000.00 Row7
E002 30000.00 E002 Row2 15000.00 Row6
E004 20000.00 E003 Row4 15000.00 Row8
E003 30000.00 E004 Row3 20000.00 Row1
E005 20000.00 E005 Row5 20000.00 Row3
E008 15000.00 E006 Row8 20000.00 Row5
E007 10000.00 E007 Row7 30000.00 Row2
E006 15000.00 E008 Row6 30000.00 Row4
Records in the table are not in the sorted order on any field.
Records in the index are in the ascending order on the index field.
Select on the table takes index scan when there is index created on predicate, otherwise it takes
table scan. Table scan is much slower than index scan.

EMP Table Clustering Index on emp_num Index on salary


E001 20000.00 E001 Row1 10000.00 Row7
E002 30000.00 E002 Row2 15000.00 Row8
E003 30000.00 E003 Row3 15000.00 Row8
E004 20000.00 E004 Row4 20000.00 Row1
E005 20000.00 E005 Row5 20000.00 Row4
E006 15000.00 E006 Row6 20000.00 Row5
E007 10000.00 E007 Row7 30000.00 Row2
E008 15000.00 E008 Row8 30000.00 Row3

11
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Records in the table will be stored in the same order of clustering index. Only one clustering
index can be created on table.

Aliases:
An Alias is an alternative name for a Table or View. It is a qualified name that can be used by any
Authorization id.
An Alias can be defined for a table or view that was created by some other user and for which
you would otherwise have to use a fully qualified name.
Aliases were designed for a distributed environment to avoid having to reference the location
qualifier of table or view.
Alias is not private to the creator.
An alias can be defined on an undefined name. That is the object on which the alias is created
need not be present at the creation time.

Synonyms:
Synonyms are useful for creating more meaningful name for a person using a Table or View.
A Synonym is an unqualified name that can only be used by the Authorization id that created it.
A Synonym is private to the user who creates it.
Synonym cannot refer to remote Table in a distributed data environment.
A Synonym can only be defined on the name of an existing Table or View.

DB2 Catalog:
The CATALOG in DB2 is a system database that contains information concerning various
objects that are of interest to DB2 itself. Examples of such objects are tables, views, indexes,
databases, plans, packages, access privileges, and so on. These information is essential, if the
system is to able to do it’s job properly.
CATALOG itself contains TABLES and you can see the contents of catalog tables using normal
query language ( SQL ). When you create, drop or alter any structure, DB2 updates or deletes
rows of the catalog that describe the structure.

Example of Catalog Tables


SYSIBM.SYSTABLES: It contains information of a table. When a new Table is created db2
inserts one row into this catalog Table.
SYSIBM.SYSCOLUMNS: It contains information about the columns in a table. This table
contains one row for every column of each row in a Table.
SYSIBM.SYSTABLESPACE: It contains information of the table space created. The table
contains one row for each tablespace.
SYSIBM.SYSTABAUTH: It contains information of the table names and Authorization id’s
which have privileges on that table.

DB2 Directory:
It contains information required to start db2 and db2 uses the directory during normal operation.
It consists of a set of db2 Tables stored in 5 table spaces in system database DSNDB01.
1. SKELETON CURSOR TABLESPACE (SCT02) contains Plans.
2. SKELETON PACKAGE TABLE (SPT01) contains Packages.
3. LOG RANGE TABLE SPACE (SYSLGRNX) contains the RBA (Relative byte address ) and
the log dataset.
4. SYSTEM UTILITIES TABLE SPACE (SYSUTILX) contains the information about
Running UTILITIES.

12
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

5.THE DATABASE DESCRIPTOR TABLE SPACE (DBD01) contains interval control


Blocks that describe the databases existing within db2.
6. Cannot Access DIRECTORY Using SQL.

Active and Archive logs:


Db2 records all data changes and significant events in a log as they occur.
Db2 writes each log record to a DASD Dataset called the Active Log.
When the Active log is full, Db2 copies the contents of the Active Log to a DASD
Called the Archive Log. The Archive Log can consist of up to 1000 datasets each of which is a
sequential dataset. In the case of failure Db2 uses Logs to recover data.

Buffer Pools:
Buffer pools, also known as virtual buffer pools, are areas of virtual storage used temporarily to
store pages of table spaces or indexes. When an application program needs to access a row of a
table, DB2 retrieves the page containing that row and places the page in a buffer. If the row is
changed, the buffer must be written back to the table space. If the needed data is already in a
buffer, the application program will not have to wait for it to be retrieved from DASD. The result
is faster performance.

DB2 can provide 2 types of buffer pools, 4K and 32K buffer pools. There are fifty 4K buffer
pools named BP0, BP1, P49 and ten 32K buffer pools named BP32K, BP32K1, BP32K9.

DB2 DATA TYPES

Data type depends on the nature of the data itself and will always be one of two types NUMERIC
or CHARACTER .

Types of CHARACTER column


CHAR – Allows any values to be entered in the column. All entries are the same length
VARCHAR – Allows any values to be entered in the column. All entries are the varying length.

Types of NUMERIC columns


INTEGER - For very large integers up to 2,147,483,647
SMALLINT - For small integer up to 9999

DECIMAL - For numbers with a fixed number of decimal places after the decimal point. The
number can have a total of 15 digits
FLOAT -For very large numbers with an undetermined number of decimal places after the
decimal point .

Types of DATE/TIME columns


DATE - Dates are stored in YYYYMMDD format
TIME - Times are stored on a 24-hour clock in HHMMSS format
TIMESTAMP – TIMESTAMP columns contain both date and time information, with the time
value accurate to the millisecond.

13
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Db2 Data types and equivalent host variables

DB2 Column Bytes Cobol PIC clause Bytes


SMALLINT 2 PIC S9(04)COMP 2

INTEGER 4 PIC S9(09)COMP 4

DECIMAL(P,Q) INT(P/2) PIC S9(P-Q)V9(Q) INT(P/2 +1)


(P Should be less than 32)

DATE 4 PIC X(10) 8

TIME 3 PIC X(08) 6

TIMESTAMP 10 PIC X(26) 26

CHAR(N) (N =1 to 254) N PIC X(N) N

VARCHAR(N) (N = 0-4046) N 01 COL-NAME. N+2


49 COL-NAME-LEN PIC S9(4)COMP.
49 COL-NAME-TEXT PIC X(N).

14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

STRUCTURED QUERY LANGUAGE (SQL)

A powerful database management language that performs the function of data manipulation, data
definition and data control and a non-procedural language.

SQL - Types (based on the functionality)

Data Definition Language (DDL)


- Create, Alter and Drop

Data Manipulation Language (DML)


- Select, Insert, Update and Delete

Data Control Language (DCL)


- Grant and Revoke

Data Definition Language (DDL)


DDL statements are used to create and maintain DB2 objects like storage groups, databases,
table spaces, tables, indexes, synonyms, aliases and views.
CREATE  Defines a new db2 object.
ALTER  Changes the characteristics of a db2 object.
DROP  Removes an existing db2 object.
These can be executed interactively or embedded in an application program.

DDL - CREATE STOGROUP


Creates a storage group and specifies a list of volumes that db2 can use in the order specified in
the statement.
Syntax:
CREATE STOGROUP stogroup-name
VOLUMES (vol1, vol2, ...)
VCAT catalog-name
[PASSWORD password]

DDL - ALTER STOGROUP


The ALTER STOGROUP statement can be used to add or remove DASD volumes associated
with the storage group. In the example adds the volumes DBPK03 and removes DBPK01 from
the storage group description.
Syntax:
ALTER STOGROUP stogroup-name
ADD VOLUMES (vol4, vol5, ...)
REMOVE VOLUMES (vol1, vol2, ...)
[PASSWORD password]
Example:
ALTER STOGROUP TRG1T01
ADD VOLUMES (DBPK03)
REMOVE VOLUMES (DBPK01)

DDL - CREATE DATABASE


The create database statement defines a db2 database to the db2 subsystem. The name must not
start with DSNDB and must not identify an existing database. In this statement you can specify
the name of buffer pool and storage group for table spaces and indexes with the database.

15
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

If buffer pool is not specified in the create database statement then default buffer pool used is
BP0.If storage group is not specified in the create database statement then default storage group
used is SYSDEFLT.
Syntax:
CREATE DATABASE database-name
[STOGROUP stogroup-name]
[BUFFERPOOL bufferpool-name]

DDL - CREATE TABLESPACE


Syntax:
CREATE TABLESPACE tablespace-name
[IN database-name]
[USING {VCAT VSAM-CATALOG-NAME/STOGROUP stogroup-name}]
[PRIQTY qty]
[SECQTY qty]
[ERASE YES/NO]
[LOCKSIZE ANY/PAGE/TABLESPACE/TABLE]
[BUFFERPOOL BP0/BP1/BP2/BP32K]
[CLOSE YES/NO DSETPASS password]
[FREEPAGE <amount>]
[PCTFREE <amount>]
database-name : The database in which the tablespace should be created. The default is
DSNDB04.
USING clause: The method of storage allocation for the tablespace is defined using the USING
parameter. In this clause, the STOGROUP name combined with the a primary (PRIQTY) and
secondary quantity(SECQTY) for space allocation can be specified or a VCAT identifier for user-
defined VSAM data sets. In future, we assume that the STOGROUP is specified.
primary allocation (PRIQTY): It is the amount of physical storage allocated when the
tablespace is created. The amount of storage space specified in qty must be available on the first
volume. As the amount of data in the tablespace grows, secondary allocations of storage
(SECQTY) are taken.
• If the PRIQTY is not specified, it is 3
• If the PRIQTY is specified, and if the page size of the table is
- 4K bytes, then the number is qty/4 rounded upto the next highest integer, but not less than 3.
- 32K bytes, then the number is qty/32 rounded upto the next highest number, but not less
than 3.
Similar rules are applicable for SECQTY also.
ERASE option: It specifies whether the physical DASD where the tablespace data set resides
should be written over with binary zeroes when the tablespace is dropped. The default is ERASE
NO.
Locksize parameter: It specifies the type of locking DB2 performs for the given tablespace.
PAGE - Page level locking
TABLE - Table-level locking (for segmented tablespaces only)
TABLESPACE - Tablespace-level locking
ANY - Lets DB2 decide, starting with PAGE (default value)
In general, it is best to let DB2 handle the level of locking required i.e.. ANY option. Locking
begins with PAGE locks and escalates to TABLE or TABLESPACE locks if DB2 determines that
the number of page locks acquired for a tablespace exceeds the maximum number of locks
allowed for a tablespace (an installation parameter).
Bufferpool option:
The four bufferpool options for DB2 objects consist of three 4K bufferpools - BP0, BP1, BP2 -
and one 32K bufferpool - BP32K. The default value is the bufferpool name for the database.

16
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

CLOSE option: It tells whether to close the data sets supporting the table space when there are
no current users of the table space. The dafault value is CLOSE YES.
FREEPAGE parameter : It specifies how often to leave a page of free space when the
tablespace or partition is loaded or reorganized. It can take values from 0 to 255. If the value is 0,
no free pages are left as free space. Otherwise, one free page is left after every amount pages.
PCTFREE parameter: It tells what percentage of each page to leave as free space when the
table is loaded or reorganized. amount may vary from 0 to 99. The first record in each page is
loaded without restriction. The default value is PCTFREE 5.
Example:
CREATE TABLESPACE
IN DSN8D2AP
USING STOGROUP DSNS6200
PRIQTY 12
SECQTY 12
ERASE NO
LOCKSIZE ANY
CLOSE YES
BUFFERPOOL BP0.

DDL - CREATE TABLE


Syntax1:
CREATE TABLE tablename
( column-definition [, column-definition] ...
[, primary-key-definition]
[, foreign-key-definition
[, foreign-key-definition] ...]
[other-parameters] )
[ IN databasename.tablespacename /
IN DATABASE databasename]
Create table statement creates a table in a table space. Table name is unique for a user. If USERA
Creates TABLEA then fully qualified name will be USERA.TABLEA .
USERA can simply use the name TABLEA but other users must specify fully qualified name.
if the tablename is unqualified, the SQL ID is the owner of the table.

column-definition:
The columns of the table are identified using this parameter. Column name column type [NOT
NULL / NULL / NOT NULL WITH DEFAULT] This defines the name, column type associated
with each of the columns of the table. The column name can be a maximum of 18 characters
starting with an alphabet.
The column type can be any of the DB2 data types. The column can be of one of the following
types.
NOT NULL - cannot contain null values
NULL - can have null values
NOT NULL WITH DEFAULT - prevents a column from containing null values, and allows a
default value other than the null value.

Data Type Default Value


Numeric 0
Fixed-length string blanks
Varying-length string a string of length 0
Date current date
Time current time
Timestamp current timestamp

17
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

When NOT NULL or NOT NULL WITH DEFAULT is not specified, then the column is
nullable.

primary-key-definition:
Primary key of a table is the unique identifier for that table. A Table cannot have more than one
primary key, and the columns of a primary key cannot contain null values. When a primary key is
defined on a table, a unique index must be created on that primary key.
This parameter defines the columns that form the primary key.
PRIMARY KEY (colname1, colname2, ...)

foreign-key-definition:
This parameter defines the foreign key(s) associated with the table.
FOREIGN KEY [constraint-name]
(colname1 [, colname2] ...)
REFERENCES base-table
[ON DELETE RESTRICT / CASCADE /
SET NULL]
Each specification of the FOREIGN KEY defines a referential constraint with the specified name.
A name is generated if the constraint-name is not specified. The foreign key of the referential
constraint is composed of the specified columns. Each name in the column list must identify a
column of the table. The base-table identified in the after the REFERENCES must identify a table
in the catalog.
The delete rule of the relationship is determine by the ON DELETE clause. The default value is
ON DELETE RESTRICT. This rule is explicitly specified for each foreign key in a table. The
DELETE rule states the requirements to be met when ....
“... a row in a parent table is deleted. Each foreign key is associated with its own DELETE rule.
All applicable DELETE rules are used to determine whether or not a delete is done.”

RESTRICT option A row of a parent table cannot be deleted if rows exist in the dependent
table(s) with foreign key values equal to the primary key value of this row.

CASCADE option If a row of a parent table is deleted, then: all rows in the dependent table(s)
with foreign key values equal to the primary key value of this row will also be deleted. The delete
will also impact the dependents of the dependent table(s).

SET NULL option If a row of a parent table is deleted then all rows in the dependent table with a
foreign key value equal to the primary key value of this row will have its foreign key value
changed to NULL.

IN clause:
This specifies the database and tablespace in which the table is created. If the IN DATABASE
clause is used then a tablespace is implicity created with name derived from the tablename.

Example:
CREATE TABLE EMPLOYEE(
EMPNO CHAR(6) NOT NULL PRIMARY KEY,
FNAME CHAR(10),
LNAME CHAR(10) NOT NULL,
DEPTNO CHAR(03),
SALARY DECIMAL(9,2) NOT NULL)
IN DB-NAME.TS-NAME;

18
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Syntax 2:
CREATE TABLE tablename
LIKE existing-tablename

This format allows the user to create a table tablename with the same column description as
some existing table existing-tablename. The table tablename does not inherit any primary or
foreign key definitions from existing-tablename.
Example:
CREATE TABLE EMPLOYEE.TEMP LIKE EMPLOYEE IN DB-NAME.TS-NAME;

DDL – CREATE VIEW


Syntax:
CREATE VIEW view-name
[(column-name, ...)]
AS SELECT column-name, column-name, …….
FROM table-name
[WHERE condition]
[WITH CHECK OPTION]
The CREATE VIEW creates a view on one or more tables or views.
If the view name in unqualified then the Authorization id is the implicit qualifier.
The column-name is a list of columns in the view. If the column names are not specified, then the
view inherits the names of the columns used in the subselect. The view consists of rows that
result from the execution of the subselect.

Example:
CREATE VIEW EMP_VIEW
AS SELECT EMPNO,NAME,DEPT,JOB FROM EMPLOYEE.

DDL – CREATE INDEX


Syntax:
CREATE [UNIQUE] INDEX indexname
ON tablename (colname [ASC/DESC], ...)

UNIQUE: Prevents the table from containing two or more rows with the same value of the index
key. There can be more than one UNIQUE INDEX for a table. Uniqueness is checked during
Update, Insert or LOAD of insert key. The constraint is also checked during the CREATE
INDEX statement. If the table contains rows with duplicate values, then the index is not created.
ASC/DESC : The index entries are put in ascending order by the column with ASC and in
descending order with DESC. The default value is ASC.
Creating unique index on a null column is possible if there is only one null is available in that
column.
Example:
CREATE UNIQUE INDEX EMPI ON EMPLOYEE (EMPNO);
(or)
CREATE TYPE 2 UNIQUE INDEX EMPI ON EMPLOYEE (EMPNO);

DDL – CREATE SYNONYM


Syntax:
CREATE SYNONYM synonym-name
FOR userid.table-name/userid.view-name
The CREATE SYNONYM defines a synonym for a table or view.
FOR introduces the name of table or view to which the synonym will apply. The name must be
qualified.

19
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

DDL – CREATE ALIAS


Syntax:
CREATE ALIAS alias-name
FOR userid.table-name/userid.view-name
The CREATE ALIAS defines a alias for a table or view.

DDL - ALTER Statement


Syntax
ALTER TABLE tablename
ADD column-definition
ADD PRIMARY-KEY column-name
ADD FOREIGN KEY [constraint-name] (column-name[,column-name….])
REFERENCES base-table
[ON DELETE RESTRICT / CASCADE / SET NULL]

DROP PRIMARY KEY


DROP FOREIGN KEY constraint-name

Alter is a DDL statement and it is used to the change the table definition on the below reasons.
1. To add/drop column to the table
2. To change an existing column definition to increase length of the field.
3. To add/drop constraints

Different types in alter statement


ALTER TABLE tab1 DROP COLUMN c1;
ALTER TABLE tab1 DROP COLUMN c1 DROP COLUMN c2 DROP COLUMN c3;
ALTER TABLE tab1 ADD COLUMN c1 INT NOT NULL;
ALTER TABLE tab1 ADD COLUMN c1 INT NOT NULL ADD COLUMN c2 CHAR(40);
ALTER TABLE tab1 ALTER COLUMN c1 SET DATA TYPE INT;
ALTER TABLE tab1 ALTER COLUMN c1 SET DATA TYPE CHAR(20);
ALTER TABLE tab1 ALTER COLUMN c1 SET NOT NULL;
ALTER TABLE tab_emp ADD CONSTRAINT fk_dept FOREIGN KEY(dept_no)
REFERENCES tab_dept(deptno) ON DELETE SET NULL;

ALTER TABLE EMP ADD CONSTRAINT unique_passport UNIQUE(passport_num));


ALTER TABLE EMP ADD CONSTRAINT Manager_age CHECK (JOB = 'Mgr' and AGE >= 40)

REORG-recommended ALTER
Reorg is recommended when table row format is altered otherwise table turned into reorg pending
status. In this case all operations on the table cannot be executed.

Ex of reorg recommended operations


ADD column
DROP column
Alter Column set data type..
Ex of reorg not recommended operations
Alter column set not null
ADD Constraint

Authorization required for ALTER


The privileges held by the authorization ID of the statement must include at least one of the
following:
• ALTER privilege on the table to be altered
• CONTROL privilege on the table to be altered

20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

• ALTERIN privilege on the schema of the table


• SYSADM or DBADM authority
• REFERENCES privilege on the table to drop or create foreign key

How to do reorg on the table/index


REORG TABLE table_owner.table_name
REORG TABLE table_owner.table_name
REORG INDEXE Index1;
REORG INDEXES ALL FOR TABLE table_owner.table_name

Runstats after Reorg


Execute runstats after Reorg then it collects latest statistics of the table.
RUNSTATS ON TABLE table_owner.table_name FOR INDEXES ALL

DDL - DROP Statement


Syntax:
DROP OBJECT-TYPE OBJECTNAME
The DROP statement deletes an object. Any objects that are directly or indirectly dependent on
that object are also deleted. object-type can be TABLE, VIEW, INDEX, SYNONYM,
STOGROUP, DATABASE, TABLESPACE.

Example:
DROP DATABASE TRG1T01
DROP TABLE SUPPLIER
DROP INDEX XS

Constraints

Constraints are used to maintain data integrity. These constraints imposes rules on fields.
Different types of constraints.
1. Primary Key
2. Foreign key
3. Unique
4. Check

CREATE TABLE EMP_TBL


(ID SMALLINT NOT NULL PRIMARY KEY,
COUNTRY_CODE CHAR(3) NOT NULL,
FIRST_NAME CHAR(20),
LAST_NAME CHAR(20).
DEPTNO SMALLINT CHECK (DEPT BETWEEN 10 AND 100),
JOB_CODE CHAR(5) CHECK (JOB IN ('Sales', 'Mgr', 'Clerk')),
HIREDATE DATE,
PASSPORT_NO CHAR(10) UNIQUE,
AGE SMALLINT CHECK (AGE >=21),
SALARY DECIMAL(7,2),
COMM DECIMAL(7,2),

FOREIGN KEY(DEPTNO) REFERNCES DEPT_TBL(DEPTNO)


ON DELETE CASCADE/SET NULL/RESTRICT,

CONSTRAINT unique_name UNIQUE(FIRST_NAME, LAST_NAME),


CONSTRAINT Manager_age CHECK (JOB = 'Mgr' and AGE >= 40))

IN DBNAME.TSNAME;

21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Primary key constraint


• Primary key should be unique and only primary key can be coded on a table.
As shown in the table declaration, if a primary key is created on single column then it can
be coded at column level. If the primary key has to be created on multiple fields then code
after the column definitions but not on column level.
Ex: Create a primary key with COUNTRY_CODE first and ID next. Now the combination of
COUNTRY_CODE and ID is unique. Then code it as shown below.
PRIMARY KEY(COUNTRY_CODE, ID)

Foreign Key constraint


• Foreign key is used to create a relation between child table and parent table.
• A field used in the child table for the relation is called foreign key and field related in the parent
parent table is called Primary key.
• Parent table should be created prior to create a foreign key in the child table.
• Foreign key in the child table need not be unique.
• Foreign key can be created with single or multiple fields.
• Foreign key can be coded with delete contraints. It says about what is the restriction
rule to delete parent record when that has a reference record in the child table.
Ex: DEPTNO in EMP_TBL is created as foreign key that relates DEPT_NO in the parent table.
ON DELETE CASCADE : When department is deleted from parent table then all employees
on child table for that department will be deleted automatically.
ON DELETE SET NULL : When department is deleted from parent table then all employees
on child table for that department will be set with NULL on
DEPNO field.
ON DELETE RESTRICT : When trying to delete a department from parent table, if any
employee is referenced to that department in the child table then
parent record cannot be deleted.
Make sure there are no child records on that parent record and
then delete parent record.

Unique constraint
• It will enforce unique key on a single field or combination of multiple fields
• If it is given on a single field then it can be coded in the column definition otherwise it should
be declared at the end of the column definition in the table declaration.
Ex1: PASSPORT_NO should be unique
Ex2: Combination of FIRST_NAME and LAST_NAME should be unique

CHECK Constraint
• It will enforce the list of values or range of values for the given column or columns.
• If a constraint on the single field then it can be coded on the field definition otherwise it should
be at the end of the column definition in the table declaration.
Ex1: DEPTNO can be inserted or updated with values between 10 and 100.
Ex2: JOB can be updated only with list of values 'Sales' or 'Clerk' or 'Mgr'
Ex3: Check constraint on multiple fields
If the value in the job is 'Mgr' then age should be >= 40

22
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

ADD/DROP constraints
All the above 4 constraints can be added/dropped with alter statement as shown below.
Examples:
1. ALTER TABLE EMP_TBL ADD CONSTRAINT Clrek_sal
CHECK (JOB = 'Clerk' and SALARY < 50000.00);
2. ALTER TABLE EMP_TBL DROP CONSTRAINT Manager_age;
3. ALTER TABLE EMP_TBL ADD CONSTRAINT fk_Jobs
FOREIGN KEY(JOB_CODE)
REFERENCES JOBS_TBL(JOB_CODE) ON DELETE SET NULL;

CREATION OF EMPLOYEE TABLE


CREATE TABLE EMPLOYEE(
EMPNO CHAR(6) NOT NULL PRIMARY KEY,
FNAME CHAR(10),
LNAME CHAR(10) NOT NULL,
DEPTNO CHAR(03),
WPHONE CHAR(08) NOT NULL,
STARTDT DATE,
SEX CHAR(01) NOT NULL,
SALARY DECIMAL(9,2) NOT NULL)
IN DB-NAME.TS-NAME;

CREATE TYPE 2 UNIQUE INDEX EMPLOYEEI ON EMPLOYEE (EMPNO);

INSERT INTO EMPLOYEE VALUES


('307117','MARY ','JOHNSON ','100','290-4788','1973-05-16','F',48000.00);
INSERT INTO EMPLOYEE VALUES
('604985','JASON ','JONES ','500','290-4128','1988-04-09','M',18000.00);
INSERT INTO EMPLOYEE VALUES
('911723','SHARON ','DYLER ','300','290-4366','1979-11-21','F',30000.00);
INSERT INTO EMPLOYEE VALUES
('827611','JOHN ','LEBLANC','100','290-4875','1984-01-15','M',42000.00);
INSERT INTO EMPLOYEE VALUES
('642655','FRANK ','RYDZIK ','300','290-4789','1986-09-10','M',28000.00);
INSERT INTO EMPLOYEE VALUES
('737466','GAIL ','BAKER ','100','290-4112','2005-05-17','F',38000.00);
INSERT INTO EMPLOYEE VALUES
('215012','GARY ','SHELDON','200','290-4631','1987-02-01','M',31000.00);
INSERT INTO EMPLOYEE VALUES
('871330','KATHY ','ZWIRNER','500','290-4267','1983-08-15','F',26000.00);
INSERT INTO EMPLOYEE VALUES
('711674','FRED ','MAYR ','100','290-4211','1987-12-01','M',33000.00);

SELECT * FROM EMPLOYEE;

+------------------------------------------------------------------+
¦EMPNO ¦ FNAME¦ LNAME ¦DEPTNO¦ WPHONE ¦ STARTDT¦SEX¦ SALARY ¦
+------+--------+---------+------+--------+-----------+---+--------¦
¦307117¦MARY ¦JOHNSON ¦ 100 ¦290-4788¦ 1973-05-16¦ F ¦48000.00¦
¦604985¦JASON ¦JONES ¦ 500 ¦290-4128¦ 1988-04-09¦ M ¦18000.00¦
¦911723¦SHARON ¦DYLER ¦ 300 ¦290-4366¦ 1979-11-21¦ F ¦30000.00¦
¦827611¦JOHN ¦LEBLANC ¦ 100 ¦290-4875¦ 1984-01-15¦ M ¦42000.00¦
¦642655¦FRANK ¦RYDZIK ¦ 300 ¦290-4789¦ 1986-09-10¦ M ¦28000.00¦
¦737466¦GAIL ¦BAKER ¦ 100 ¦290-4112¦ 2005-05-17¦ F ¦38000.00¦
¦215012¦GARY ¦SHELDON ¦ 200 ¦290-4631¦ 1987-02-01¦ M ¦31000.00¦
¦871330¦KATHY ¦ZWIRNER ¦ 500 ¦290-4267¦ 1983-08-15¦ F ¦26000.00¦
¦711674¦FRED ¦MAYR ¦ 100 ¦290-4211¦ 1987-12-01¦ M ¦33000.00¦
+------------------------------------------------------------------+

23
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

CREATION OF DEPARTMENT TABLE

CREATE TABLE DEPARTMENT(


DEPTNO CHAR(3) NOT NULL PRIMARY KEY,
DEPTNAME CHAR(15),
MANAGER CHAR(6) NOT NULL)
IN DB-NAME.TS-NAME;

CREATE TYPE 2 UNIQUE INDEX DEPTI ON DEPARTMENT (DEPTNO);

INSERT INTO DEPARTMENT VALUES ('100','PRODUCTION ','737466');


INSERT INTO DEPARTMENT VALUES ('200','ACCOUNTING ','865403');
INSERT INTO DEPARTMENT VALUES ('300','PERSONNEL ','491640');
INSERT INTO DEPARTMENT VALUES ('400','ENGINEERING','604985');

SELECT * FROM DEPARTMENT;

DEPARTMENT TABLE
+-------------------------------+
¦DEPTNO¦ DEPTNAME ¦ MANAGER¦
+------+---------------+--------¦
¦ 100 ¦ PRODUCTION ¦ 737466 ¦
¦ 200 ¦ ACCOUNTING ¦ 865403 ¦
¦ 300 ¦ PERSONNEL ¦ 491640 ¦
¦ 400 ¦ ENGINEERING ¦ 604985 ¦
+-------------------------------+

DML(Data Manipulation Language)


DML statements access and modify data available in tables. SELECT and UPDATE operate on
specified columns within the rows, whereas DELETE and INSERT operate on complete rows.

SELECT  Retrieves data.


UPDATE Changes existing values.
DELETE  Removes rows from the table.
INSERT  Adds rows to the table.

The INSERT statement


It adds rows to a table.

INSERT format1:
It assigns values to columns in the order the columns appear in the table.

SYNTAX: INSERT INTO table-name


VALUE (value1, value2, ...)

EX: INSERT INTO EMPLOYEE


VALUES (283721, 'ANNE', 'PATON', 400, '290-4871', '120588', 'F', 37000.00)

EX: Write a command to add a row to the DEPARTMENT table to include the
LEGAL department, number 400.The manager's employee number is 283721.
INSERT INTO DEPARTMENT
VALUES (400, 'LEGAL', 283721);

24
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

INSERT format2:
It has entries in the column list which correspond to entries in the value list.

SYNTAX:
INSERT INTO table-name (column-1, column-2, ...)
VALUE (value1, value2, ...)

EX:
INSERT INTO DEPARTMENT (DEPTNAME, DEPTNO, MANAGER)
VALUES ('LEGAL', 400, 283721);

Multiple rows can be added to a table by copying rows from one table into another. This is
accomplished by using a query to define the set of rows to be inserted into the table.

SYNTAX:
INSERT INTO target-table(column, ...)
SELECT column, ...
FROM source table(s)
WHERE search conditions

Ex: To create a new table called MANAGER which consists of information on employees who
are managers. We could insert information into the table using a query.

INSERT
INTO MANAGER(DEPTNAME,DEPTNO,EMPNO,FNAME,LNAME,WPHONE)
SELECT DEPTNAME,DEPTNO,EMPNO,FNAME,LNAME,WPHONE
FROM DEPARTMENT,EMPLOYEE
WHERE EMPLOYEE.EMPNO = DEPARTMENT.MANAGER

MANAGER
+-------------------------------------------------+
¦ DEPTNAME ¦DEPTNO¦ EMPNO¦FNAME ¦ LNAME ¦ WPHONE ¦
+-----------+------+------+------+-------+--------¦
¦PRODUCTION ¦ 100 ¦737466¦GAIL ¦BAKER ¦290-4112¦
¦ACCOUNTING ¦ 200 ¦865403¦ALBERT¦CHILDS ¦290-4631¦
¦PERSONNEL ¦ 300 ¦911723¦SHARON¦DYLER ¦290-4366¦
¦LEGAL ¦ 400 ¦283721¦ANNE ¦PATON ¦290-4871¦
¦ENGINEERING¦ 500 ¦604985¦JASON ¦JONES ¦290-4128¦
+-------------------------------------------------+

SELECT Statement and its varieties


SELECT statement used to retrieve all or specified columns from a table.

SELECT * FROM EMPLOYEE;  To retrieve all columns from the table


SELECT DEPTNO FROM EMPLOYEE; gives the following table:
+------+
¦DEPTNO¦ +-> Note that duplicate rows
+------¦ ¦ appear in the result
¦ 100 ¦ ------+ ¦ table.
¦ 500 ¦ ¦ ¦
¦ 300 ¦ +----------+ SQL allows us to eliminate
¦ 100 ¦ ------¦ duplicate rows from a table.
¦ 300 ¦ ¦
¦ 100 ¦ ------¦
¦ 200 ¦ ¦
¦ 500 ¦ ¦
¦ 100 ¦ ------+
+------+

25
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SELECT DISTINCT DEPTNO FROM EMPLOYEE;


+------+ We can avoid these duplications
¦DEPTNO¦ by using the DISTINCT keyword.
+------¦
¦ 100 ¦
¦ 200 ¦ <------------------ Now there is only one entry for
¦ 300 ¦ each DEPTNO.
¦ 500 ¦
+------+
SQL provides four arithmetic symbols that can be used in an expression. They are:
+ addition
- subtraction
* multiplication
/ division

SELECT LNAME, SALARY FROM EMPLOYEE;

+------------------------+
¦ LNAME ¦ SALARY ¦
+---------------+--------¦
¦JOHNSON ¦48000.00¦
¦JONES ¦18000.00¦
¦DYLER ¦30000.00¦
¦LEBLANC ¦42000.00¦
¦RYDZIK ¦28000.00¦
¦BAKER ¦38000.00¦
¦SHELDON ¦31000.00¦
¦ZWIRNER ¦26000.00¦
¦MAYR ¦33000.00¦
+------------------------+

The SALARY column lists the annual income for each employee. If we want to know the
monthly income we can use the calculation feature to divide each salary by 12.

SELECT LNAME, SALARY/12 FROM EMP


^
|
+-------------------------+
¦ LNAME ¦SALARY/12¦
+---------------+---------¦
¦JOHNSON ¦ 4000.00 ¦
¦JONES ¦ 1500.00 ¦
¦DYLER ¦ 2500.00 ¦
¦LEBLANC ¦ 3500.00 ¦
¦RYDZIK ¦ 2333.33 ¦
¦BAKER ¦ 3166.67 ¦
¦SHELDON ¦ 2583.33 ¦
¦ZWIRNER ¦ 2166.67 ¦
¦MAYR ¦ 2750.00 ¦
+-------------------------+

The arithmetic expression SALARY/12 is displayed as a new column in the table.


Ex: Write a query that would display the employee number (EMPNO) and SALARY if all
employees were given a 10 % salary increase.

SELECT EMPNO,SALARY * 1.1 FROM EMPLOYEE;

26
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

WHERE CLAUSE

The WHERE clause works as a filter to choose only those rows in a table that satisfy the search
condition.

SELECT column name(s) FROM tablename WHERE .........

For example: If we wanted to list only the employees that are in department 300, from the
employee table
SELECT *
FROM EMPLOYEE WHERE DEPTNO = 300;

+------------------------------------------------------------------------+
¦EMPNO ¦ FNAME ¦ LNAME ¦DEPTNO¦ WPHONE ¦STARTDT¦SEX¦ SALARY ¦
+------+------------+---------------+------+--------+-------+---+--------¦
¦911723¦SHARON ¦DYLER ¦ 300 ¦290-4366¦112179 ¦ F ¦30000.00¦
¦642655¦FRANK ¦RYDZIK ¦ 300 ¦290-4789¦091086 ¦ M ¦28000.00¦
+------------------------------------------------------------------------+

Ex: 1. SELECT EMPNO, LNAME, SEX, SALARY


FROM EMPLOYEE
WHERE SEX = 'F';

Note: when a character string is used in a search condition it is enclosed in single quotes.
+-----------------------------------+
¦EMPNO ¦ LNAME ¦SEX¦ SALARY ¦
+------+---------------+---+--------¦ +----- Only those rows where
¦307117¦JOHNSON ¦ F ¦48000.00¦ ¦ SEX = 'F' are included
¦911723¦DYLER ¦ F ¦30000.00¦ ¦ in the table
¦737466¦BAKER ¦ F ¦38000.00¦ ¦
¦871330¦ZWIRNER ¦ F ¦26000.00¦ ¦
+-----------------------------------+ ¦
| ¦
|--------------+
Ex: 2. Write a query to retrieve all the columns from the EMPLOYEE table for those whose last
name (LNAME) is JONES.
SELECT * FROM EMPLOYEE WHERE LNAME='JONES';

The comparison operators available to use with the WHERE clause as a search condition is:
= equal to
<> or ¬= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
Sometimes you will need to link more than one search condition in a WHERE command.
Multiple search conditions are linked by:
AND - meaning All conditions MUST be met
OR - meaning AT LEAST ONE condition must be met

SELECT EMPNO, LNAME, DEPTNO, SALARY


FROM EMPLOYEE
WHERE DEPTNO = 200
OR DEPTNO = 300
OR DEPTNO = 500;

27
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

List the rows in a table that meet one of several criteria using the OR operator. To achieve the
same result by using the set comparison operator IN.

SELECT EMPNO, LNAME, DEPTNO, SALARY


FROM EMPLOYEE
WHERE DEPTNO IN (200,300,500)

+-------------------------------+
¦EMPNO ¦ LNAME ¦DEPTNO¦ SALARY ¦
+------+--------+------+--------¦ Note that only the department
¦604985¦JONES ¦ 500 ¦18000.00¦ numbers in the list were
¦911723¦DYLER ¦ 300 ¦30000.00¦ selected.
¦642655¦RYDZIK ¦ 300 ¦28000.00¦
¦215012¦SHELDON ¦ 200 ¦31000.00¦
¦871330¦ZWIRNER ¦ 500 ¦26000.00¦
+-------------------------------+

SELECT EMPNO, LNAME, SALARY


FROM EMPLOYEE
WHERE SALARY >= 30000
AND SALARY <= 50000 ;

We can list the rows in a table that fall within a specified range of values by using the AND
operator.
The BETWEEN operator lets us select rows that contain values within a specified range.
BETWEEN has the same effect as using >= AND <=.

SELECT EMPNO, LNAME, SALARY


FROM EMPLOYEE
WHERE SALARY
BETWEEN 30000 AND 50000 ;

+------------------------+
¦EMPNO ¦ LNAME ¦ SALARY ¦
+------+--------+--------¦
¦307117¦JOHNSON ¦48000.00¦
¦911723¦DYLER ¦30000.00¦
¦827611¦LEBLANC ¦42000.00¦
¦737466¦BAKER ¦38000.00¦
¦215012¦SHELDON ¦31000.00¦
¦711674¦MAYR ¦33000.00¦
+------------------------+

Write a query to want all the information on the employees JONES, JOHNSON and DYLER.

SELECT * FROM EMPLOYEE


WHERE LNAME IN ('JONES', 'JOHNSON', 'DYLER');

Another form of selection criteria which is useful is to compare a column with a specific part of a
constant. The SQL operator for this is... LIKE.
The syntax for using LIKE is ...

SELECT ...
FROM ...
WHERE column name
LIKE quoted-string

28
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

A quoted-string may contain any string of characters. Special meanings are reserved for the
characters _ and %. _ (underscore) represents any single character. % represents any string of
zero or more characters.

Ex: In order to list all employees whose name begins with a 'J' from the EMPLOYEE table .
SELECT *
FROM EMPLOYEE
WHERE LNAME
LIKE 'J%' ;

+------------------------------------------------------------------------+
¦EMPNO ¦ FNAME ¦ LNAME ¦DEPTNO¦ WPHONE ¦STARTDT¦SEX¦ SALARY ¦
+------+------------+---------------+------+--------+-------+---+--------¦
¦307117¦MARY ¦JOHNSON ¦ 100 ¦290-4788¦051673 ¦ F ¦48000.00¦
¦604985¦JASON ¦JONES ¦ 500 ¦290-4128¦040988 ¦ M ¦18000.00¦
+------------------------------------------------------------------------+
?
¦
¦ Only rows were selected
+--------------- WHERE LNAME begins with
the letter 'J'.
To retrieve information on an employee but you are uncertain whether his name is SHELDON or
SHELTON
SELECT *
FROM EMPLOYEE
WHERE LNAME
LIKE 'SHEL_ON';

+------------------------------------------------------------------------+
¦EMPNO ¦ FNAME ¦ LNAME ¦DEPTNO¦ WPHONE ¦STARTDT¦SEX¦ SALARY ¦
+------+------------+---------------+------+--------+-------+---+--------¦
¦215012¦GARY ¦SHELDON ¦ 200 ¦290-4631¦020187 ¦ M ¦31000.00¦
+------------------------------------------------------------------------+
?
¦
¦ Only the row where LNAME
+---------- matched the string in the
LIKE clause was retrieved.

ORDER BY CLAUSE
The ORDER BY clause can be used to display information in either ascending (ASC) or
descending (DESC) order. The default is ASC. SQL assumes ASC if you do not specify a value.

Ex .1:
SELECT DEPTNO, EMPNO, LNAME, SALARY/12
FROM EMPLOYEE
WHERE SEX = 'F'
ORDER BY DEPTNO;

+---------------------------------+
¦DEPTNO¦EMPNO ¦ LNAME ¦SALARY/12¦
+------+------+---------+---------¦
¦ 100 ¦737466¦BAKER ¦ 3166.67¦
¦ 100 ¦307117¦JOHNSON ¦ 4000.00¦
¦ 300 ¦911723¦DYLER ¦ 2500.00¦
¦ 500 ¦871330¦ZWIRNER ¦ 2166.67¦
+---------------------------------+
NOTE: SQL assumed ascending order.

29
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Ex .2:
If we had wanted to list the department numbers in descending order the command would be
SELECT DEPTNO, EMPNO, LNAME, SALARY/12
FROM EMPLOYEE
WHERE SEX = 'F'
ORDER BY DEPTNO DESC;

+---------------------------------+ +------------------------+
¦DEPTNO¦EMPNO ¦ LNAME ¦SALARY/12¦ ¦ Note, the department ¦
+------+------+---------+---------¦ +---- ¦ numbers are now listed ¦
¦ 500 ¦871330¦ZWIRNER ¦ 2166.67¦ ¦ ¦ in descending order ¦
¦ 300 ¦911723¦DYLER ¦ 2500.00¦ ¦ +------------------------+
¦ 100 ¦307117¦JOHNSON ¦ 4000.00¦ ¦
¦ 100 ¦737466¦BAKER ¦ 3166.67¦ ¦
+---------------------------------+ ¦
? ¦
+-----------------------------------+

Ex .3:
SELECT DEPTNO, EMPNO, LNAME, SALARY/12
FROM EMPLOYEE
WHERE SEX = 'F'
ORDER BY DEPTNO, LNAME;

Select statement will first order the rows by DEPTNO, then order them alphabetically within each
department. The columns named for ordering must be columns selected.
+---------------------------+
+---------------------------------+ ¦ Notice that DEPTNO is now ¦
¦DEPTNO¦EMPNO ¦ LNAME ¦SALARY/12¦ +----¦ ordered by department ¦
+------+------+---------+---------¦ ¦ ¦ number in ascending order.¦
¦ 100 ¦737466¦BAKER ¦ 3166.67¦ ¦ +---------------------------+
¦ 100 ¦307117¦JOHNSON ¦ 4000.00¦ ¦
¦ 300 ¦911723¦DYLER ¦ 2500.00¦ ¦ +---------------------------+
¦ 500 ¦871330¦ZWIRNER ¦ 2166.67¦ ¦ ¦ The last names are in ¦
+---------------------------------+ +----¦ alphabetical order within ¦
? ? ¦ ¦ each department. ¦
+-----------------------------------+ +---------------------------+

It is possible to use the position of the column in place of its name in an ORDER BY clause.
Whether the name or column number is used the result is the same.
+-------------+ +---------------+
¦ ? ? ¦
¦ SELECT DEPTNO, EMPNO, LNAME, SALARY/12 ¦
¦ FROM EMPLOYEE ¦
¦ WHERE SEX = 'F' ¦
¦ ORDER BY 1, 3 ¦
¦ ? ? ¦
+-----------+ +-----------------------------+

30
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Intersection of Tables
SQL allows you to select data from more than one table. In relational terms, this is called an
intersection of tables.

Ex: To want the name of the department where SHELDON works.


The first step would be to find the department number where SHELDON works from the
EMPLOYEE table.
Results of the first step is this table.
SELECT LNAME,DEPTNO +-----------------+
FROM EMPLOYEE ¦ LNAME ¦DEPTNO¦
WHERE LNAME = 'SHELDOM'; +----------+------¦
¦ SHELDON ¦ 200 ¦
+-----------------+

Next we would place this result (DEPTNO = 200) in a query to find the name of this department.
+--------------------+
SELECT DEPTNO, DEPTNAME ¦DEPTNO¦ DEPTNAME ¦
FROM DEPARTMENT +------+-------------¦
WHERE DEPTNO = 200; ¦ 200 ¦ACCOUNTING ¦
+--------------------+

Using this two-step process to find SHELDON's department name, we are unable to list the
employee name and the department name on the same result table. This problem would be worse
if we wanted to match many employee's names with their department name.

SQL provides us with a JOIN of tables feature to combine information from more than one table
into a single result table. The tables must have a common column of data. The columns need not
have the same name, but they must contain the same type of data.

The general form of a select from two tables is:

SELECT column-names
FROM table1-name, table2-name
WHERE table1-name.column-name = table2-name.column-name;

EX:
SELECT LNAME, DEPTNAME
FROM EMPLOYEE, DEPARTMENT ?---------------------+
WHERE EMPLOYEE.DEPTNO = DEPARTMENT.DEPTNO; ¦
? ? ¦
¦ ¦ Note that the tables to be joined
¦ ¦ are listed in the FROM clause.
¦ ¦
¦ ¦ WHERE specifies the join criteria,
¦ ¦ the common link between the tables.
¦ ¦ The data types in the columns from
+---------------------- the two tables must be the same.

Ex: To make a table that lists all department names along with the last name of the department
manager
SELECT DEPTNAME , LNAME
FROM DEPARTMENT , EMPLOYEE
WHERE DEPARTMENT.MANAGER = EMPLOYEE.EMPNO;

31
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

GROUP OR BUILT IN OR COLUMN FUNCTIONS

To perform calculations using SQL's group functions.


SQL supports the group functions
AVERAGE [AVG]
COUNT
MAXIMUM [MAX]
MINIMUM [MIN]
SUM

They all return a single value for the rows specified in the argument.
SYNTAX:
SELECT group function(column name) The group function goes
? ? in the SELECT statement
+-----------+ and is followed by the
¦ column to which it applies.
¦
+--------------- The column name must be
enclosed in parentheses.

SELECT GROUP FUNCTION1(COLUMN NAME),


GROUP FUNCTION2(COLUMN NAME),
.
.
You can use more than one group function. If you use a group function on one column then for
other columns you must either use a group function or have the columns included in the GROUP
BY clause.
You CANNOT mix a request for individual row values in the same SELECT statement.

The AVERAGE function


• Averages the specified values in the column.
• Column selected MUST contain numeric values.
• Arguments may be preceded by DISTINCT to eliminate duplicate values.
• The syntax for the Average function is :

SELECT AVG(column name)


FROM table

Ex: To find the average salary of all employees from the EMPLOYEE table.

SELECT AVG(SALARY) RESULT


FROM EMPLOYEE ; 32666.67
The result of this query is a table with one row and one column.

Ex: To find the average salary of all employees in DEPTNO 100 from the EMPLOYEE table.
SELECT AVG(SALARY)
FROM EMPLOYEE
WHERE DEPTNO = 100;
The WHERE clause tells SQL to average all values that meet the specified criteria.

32
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

The COUNT function

• Must be followed by the specification DISTINCT or *.


• COUNT(DISTINCT) returns the number of values in the column. No duplicates are counted.
• COUNT(*) counts all rows without eliminating duplicates.

The syntax for the Count function is :


SELECT COUNT(DISTINCT column name) or SELECT COUNT(*)

Ex: To find the number of departments in the EMPLOYEE table.

SELECT COUNT(DISTINCT DEPTNO)


FROM EMPLOYEE ;
The result of this query is 4.

SQL only counts each different value once. There are 4 unique values.
DEPTNO
100 <----
500 <----
300 <----
100
300
100
200 <----
500
100

MAX and MIN functions

• The MAX function returns the largest value in a column.


• The syntax for the MAX function is :
SELECT MAX(column name) FROM table
• The MIN function returns the smallest value in a column.
• The syntax for the MIN function is :
SELECT MIN(column name) FROM table

Ex: To find the minimum salary in the EMPLOYEE table.


SELECT MIN(SALARY)
FROM EMPLOYEE ;
In this case SQL returns the smallest value in the column.

Ex: To find the maximum salary in the EMPLOYEE table.


SELECT MAX(SALARY)
FROM EMPLOYEE ;
In this case SQL returns the Largest value in the column.

The SUM function


• Returns the sum of the values in the column
• Column selected MUST contain numeric value
• Arguments may be preceded by DISTINCT to eliminate duplicate values.
• The syntax for the SUM function is :
SELECT SUM(column name) FROM table

33
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Ex: To get the total salaries in the SALARY column for DEPTNO 100.These are found
in the EMPLOYEE table.

SELECT SUM(SALARY) RESULT


FROM EMPLOYEE ------
WHERE DEPTNO = 100 161000.00

The result is a table with one row and one column that gives the total salary of all employees in
department number 100.

Group functions return a single value for the rows specified. When using group functions in the
SELECT statement you cannot mix a query for individual values with one for group values.
SQL allows us to include an individual value column in the select statement if we are Grouping
on that column.

THIS QUERY IS NOT LEGAL BUT, THIS QUERY IS


------------------------ ------------------
SELECT DEPTNO, AVG(SALARY) SELECT DEPTNO, AVG(SALARY)
FROM EMPLOYEE; FROM EMPLOYEE
GROUP BY DEPTNO;

SELECT ... • MUST SPECIFY A BUILT IN FUNCTION


• MAY SELECT THE COLUMN IN THE GROUP BY CLAUSE

FROM ... • CODE THESE AS USUAL


WHERE ...

GROUP BY ... • MUST FOLLOW FROM AND WHERE AND PRECEDE ORDER BY
• MUST SPECIFY THE COLUMN YOU WANT TO SUMMARIZE
• CAN ONLY BE USED WHEN SELECT SPECIFIES A BUILT-IN FUNCTION.
EX:
SELECT DEPTNO, AVG(SALARY) SELECT DEPTNO, AVG(SALARY)
FROM EMPLOYEE FROM EMPLOYEE
GROUP BY DEPTNO WHERE SEX = 'F'
+------> GROUP BY DEPTNO
¦
THE RESULT OF THIS QUERY ¦ THE RESULT OF THIS QUERY
IS A TABLE THAT GIVES THE ¦ IS A TABLE THAT GIVES THE
AVERAGE SALARY FOR EACH +------- AVERAGE SALARY FOR FEMALES
DEPARTMENT. IN EACH DEPARTMENT.
+---------------+ +---------------+
¦DEPTNO¦ SALARY ¦ ¦DEPTNO¦ SALARY ¦
+------+--------¦ +------+--------¦
¦ 100 ¦40250.00¦ ¦ 100 ¦43000.00¦
¦ 200 ¦31000.00¦ ¦ 300 ¦30000.00¦
¦ 300 ¦29000.00¦ ¦ 500 ¦26000.00¦
¦ 500 ¦22000.00¦ +---------------+
+---------------+
If the command does not contain a WHERE clause the GROUP BY follows the FROM clause.
Otherwise the GROUP BY clause follows the WHERE clause.

Ex: Write a query that returns the number of employees in each DEPTNO from
the EMPLOYEE table.

SELECT DEPTNO, COUNT(*)


FROM EMPLOYEE
GROUP BY DEPTNO;

34
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

GROUP BY can also be followed by a HAVING clause, which is in some ways comparable to a
WHERE clause. The GROUP BY clause returns all groups in the result. Often we are only
interested in groups that meet certain criteria. To see only the groups of interest, you can specify
a search condition in a HAVING clause.
This statement:
• groups rows by department numbers
• performs the AVG group function
• tests each group for inclusion in the result
• returns only those groups that satisfy the condition .

SELECT DEPTNO, AVG(SALARY) SELECT DEPTNO, AVG(SALARY)


FROM EMPLOYEE FROM EMPLOYEE
GROUP BY DEPTNO WHERE SEX = 'F'
HAVING AVG(SALARY) > 30000.00 GROUP BY DEPTNO
HAVING AVG(SALARY) > 30000.00

HAVING determines which WHERE determines which


groups will be individual rows will
included be included

Rules for using a HAVING clause


HAVING can only be used with GROUP BY
HAVING must immediately follow the GROUP BY clause
HAVING can only compare built-in functions, not individual columns
EX:
SELECT DEPTNO, AVG(SALARY)
FROM EMPLOYEE
GROUP BY DEPTNO
HAVING COUNT (*) > 3;

COUNT was not included in the SELECT you can still use it in the HAVING clause.This query
will display the average salary for departments with more that 3 employees.

SUBQUERIES

Sub queries are powerful features of SQL.


Ex: To produce a table containing the last name, department number and salary of female
employees whose SALARY is greater than the average salary of male employees.

The first step is to find the average salary of male employees.


SELECT AVG(SALARY) RESULT
FROM EMPLOYEE ----------
WHERE SEX = 'M' 30400.00

The next step is to use this result by placing it in another query to find out which female
employees have a salary greater than the average salary for male employees.
RESULT
SELECT LNAME, DEPTNO, SALARY +------------------------+
FROM EMPLOYEE ¦ LNAME ¦DEPTNO¦ SALARY ¦
WHERE SEX = 'F' +--------+------+--------¦
AND SALARY > 30400.00; ¦JOHNSON ¦ 100 ¦48000.00¦
¦BAKER ¦ 100 ¦38000.00¦
+------------------------+

35
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Subqueries allow us to combine these two simple queries. The result of the subquery is evaluated
first since it needs the result to process the main query. To achieve the same result with only one
query.
SELECT LNAME, DEPTNO, SALARY
FROM EMPLOYEE
WHERE SEX = 'F'
AND SALARY >
(SELECT AVG(SALARY)
FROM EMPLOYEE
WHERE SEX = 'M');
Ex: Write the subquery required to list all employees who work in the same department as
Johnson.
SELECT LNAME, DEPTNO
FROM EMPLOYEE
WHERE DEPTNO IN
(SELECT DEPTNO
FROM EMPLOYEE
WHERE LNAME = 'JOHNSON')
Rules
Allow you to form complex queries out of several simple queries.
Must be enclosed in parentheses.
Follow the same general format as normal queries
SELECT ...
FROM ...
WHERE ...

May not have an ORDER BY clause.Allows only one column-name in its SELECT clause.
Processes the subquery first and passes the result to the main-query which then computes the
entire answer.Subqueries may contain multiple levels. When using more than one subquery, the
same rules apply and the format is the same.
Ex: To find the manager of the department where Mayr works, these are the steps we would
follow:
SELECT LNAME Result
FROM EMPLOYEE --------
WHERE EMPNO IN BAKER

(SELECT MANAGER Result


FROM DEPARTMENT --------
WHERE DEPTNO IN 737466

(SELECT DEPTNO Result


FROM EMPLOYEE -------
WHERE LNAME = 'MAYR')); 100
First SQL would search the employee table for the department number and pass it to the next
level. Next SQL would use the result to find the employee number of the manager from the
DEPARTMENT table. Finally SQL passes the EMPNO to the main query to find the manager's
name.

36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

JOINS
SELECT * FROM PARTS;

PART PRODNO SUPPLIER


-------------------- ----------- --------------------
WIRE 10 AMCO
GLASS 35 BRADCO
PLASTIC 50 OK_CHEM
MAGNET 10 TURNER
BLADES 250 HOWARTH

SELECT * FROM PRODUCTS;

PRODNO PRODUCT PRICE


----------- -------------------- ----------
250 SAW 22.00
10 ALTERNATOR 55.50
45 PLIERS 75.75
50 RELAY 12.25

INNER JOIN
Two or more tables are joined together using the column having equal values among them.
SELECT A.PART, A.SUPPLIER, A.PRODNO, B.PRODUCT
FROM PARTS A
INNER JOIN PRODUCTS B
ON A.PRODNO = B.PRODNO

PART SUPPLIER PRODNO PRODUCT


-------------------- -------------------- ----------- --------------------
MAGNET TURNER 10 ALTERNATOR
WIRE AMCO 10 ALTERNATOR
PLASTIC OK_CHEM 50 RELAY
BLADES HOWARTH 250 SAW

LEFT OUTER JOIN


The clause LEFT OUTER JOIN includes rows from the table named before it where the values in
the joined columns are not matched by values in the joined columns of the table named after it.

SELECT A.PART, A.SUPPLIER, A.PRODNO, B.PRODUCT


FROM PARTS A
LEFT OUTER JOIN PRODUCTS B
ON A.PRODNO = B.PRODNO

PART SUPPLIER PRODNO PRODUCT


-------------------- -------------------- ----------- --------------------
MAGNET TURNER 10 ALTERNATOR
WIRE AMCO 10 ALTERNATOR
GLASS BRADCO 35 -
PLASTIC OK_CHEM 50 RELAY
BLADES HOWARTH 250 SAW

37
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

RIGHT OUTER JOIN


The clause RIGHT OUTER JOIN includes rows from the table named after it where the values in
the joined columns are not matched by values in the joined columns of the table named before it.

SELECT A.PART, A.SUPPLIER, A.PRODNO, B.PRODUCT


FROM PARTS A
RIGHT OUTER JOIN PRODUCTS B
ON A.PRODNO = B.PRODNO

PART SUPPLIER PRODNO PRODUCT


-------------------- -------------------- ----------- --------------------
MAGNET TURNER 10 ALTERNATOR
WIRE AMCO 10 ALTERNATOR
- - - PLIERS
PLASTIC OK_CHEM 50 RELAY
BLADES HOWARTH 250 SAW

FULL OUTER JOIN


The clause FULL OUTER JOIN includes unmatched rows from both tables. Missing values in a
row of the result table contain nulls.
SELECT A.PART, A.SUPPLIER, A.PRODNO, B.PRODUCT
FROM PARTS A
FULL OUTER JOIN PRODUCTS B
ON A.PRODNO = B.PRODNO

PART SUPPLIER PRODNO PRODUCT


-------------------- -------------------- ----------- --------------------
MAGNET TURNER 10 ALTERNATOR
WIRE AMCO 10 ALTERNATOR
GLASS BRADCO 35 -
- - - PLIERS
PLASTIC OK_CHEM 50 RELAY
BLADES HOWARTH 250 SAW

Union and Union All

Union
This command will allow you to combine result-set of two queries into single output.
It eliminate duplicates and gives unique rows.
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

Union All
This command will allow you to combine result-set of two queries into single output.
It gives duplicates into output and it is much faster than UNION.
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2

38
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Rules to code union/union all


1. Each query must have the same number of columns.
2. Each column must have compatible data types.
3. Column names for the final result set are taken from the first query.
4 .ORDER BY and COMPUTE clauses can only be issued for the overall result set and not
within each individual result set.
5. GROUP BY and HAVING clauses can only be issued for each individual result set and
not for the overall result set

How to combine two queries that has different set of columns


If you don't have the exact same columns in all queries use a default value or a NULL value such
as:
SELECT firstName, lastName, company FROM businessContacts
UNION ALL
SELECT firstName, lastName, NULL FROM nonBusinessContacts

Ex of Union and Union All


SELECT LNAME,DEPTNO LNAME DEPTNO
FROM EMPLOYEE JOHNSON 100
WHERE DEPTNO = '100'; LEBLANC 100
BAKER 100
MAYR 100

SELECT LNAME,DEPTNO LNAME DEPTNO


FROM EMPLOYEE JOHNSON 100
WHERE SALARY > 30000; LEBLANC 100
BAKER 100
SHELDON 200
MAYR 100

SELECT LNAME,DEPTNO LNAME DEPTNO


FROM EMPLOYEE JOHNSON 100
WHERE DEPTNO = '100'; LEBLANC 100
UNION ALL BAKER 100
SELECT LNAME,DEPTNO MAYR 100
FROM EMPLOYEE JOHNSON 100
WHERE SALARY > 30000; LEBLANC 100
BAKER 100
SHELDON 200
MAYR 100

SELECT LNAME,DEPTNO
FROM EMPLOYEE LNAME DEPTNO
WHERE DEPTNO = '100'; BAKER 100
UNION JOHNSON 100
SELECT LNAME,DEPTNO LEBLANC 100
FROM EMPLOYEE MAYR 100
WHERE SALARY > 30000; SHELDON 200

Ex of UNION from different tables


SELECT STUDENT_NAME, MOBILE_NUM SELECT STUDENT_NAME, MOBILE_NUM
FROM JUST_DIAL_ENQ UNION FROM OFFICE_ENQ
WHERE ENQ_DATE >= 20120101 WHERE ENQ_DATE >= 20120101

39
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

The UPDATE Statement


The UPDATE command is used to change the values in existing rows.
The general form is:
UPDATE table-name
SET column-name = newvalue
.
.
WHERE search condition
The set clause tells which columns to update and what values to change them to. To update
multiple columns in each row with a single UPDATE command by listing multiple columns in
the SET clause.
Ex.1:
UPDATE EMPLOYEE
SET SALARY = SALARY + 2000
WHERE EMPNO = 215012;

Ex.2: Write an UPDATE command to record a 10% increase in SALARY for everyone
in DEPTNO 100 in the EMPLOYEE table.

UPDATE EMPLOYEE
SET SALARY = SALARY * 1.1
WHERE DEPTNO = 100;

The DELETE statement


To removes one or more rows from a table a WHERE clause determines which rows are affected.
To delete all rows from a table omit the WHERE clause.

The general form is:


DELETE FROM table name
WHERE search condition

EX: DELETE
FROM EMPLOYEE
WHERE EMPNO = 737654;

EMBEDDED SQL

• Hard-coded into an application program


• cannot be modified during the program’s execution except for changes to the values assigned to
the host variables
• Cursors are used to access set-level data (i.e when a SQL SELECT returns more than 1 row)
The general form is
EXEC SQL
[SQL statements]
END-EXEC.

Embedded SQL statements always begin with EXEC SQL, and end with END-EXEC. There are
two important items in the WORKING STORAGE SECTION of a DB2 application program.

SQL Communications Area (SQLCA)


Declarations for Variables

40
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SQL Communications Area (SQLCA)

An SQLCA is a structure or collection of variables that is updated after each SQL statement
executes. An application program that contains executable SQL statements must provide exactly
one SQLCA.
EXEC SQL INCLUDE SQLCA END-EXEC.
The "INCLUDE SQLCA" command merges the declaration of the SQL communications area
into your application program. This merge occurs when you precompile the application program.

Structure of the SQLCA (for COBOL)


01 SQLCA.
05 SQLCAID PIC X(8).
05 SQLCABC PIC S9(9) COMP.
05 SQLCODE PIC S9(9) COMP.
05 SQLERRM.
.
05 SQLERRD OCCURS 6 TIMES PIC S9(9) COMP.
05 SQLWARN.
10 SQLWARN0 PIC X(1).
10 SQLWARN1 PIC X(1).
.
.
10 SQLWARN7 PIC X(1).

SQLCODE
Each SQL statement is executed, a "return code" is placed in the SQLCODE. The value of
SQLCODE
0 : Successful SQL execution.
Positive Integer: Successful execution but an exceptional condition has occurred.
Negative Integer: An error has occurred, and no data has been moved.

SQLERRM
Whenever an error occurs, you will want to see the error message found in this SQLERRM field.
You should make use of the IBM supplied program, DSNTIAR, to display or record the
SQLERRM information.

SQLERRD(3)
It tells how many rows were modified by an INSERT, DELETE, or UPDATE statement.

SQLWARN
These warning fields are rarely used in most applications.

Declarations for Variables


EXEC SQL
INCLUDE EMPLOYEE
END-EXEC.
To use an "INCLUDE" for table declarations, you must have already generated and stored the
declarations. The tool for doing this is DB2I's DCLGEN.
DCLGEN
• Issued for a single table.
• Prepares the structures of the table in a COBOL copy book.
• The copy book contains a SQL DECLARE TABLE statement along with a working storage host
variable definition for the table

41
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Host Variables
Host variables must be declared in the application program. Host variables in an SQL statement
should have a colon added to its name as the first character.Host variables are used in SQL
statements for two main purposes:
1. The first use of a host variable is to specify a search condition.
MOVE '560983' TO EMPNO.
EXEC SQL
SELECT FNAME, LNAME
INTO :FNAME, :LNAME
FROM EMPLOYEE
WHERE EMPNO = :EMPNO
END-EXEC.
This SELECT uses the host variable :EMPNO, to find the record where :EMPNO='560983'

2. Host variables are used in another way in DB2 application programs. A host variable can be
used as a receiving variable, receiving data from a SELECT.
Ex: In the above SELECT Statement, Once the row has been selected where EMPNO = '560983',
data from the two columns, FNAME and LNAME, is placed into the host variables :FNAME
and :LNAME.

Null indicator

What is NULL
Null indicates an unknown value or value not known at this time.
Null increases business meaning i.e. one can easily write a query to find the null rows.
Ex: If a Bonus field of an employee table is null able, then it is easy to find the employees for
whom the bonus is not decided.
Null takes an extra byte to store the NULL value.
Ex: EMP_EMAIL CHAR(80)
If the employee has an email then it takes 80 bytes but internally it takes 81 bytes
If the employee email is not known at this time then it takes 1 byte internally.
Hexadecimal value of the first character of null is 'FF' and value is '00'.

How to handle null in SPUFI

How to insert Null


INSERT INTO EMPLOYEE (EMPNO,FNAME,DEPTNO,WPHONE,STARTDT,SEX,SALARY)
VALUES('307117',NULL,'JOHNSON ',NULL,'290-4788','1973-05-16','F',48000.00);

How to select all rows with NULL


SELECT * FROM EMPLOYEE
WHERE DEPTNO IS NULL

How to select all rows with NOT NULL


SELECT * FROM EMPLOYEE
WHERE FNAME IS NOT NULL

How to update with NULL


UPDATE EMPLOYEE
SET DEPTNO = NULL
WHERE EMPNO = '604985'

42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

How to handle null in application program

How to select null fields

01 WS-IND PIC S9(4) COMP.

MOVE '307117' TO EMPNO


EXEC SQL
SELECT FNAME
INTO :FNAME :WS-IND
FROM EMPLOYEE
WHERE EMPNO = :EMPNO
END-EXEC

EVALUATE WS-IND
WHEN 0
DISPLAY 'FIRST NAME HAS VALUE'
WHEN -1
DISPLAY 'FIRST NAME HAS VALUE'
WHEN -2
DISPLAY 'FIRST NAME HAS VALUE BUT TRUNCATED BECAUSE HOST VARIABLE IS
SMALLER'
END-EVALUATE
Note: If the null is retrieved and null indicator is not used then it returns SQLCODE -305

How to retrieve null field without using null indicator


MOVE '307117' TO EMPNO
EXEC SQL
SELECT coalesce(FNAME,' ')
INTO :FNAME :WS-IND
FROM EMPLOYEE
WHERE EMPNO = :EMPNO
END-EXEC

How to update null fields

MOVE '604985' TO FNAME


MOVE -1 TO WS-IND

EXEC SQL
UPDATE EMPLOYEE
SET FNAME = :FNAME :WS-IND
WHERE EMPNO = :EMPNO
END-EXEC

Note: If you are trying to update a not null column with a null value then it returns sqlcode -407

VARCHAR

VARCHAR data type is used to save the memory when smaller length of the data is stored in a
field.
CHAR FIELD VARCHAR FILED
Field declaration: EMP_EMAIL CHAR(80) EMAIL_EMAIL VARCHAR(80)
Host variable: 05 EMP-EMAIL PIC X(80). 05 EMP-EMAIL.
49 EMP-EMAIL-LEN PIC S9(4) COMP.
49 EMP-EMAIL-TEXT PIC X(80).

43
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

How to update a varchar field

Here is an example: Read a FILE and update EMP_EMAIL column

FD IN-FILE.
01 IN-REC.
05 IN-EMP-NUM PIC X(4).
05 IN-EMAIL PIC X(80).
01 EMP-TBL.
05 EMP-NUM PIC X(4).
05 EMP-EMAIL.
49 EMP-EMAIL-LEN PIC S9(4) COMP.
49 EMP-EMAIL-TEXT PIC X(80).

01 STOP-LOOP PIC X(1) value 'n'.


01 WS-COUNT PIC S9(4) COMP VALUE zeros.

READ IN-FILE
MOVE 'N' TO STOP-LOOP
PERFORM VARYING WS-COUNT FROM 80 BY -1 UNTIL WS-COUNT < 1
OR STOP-LOOP = 'Y'
IF IN-EMAIL(WS-COUNT:1) > SPACE
MOVE WS-COUNT TO EMP-EMAIL-LEN  It removes trailing spaces and moves
MOVE 'Y' TO STOP-LOOP actual length of the email
END-IF
END-PERFORM
MOVE IN-EMAIL TO EMP-EMAIL-TEXT  Text is moved here
MOVE IN-EMP-NUM to EMP-NUM
EXEC SQL
UPDATE EMP
SET EMP_EMAIL = :EMP-EMAIL  Group field is used here
WHERE EMP_NUM = :EMP-NUM
END-EXEC.

If the actual length of the email is 40 then the column is written with 40 bytes
If the actual length of the email is 80 then the column is written with 80 bytes
Internally, varchar takes two extra bytes to store the length.
If most of the emails are close to the right limit (i.e. 80 characters) then use CHAR instead of
VARCHAR

COMMIT
Commit operates on a unit of recovery after executing this statement
All changes will be done permanently.
Row locks will be released .
Default commit is at program termination.
Cursors are closed except those declares with hold option.
Syntax:
EXEC SQL
COMMIT[WORK]
END-EXEC.

ROLLBACK
A unit of work is undone if any abnormal condition occurs. when the statement is executed
All changes in that unit of work be backed out,
All locks are released and all open cursors are closed.

44
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

When you issue a rollback then the database manager will re-establish the state of the database at
the last completed unit of work.
Rollback will be done either by the program or by the system.
Syntax:
EXEC SQL
ROLLBACK [WORK]
END-EXEC.

CURSORS

What is cursor and when is it used


Cursor is a resultant table of a select query. Cursor is used in the application program when the
Select query is returning more than one row.
In a Select query, When a where condition is used with equal operator on unique column, then it
will return single row. In all other cases it may return multiple rows. Use a singleton query in the
first case and use a cursor in the second case.

What are different steps involved in using CUSORS


There are four steps involved in using CUSORS.
1. Declare cursor  It can be declared either in WS section/Procedure division
2. Open Cursor  It should be coded in Procedure division
3. Fetch Cursor  It should be coded in Procedure division
4. Close Cursor  It should be coded in Procedure division

DECALRE Cursor
It is a declarative statement and it can be declared either working storage section or procedure
division. If it is declared in the procedure division, then declare it before OPEN Cursor statement.
It is recommended to declare in the working storage section.
Syntax Example

EXEC SQL DECLARE Cursorname CURSOR FOR EXEC SQL DECLARE cur1 CURSOR FOR
SELECT col1, col2, col3... SELECT emp_no,emp_name,dept_no,emp_sal
FROM Tablename FROM emp
[WHERE condition] WHERE dept_no = :dept-no
END-EXEC. END-EXEC.

Note: INTO clause is not used in the cursor declaration because cursor is not executed here.

OPEN Cursor
It is an executable statement and it should be declared in procedure division before FETCH
Cursor. Select statement in a cursor is executed here and returns resultant rows into cursor
table(resultant table). Move values to the host variables given in the where condition before the
OPEN cursor statement.
Open cursor generates resultant table but are not returned to host variables of the program.
Syntax Example

Move values to the host variable of MOVE 100 to dept-no


where condition

EXEC SQL OPEN Cursorname EXEC SQL OPEN cur1


END-EXEC END-EXEC

45
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

FETCH Cursor
Rows from resultant table are returned to the host variables in this statement.One FETCH
statement returns one row from resultant table to host variables.
Repeat the FETCH process until end of resultant table.
Syntax Example
PERFORM UNTIL SQLCODE = 100 PERFORM UNTIL SQLCODE = 100
EXEC SQL FETCH Cursorname EXEC SQL FETCH cur1
INTO :col1, INTO :emp-no,
:col2, :emp-name,
:col3, :dept_no,
. :emp-sal
. END-EXEC
END-EXEC IF SQLCODE = 0
END-PERFORM PERFORM PROCESS-PARA
END-IF
END-PERFORM
CLOSE Cursor
Close the cursor after completion of FETCH process. Cursor can be opened again with different
values after CLOSE cursor.
Syntax Example

EXEC SQL CLOSE Cursorname EXEC SQL CLOSE cur1


END-EXEC END-EXEC

Different options in Cursors

1. FOR UPDADTE OF col1, col2.. and WHERE CURRENT OF

FOR UPDATE OF clause is used to update the fetched rows of cursor.


Requirement
Hike the salary of employees by 10% in the department 300 and write ouput file with old
salary and new salary.

EXEC SQL DECLARE cur1 CUROSR FOR


SELECT emp_no, emp_sal
FROM emp
WHERE dept_no = :dept-no
END-EXEC
.
.
MOVE 300 TO dept-no

EXEC SQL
OPEN cur1
END-EXEC

PERFORM UNTIL SQLCODE = 100


EXEC SQL FETCH cur1
INTO :emp-no,
:emp-sal
END-EXEC

IF SQLCODE = 0
MOVE emp-no TO out-emp-no
MOVE emp-salary TO out-old-salary
COMPUTE out-new-salary = emp-salary * 1.1
WRITE out-rec

46
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

EXEC SQL
UPDATE emp
SET emp-sal = emp-sal * 1.1
WHERE CURRENT OF cur1
END-EXEC
END-IF
END-PERFORM

EXEC SQL
CLOSE cur1
END-EXEC

NOTE:
1. FOR UPDATE OF cannot be used when a cursor is declared with JOINS. In that case update
the selected rows with where condition but not WHERE CURRENT OF.

Delete a record which is just fetched


Delete the record which is just fetched with ‘WHERE CURRENT OF’ clause. ’WHERE
CURRENT OF’ clause can also be used in delete statement without declaring ‘FOR UPDATE
OF’ clause in cursor declaration.
Syntax:
EXEC SQL
DELETE FROM tbl1
WHERE CURRENT OF Cur1
END-EXEC

2. WITH HOLD
Cursor will be closed automatically when a commit/rollback is used. When WITH HOLD is
used, cursor will not be closed when Commit/Rollback is used.
EXEC SQL DECLARE cur1 WITH HOLD FOR
SELECT emp_no, emp_sal
FROM emp
WHERE dept_no = :dept-no
END-EXEC

SQLCODES on CURSORS

-500  Fetch or close on a closed cursor that is declared with WITH HOLD option.
-501  Fetch or close on a closed cursor.
-502  Open on opened cursor
-503  A column cannot be updated by using WHERE CURRENT OF clause because FOR
UPDATE OF clause is not coded in the cursor declaration
-504  Opening a cursor but cursor is not declared
Cursor is declared after open statement
-507  Update or delete by using WHERE CURRENT OF clause but cursor is not opened
-508  Update or delete by using WHERE CURRENT OF clause but the fetched row is deleted
by another SQL Statement. Update or delete but prior fetch is not success.
-509  Update or delete by using WHERE CURRENT OF clause but cursor is not declared
on that table.
-510  Update or delete by using WHERE CURRENT OF clause but cursor is declared as
shown below.
1. Declared with FOR FETCH ONLY option.
2. Declared on multiple tables by using joins.
3. Declared on non-updatable views.

47
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

DB2 PROGRAM PREPARATION

+-------------+
¦ Source Code ¦ sourcelib(mem)
+-------------+
¦
(Modified source) +----------------+ (Extracted SQL
¦ DSNHPC ¦ statements)
+--------¦ Pre-Compiler ¦--------+
¦ +----------------+ ¦
¦ ¦
¦ ¦
+-----------+ +-----------+
¦ IGYCRCTL ¦ +---- ¦ DBRMs ¦ (DBRM library that
¦ Compile ¦ ¦ +-----------+ collects members)
+-----------+ ¦ ¦
¦ ¦ +-------------+ (Bind one DBRM mem
+-----------+ ¦ ¦ IKJEFT01 ¦ to one package)
¦ IEWL ¦ ¦ ¦ Bind Package¦
¦ Link Edit ¦ ¦ +-------------+
+-----------+ ¦ ¦
¦ ¦ +-------------+ (Bind packages or
Loadlib(mem) ¦ ¦ IKJEFT01 ¦ DBRM members to
+----¦ Bind Plan ¦ plan)
+-------------+

Steps to execute a COBOL+DB2 program

1. Create Source PDS, Copy library, DBRM Library, Load library


2. Create Table and Index in SPUFI/QMF
3. Create copybook for the table in Copy library from DCLGEN
4. Write a COBOL + DB2 program based on the requirement
a. Define table copybook created in DCLGEN with INCLUDE statement
Ex: Include DCLEMP
b. Define system defined copybook SQLCA
Ex: Include SQLCA
c. Code embedded SQL statements in delimiters
EXEC SQL
Select emp_num, emp_sal into :emp-num, :emp-sal
From EMP Where emp_num = :emp-num
END-EXEC.
5. Prepare COBOL+DB2 program with the below steps
PGM1
Pre-compile

Compile Bind Package

Link edit Bind Plan

Userid.loadlib1 (PGM1) Plan1

48
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

6. Create RUN JCL to execute COBOL+DB2 program


//step1 EXEC PGM=IKJEFT01
//infile dd dsn=file1,disp=shr
//outfile dd dsn=file2,disp(new,catlg,delete)
// unit=sysda,space=(cyl,(10,5),rlse)
// dcb=(recfm=fb,lrecl=100,blksize=0)
//systsin dd *
DSN System(DB2T)
Run Program(PGM1) Plan(PLAN1) Library(userid.loadlib1)
/*
7. Prepare test data into input DB2 tables and input files
Enter data in tables in below methods
a. Execute Insert statement from SPUFI/QMF
b. Edit data from File aid DB2
c. Load data from PS to Table in batch with DSNUTILB
8. Execute RUN JCL and check the results

COBOL+DB2 compile JCL

//OZAXXXPC JOB (99012T),'MADHU PADALA',


// CLASS=A,MSGCLASS=X,REGION=0M,NOTIFY=&SYSUID
//*
//PRECOMP EXEC PGM=DSNHPC,PARM='HOST(IBMCOB),SOURCE'  precompile step
//SYSIN DD DISP=SHR,DSN=OZAXXX.SMF.SRCLIB(PGM1)  Source code
//SYSLIB DD DISP=SHR,DSN=OZAXXX.SMF.DB2.COPYLIB  DCLGEN Copy Library
//DBRMLIB DD DISP=SHR,DSN=OZAXXX.SMF.DBRMLIB(PGM1)  DBRM into DBRM Library
//SYSCIN DD DSN=&&TEMP1,DISP=(MOD,PASS),UNIT=SYSDA,Modified Source
// SPACE=(CYL,(1,1))
//SYSUT1 DD SPACE=(CYL,(1,1),,,ROUND),UNIT=SYSDA
//SYSUT2 DD SPACE=(CYL,(1,1),,,ROUND),UNIT=SYSDA
//SYSPRINT DD SYSOUT=*  Precompile listing
//SYSTERM DD SYSOUT=*
//*
//COMPILE EXEC PGM=IGYCRCTL,PARM='APOST',COND=(4,LT,PRECOMP)  compile step
//STEPLIB DD DSN=IGY.SIGYCOMP,DISP=SHR
//SYSIN DD DSN=&&TEMP1,DISP=(OLD,DELETE) Modified source from PRECOMPILE
//SYSLIB DD DSN=OZAXXX.SMF.COBOL.COPYLIB,DISP=SHR  COBOL Copy Library
//SYSLIN DD DSN=&&TEMP2,UNIT=SYSDA,DISP=(MOD,PASS),  Object code
// SPACE=(CYL,(1,1))
//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSPRINT DD SYSOUT=*  Compile listing
//SYSOUT DD SYSOUT=*
//*
//LKED EXEC PGM=IEWL, PARM='AMODE(31), RMODE=ANY',  Link edit step
// COND=(4,LT,COMPILE)
//SYSLIN DD DSNAME=&&TEMP2,DISP=(OLD,DELETE)  Object code from compile
// DD DDNAME=SYSIN

49
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

//SYSLIB DD DSN=OZAXXX.SMF.LOADLIB,DISP=SHR  Subprogram Load Library


// DD DSN=CEE.SCEELKED,DISP=SHR
// DD DSN=DSN710.SDSNLOAD,DISP=SHR
//SYSLMOD DD DSN=OZAXXX.SMF.LOADLIB(PGM1),DISP=SHR  Load module
//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
NAME PGM1(R)
/*
//*
//BINDPLAN EXEC PGM=IKJEFT01  Bind plan step
//DBRMLIB DD DISP=SHR,DSN=OZAXXX.SMF.DBRMLIB  DBRM Library from PRECOMP
//SYSPRINT DD SYSOUT=*
//SYSTSPRT DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(DSN)
BIND PLAN(PLAN1) -  PLAN
MEMBER(PGM1) -
ACT(REP) -
ISOLATION(CS) -
VALIDATE(BIND) -
EXPLAIN(NO)
END
/*

Run JCL
//OZAXXXRN JOB OZA,OZA,MSGLEVEL=(1,1),
// CLASS=A,MSGCLASS=A,NOTIFY=&SYSUID,REGION=6M
//*
//STEP1 EXEC PGM=IKJEFT01,DYNAMNBR=20
//SYSTSPRT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
//SYSOUT DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(DSN)  DB2 Subsystem name
RUN PROGRAM(PGM1) PLAN(PLAN1) -  Program name and plan name
LIB('OZAXXX.SMF.LOADLIB')  Load library of the program
END
/*

Precompile

Different activities of precompilation


COBOL compiler doesn't know about Sql statements, with this reason cobol db2 program has to
undergo with precompilation. Precompile does the following activities

1. Expands all copybooks declared with include statement


2. Validates table declaration used in the DCLGEN copybook
3. Checks Syntactical errors on SQL statements and also validates the fields
based on table declaration from DCLGEN copybook
4. Extracts all sql statements into DBRM and replaces sql statements with
COBOL Call statements (CALL 'DSNHLI' using..).
COBOL code which is replaced with CALL statements is called modified source

50
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

5. Generates Timestamp for both modified source and DBRM. These are checked
in the run time.
Note: Precompilation can be executed even if DB2 is down.
Table validations are done based on dclgen copybook but not from the DB2 catalog entries.
Note: Supply only Dclgen copybooks in SYSLIB of precompilation step

Compile
It is same as normal COBOL compilation. It takes modified source as input and compiles. Supply
Copy copybooks in this step. Output of this compilation is object module.

Linkedit
This takes object module from compile step and also takes sub program load modules and
generates load module.

Bind
DBRM which is extracted in the precompilation is not an executable. It has to undergo through
BIND process which makes statements executable.

Activities of Bind process


1. Checks SQL statements with the DB2 cataloged entries.
2. Checks authorization of the programmer on the sql statements
3. Gets optimized access path from the statistics of the runstats. It gets best indexed path if the
indexes are built. This improves these SQL performance improvement of bind process in
different evolutions.

1. Bind all DBRM members directly to the PLAN.

Disadvantages
When a new program is to be bound to the existing plan or changes are done in the existing
program which is bound to a plan then BIND PLAN has to be executed. Even though single
elements has to be bound, all elements which were already bound to the plan are bound once
again

2. Bind one DBRM in to a one package and then all packages bind to PLAN

Bind package
Bind package is almost similar to bind plan. Bind package means transferring bind activities
from plan to a package and this package is executed from plan

Improvement in the second evolution


When existing program is impacted then bind that package only. In the run time the plan picks up
the updated package. So, no need to bind other packages which are bound to the plan.

Disadvantage
When a new program is created and this is to be executed with existing plan, then bind this
program to a new package and then bind plan by including this package. So, bind plan is required
when a new program is created.

51
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

3. Bind one DBRM to one package and group packages into a collection.
Bind package with Collection ID. Bind plan with collections. Collection is not a physical object
it is logical name.

Improvement in the third evolution


When a new program is created which is bind with a new package and grouped to existing
collection. Then bind plan is not required. Bind plan is done only one time. As long as packages
are bound to the existing collections Bind plan is not required. When new collections are
introduced then go for bind plan.

Conclusion:
Evolution1
When members directly bound to plan, then if existing member modified or new member is
created then bind the plan.

Evolution2
When packages are directly bound to plan, then if the existing members are modified then it is
required to bind package only. If a new member is created then it is required to bind package and
then bind plan.

Evolution3
When packages are indirectly bound to plan with collection id, then if the existing package is
modified or new package is created to the existing collections then bind package is enough, bind
plan is not required.

How the program preparation done with ENDEVOR

1. Add COBOL-DB2 program to Endevor. Endevor does the following activities.


a) Precompile which creates DBRM member into DBRM library.
b) Compile
c) Linkedit
2. Bind DBRM member to a package with SPUFI or external bind JCL

Bind parameters

Isolation(CS/RR/UR)
CS - Cursor stability
When a row is selected then it applies lock on the page. When it moves the next row which is on
another page then the lock held on first page is released and it is held on second page. When a
row is updated then the page is locked until commit is issued. Most of real applications use this
option. With this more concurrency is achieved.

RR - Repeatable Read
When a row is read then page is locked until the next commit point. All rows that are read are
locked until next commit point. When program wants to read the same record again and again
then that should not be modified another program. When mass updates are required then this
option is used. With this concurrency is reduced.

52
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

UR - Uncommitted read/ Dirty read


It does not hold any locks on the table. It can read the uncommitted rows (Rows that are updated
but not committed). Once after reading the row, then other program can rollback the updates done
on the row. Accessing data is faster but you may get incorrect data. After the record is read

Isolation Examples

Bind Parameters
RR/RS/CS/UR

Select *
From Theater
Where Class = 'F' and
Booked_status = 'N'
Seat_no between 001 and 100
The above query is executed by USER1.Seat numbers 007, 009, 025, 027, 035 are selected for the
above selection

RR  User1 can see 5 records and these are locked by share lock i.e. others can browse the data
in a share lock but they cannot update these. Only User1 can update above 5 records.
If user1 updates any ticket then that record cannot be viewed by other users because it turns into
Exclusive lock. This can be viewed by other user with UR.
Other users can browse other 95 records in share lock i.e. they can read but not update
If User1 executes the same query again and again before commit point but it returns the same
number of records that he got for the first time.

RS  User1 can see 5 records and these are locked by share lock i.e. others can browse the data
in a share lock but they cannot update these. Only User1 can update above 5 records
If user1 updates any ticket then that record cannot be viewed by other users because it turns into
Exclusive lock. This can be viewed by other user with UR.
Other users can edit other 95 records if it is not reducing user1's output. Other users can cancel
the tickets that are already booked.
If User1 executes the same query again and again before commit point then it should return >=5
records but not less than 5

CS  5 records are selected but the record on which the cursor is placed is locked by share lock.
If the record is simply read and moved to the next record then lock is held on second record and
lock release on the first record.
If the record is updated and moved to the next record then lock is held on first record until the
commit point.

UR  User1 can read 5 records even these are locked by other users with CS/RR/RS.
While user1 is looking into these five records; others can also update these records.

Validate (BIND/RUN)
Default -> RUN It Validates db2 objects either bind time or run time. Validate bind time is
always better because it reduces burden at run time. Also if it is at bind time, then it will be done
one time. If it is given at run time then validation will be done for every run.

53
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Action (ADD/Replace)
Default -> REPLACE

ADD
Add member to package or plan. It fails if the members is already bound. Replace It will add
member to package or plan if it is first time otherwise it will replace the existing member.

EXPLAIN (YES/NO)
Default -> NO
It will explain about the access path that is taken into User_Plan if YES is given.

Qualifier
If the qualifier is used for every table then if that qualifier is given in the Qualifier option then it
is not required to code for every table in the program. Actual table name is MNT1.EMP
Qualifier(MNT1) Then you can write in the program like it is shown below
EXEC SQL
Select *
Into :Emp-num,
:Emp-name,
:Emp-sal
From EMP
Where Emp_num = :Emp-num
END-EXEC

If the qualifier is not given in the Bind then you have to use like it is shown below
EXEC SQL
Select *
Into :Emp-num,
:Emp-name,
:Emp-sal
From MNT1.EMP
Where Emp_num = :Emp-num
END-EXEC
Then it is not required to give MNT1

ACQUIRE(USE) RELEASE(COMMIT)
DB2 imposes TABLE or TABLESPACE lock when it executes an SQL statements that
references a table in the table space and it release the acquired lock on COMMIT or
ROLLBACK.This is default option and provides greater concurrency.

Show Bind cards and Run card


________________________________________________________________________
| Bind package | Bind Plan | Run |
| IKJEFT01 | IKJEFT01 | IKJEFT01 |
|_________________________|_______________________|______________________________|
|//SYSTSIN DD * | //SYSTSIN DD * |//SYSTSIN DD * |
| DSN SYSTEM(DB2T) | DSN SYSTEM(DB2T) | DSN SYSTEM(DB2T) |
| BIND PACKAGE(COLL1) - | BIND PLAN(PLAN1) - | RUN PROGRAM(PGM1) - |
| MEMBER(PGM1) - | PKLIST(COLL1.*, - | PLAN(PLAN1) - |
| ACT(REP) - | COLL2.*) - | LIB('TSO.USERID.LOADLIB') |
| ISOLATION(CS) - | ACT(REP) - | |
| VALIDATE(BIND) - | ISOLATION(CS) - | END |
| EXPLAIN(NO) | VALIDATE(BIND) - |/* |
| | EXPLAIN(NO) | |
| END | | |
|/* | END | |
| | /* | |
|_________________________|_______________________|______________________________|

54
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Dynamic Sql

What is dynamic SQL


It is a concept of application program. The SQL statement is prepared and executed in the run
time.

Difference between Static SQL and Dynamic SQL


Static SQL Dynamic SQL
1. Object and action of a query is known 1. Object or action of a query is not known
2. Statement is prepared at the time the 2. Statement is prepared at run time
program is written
3. Syntax checking of statement is done 3. Syntax checking and binding is done at
at precompile time and bound at run time. It is done for every run.
bind time. It is bound one time.
4. It is faster than dynamic sql 4. It is slower than Static SQL
5. It generates sql codes for run time 5. It generates sqlcodes for both compile
errors time errors and run time errors
Ex: Incorrect column name is specified. Ex: Incorrect column name is specified.
This is a compile time error but This is a run time error.
not run time error.
6. It is highly used in applications 6. It is rarely used in real applications

Coding a Dynamic SQL


1. Translate the input data into SQL statement
2. Prepare the SQL statement to execute
3. Execute SQL statement
4. Handle SQL return codes
5. Process the information returned

Translate the input data into SQL statement


1. Declare variable as shown below.
2. Move statement and length in the text and length field as shown.
01 WS-STMT.
05 WS-STMT-LEN PIC S9(04) COMP.
05 WS-STMT-TEXT PIC X(50).

MOVE ‘DELETE FROM EMPLOYEE’ TO WS-STMT-TEXT.


MOVE 50 TO WS-STMT-LEN.

Execute Immediate in a Dynamic SQL


Execute immediate is used when there are no host variables in the SQL statement

01 WS-STMT.
05 WS-STMT-LEN PIC S9(04) COMP.
05 WS-STMT-TEXT PIC X(50).

MOVE ‘DELETE FROM EMPLOYEE’ TO WS-STMT-TEXT.


MOVE 50 TO WS-STMT-LEN.

EXEC SQL
EXECUTE IMMEDIATE :WS-STMT
END-EXEC.

55
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Parameter makers
Host variables cannot be used in statement that is moved to the text field.
Use parameter makers if a host variable is required in the statement as shown below.
Move 'DELETE FROM EMPLOYEE WHERE EMPNO = ?' to WS-STMT-TEXT

Prepare once
EXEC SQL
PREPARE S1 FROM :WS-STMT
END-EXEC.

Execute many times


Read In-file
Move in-empno to WS-EMPNO
EXEC SQL
EXECUTE S1 USING :WS-EMPNO
END-EXEC.

Dynamic SQL for Cursor


1. Declare cursor
2. prepare statement for cursor
3. Open cursor
4. Fetch cursor until sqlcode = 100
5. Close cursor

Declare Cursor
EXEC SQL
DECLARE C1 CURSOR FOR STMT
END-EXEC.

Prepare Statment for curosr


MOVE 'SELECT empno, empsal, deptno FROM EMPLOYEE WHERE deptno = ?'
TO WS-STMT-TEXT
MOVE 50 to WS-STMT-LEN
EXEC SQL
PREPARE STMT FOR :WS-STMT
END-EXEC.

Open Cursor
MOVE '100' to ws-deptno
EXEC SQL
OPEN C1 USING :ws-deptno
END-EXEC.

Fetch cursor
Perform until SQLCODE = 100
EXEC SQL
FETCH C1 INTO :EMPNO, :EMPSAL, :DEPTNO
END-EXEC.
If SQLCODE = 0
Perform Process-para
End-if
End-Perform

Close Cursor
EXEC SQL
CLOSE C1
END-EXEC.

56
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Grant
Grant is used to give the authorizations on a table/view to the other users/group/public.
General syntax:
GRANT ALL ON TABLE table-name/view-name TO USER/GROUP/PUBLIC [WITH GRANT
OPTION]

ALTER
CONTROL
DELETE
INDEX
INSERT
REFERENCES
SELECT
UPDATE (COLUMN)

ALTER grants the following privileges


. Ability to Add/drop/alter a column
. Ability to Add/drop primary key, foreign key
. Ability to Add check/unique constraint
. Ability to Create a trigger

CONTROL grants the following privileges


. Ability to Alter, Control, Delete, Insert, references, select and update to base tables
. Ability to Control, Delete, Insert, Select and update on views
. Ability to execute runstats and reorg
. Ability to grant the above privileges to others

DELETE grants the privilege to delete rows from the table or updatable view
. Ability to delete rows from table and updatable views

INDEX grants the privilege to create index on the table


. Ability to create or drop indexes on the table

INSERT
. Ability to insert rows into table and updatable views

REFERENCES
. Ability to create or drop foreign keys

SELECT
. Ability to select data from the table
. Ability to create view on the table

Update
. Ability to update either all columns or columns specified in Grant option

WITH GRANT OPTION


. Ability for the grantee to grant privileges to others

57
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Examples:

Grant ALL accesses on EMPLOYEE table to single user USER1


GRANT SELECT ON employee TO USER user1

Grant Select access on EMPLOYEE table to single user USER1


GRANT SELECT ON employee TO USER USER1

Grant Select access on EMPLOYEE table to single user USER1 and USER1 can give
select grant to others
GRANT SELECT ON employee TO USER user1 WITH GRANT OPTION

Grant Select access on EMPLOYEE table to all users under group GROUP1
GRANT SELECT ON employee TO GROUP group1

Grant Select and update access on STAFF table to all users under group GROUP1
GRANT SELECT,UPDATE ON TABLE staff TO GROUP group1

Grant insert access on EMPLOYEE table to all users in the system


GRANT INSERT ON TABLE employee TO PUBLIC

Revoke

Revoke is used to take privileges on table/view from users/group/public.


General syntax:
REVOKE ALL ON TABLE table-name/view-name FROM USER/GROUP/PUBLIC

ALTER
CONTROL
DELETE
INDEX
INSERT
REFERENCES
SELECT
UPDATE (COLUMN)

Examples:

Revoke Select access on EMPLOYEE table from user USER1


REVOKE SELECT ON employee FROM USER user1

Revoke Select access on SYSCAT.TABAUTH table from user USER1


REVOKE SELECT ON TABLE SYSCAT.TABAUTH FROM PUBLIC

58
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Trigger

What is a Trigger?
A trigger is a specialized program that is not called directly, but is event-driven.
When a data modification statement, such as an insert or an update, occurs, a trigger is executed,
or “fired”, which may make other database updates or call a stored procedure.
A trigger is not directly called or executed. After being created, it is always executed when its
firing event occurs. DB2 version 5 does not support triggers.

Why Use Triggers?


1. Support data integrity – if a change to one column dictates a change to another, a trigger
ensures they always stay in sync.
2. Simplify scheduling – if an action needs to happen every time a particular column is updated,
the trigger avoids having to schedule it.
3. Support complex business rules – having business rules in the database ensures everyone uses
the same logic to accomplish the same process.

CREATE TRIGGER Sample SQL (DB2)


The following examples show sample SQL code for creating different types of DB2 triggers.

Example 1
Create two triggers that will result in the automatic tracking of the number of employees a
company manages. The triggers will interact with the following tables:

EMPLOYEE table with these columns: ID, NAME, ADDRESS, and POSITION.
COMPANY_STATS table with these columns: NBEMP, NBPRODUCT, and REVENUE.

The first trigger increments the number of employees each time a new person is hired; that is,
each time a new row is inserted into the EMPLOYEE table:
CREATE TRIGGER NEW_HIRED
AFTER INSERT ON EMPLOYEE
FOR EACH ROW MODE DB2SQL
UPDATE COMPANY_STATS SET NBEMP = NBEMP + 1

The second trigger decrements the number of employees each time an employee leaves the
company; that is, each time a row is deleted from the table EMPLOYEE:
CREATE TRIGGER FORMER_EMP
AFTER DELETE ON EMPLOYEE
FOR EACH ROW MODE DB2SQL
UPDATE COMPANY_STATS SET NBEMP = NBEMP - 1

Example 2
Create a trigger that ensures that whenever a parts record is updated, the following check and (if
necessary) action is taken:
If the on-hand quantity is less than 10% of the maximum stocked quantity, then issue a shipping
request ordering the number of items for the affected part to be equal to the maximum stocked
quantity minus the on-hand quantity.
The trigger will interact with the PARTS table with these columns: PARTNO, DESCRIPTION,
ON_HAND, MAX_STOCKED, and PRICE.
ISSUE_SHIP_REQUEST is a user-defined function that sends an order form for additional parts
to the appropriate company.

59
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

CREATE TRIGGER REORDER


AFTER UPDATE OF ON_HAND, MAX_STOCKED ON PARTS
REFERENCING NEW AS N
FOR EACH ROW
WHEN (N.ON_HAND < 0.10 * N.MAX_STOCKED)
BEGIN ATOMIC
VALUES(ISSUE_SHIP_REQUEST(N.MAX_STOCKED - N.ON_HAND, N.PARTNO));
END

Example 3
Create a trigger that will cause an error when an update occurs that would result in a salary
increase greater than ten percent of the current salary.
CREATE TRIGGER RAISE_LIMIT
AFTER UPDATE OF SALARY ON EMPLOYEE
REFERENCING NEW AS N OLD AS O
FOR EACH ROW MODE DB2SQL
WHEN (N.SALARY > 1.1 * O.SALARY)
SIGNAL SQLSTATE '75000' SET MESSAGE_TEXT='Salary increase>10%'

Performance guide lines

1. pre test all your queries in SPUFI/QMF before used in the program
2. Use Qualifies in the bind and Avoid it in the program
3. Code most restrictive predicate first
4. Create index on predicates, Group by columns, orderby columns, join columns
5. Prefer IN clause instead of multiple OR conditions
6. If possible, Use Joins in the place of subquery
7. Go for runstats and rebind after large updates, inserts
8. Don’t use SELECT *. It increases program maintenance when a new field is added and
that is not required in few programs.
9. Do the arithmetic and string manipulation in the query rather than programming language.
10. Avoid Usage of NOT = except in NOT EXITS
11. Use for Fetch only in the cursor declaration, if the rows are not updatable.
12. Use UR in the BIND option for report programs, so that it will not lock any records.
But make sure other update jobs are not running at that time.
13. Use multicolumn index instead of multiple indexes
14. Do not use arithmetic operations in predicate, because it will not use indexes.
15. Minimize number of tables in Join.
16. Use BETWEEN clause instead of >= and <=
17. Use CHAR instead of VARCHAR on small fields
18. Use Where EXISTS (Select 1 from tab) to check the existence of a row.
19. Apply a commits and restart logic on mass update programs.

60
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Explain

When an SQL is executed against or bound to a DB2 database DB2, Optimizer tool defines the
access path used to access the data. This access path is defined according to tables’ statistics
generated by DB2 Runstats tool.
The Explain command details the access path defined by DB2 and allows you to analyze how the
data will be accessed and how you can improve the command’s performance.

Steps required to find the access path


3 steps required to find the access path used for the given SQL statement.
Step1:
• Create a PLAN_TABLE on userid like OZA183.PLAN_TABLE. Here OZA183 is a userid.
• Create this table with 51 columns prior to Version 8 and 58 columns after Version 8.
• Table definition can be copied from the IBM’s Public library site.
• You can also create this table from other users with the below command.
CREATE TABLE User1.PLAN_TABLE AS user2.PLAN_TABLE
• Create table is one time activity and this table can be used for ever to explain access path of
any query.

Step2:
Execute the explain command on your selection command:
EXPLAIN PLAN SET QUERYNO = 1 FOR [your sql statement here];
This command will put the Explain information in the PLAN_TABLE.
Ex: EXPLAIN the access path for the below queries.
EXPLAIN PLAN SET QUERYNO = 1 FOR SELECT * FROM employee WHERE EMP_NO = 10001;
EXPLAIN PLAN SET QUERYNO = 2 FOR SELECT * FROM employee WHERE DEPT_NO = 300;

Step3: Execute select statement on PLAN_TABLE to obtain explain information that is written
in STEP2.
SELECT *
FROM PLAN_TABLE
WHERE
QUERYNO = 1 or 2
ORDER BY TIMESTAMP, QUERYNO, QBLOCKNO, PLANNO, MIXOPSEQ
WITH UR;
QUERYNO should be the same used in the explain command on Step 1.

Step4:
Look at these fields of PLAN_TABLE for important information to understand the access path.
PLANNO – Number of steps necessary to process the query indicated in QBLOCKNO;
METHOD – Indicate joins method used for the step (PLANNO);
ACCESTYPE – Method used to access the table;
MATCHCOLS – Number of index key used for index scan (when ACCESTYPE is I, IN,
M, MX);
ACCESSNAME – Name of the index used for index scan (when ACCESTYPE is I, IN, M, MX);
INDEXONLY – Indicates if the index alone is enough to carry out the step;
PREFETCH – Indicates if data pages can be read in advance by prefetch;

61
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Step5:
Analyze the results using the following tips:
Is data accessed through an index?
ACCESSTYPE:
I – Index
This is the best access after the one-fetch index. It uses the index to retrieve rows.
The number of index columns used for matching is represented in MATCHCOLS.
I1 – One-fetch index access
Is the best access possible as it requires retrieving only one row. However, it applies only to
statement with a MAX or MIN function.
N – Index scan with IN keyword in the predicate.
In the example: T(IC1, IC2, IC3, IC4).
Command: Select * from T where IC1 = 1 AND IC2 (in 1,2,3) AND IC3 > 0 and IC4 = 1.
MATCHCOLS will be 3 and ACCESSTYPE will be N. The IN-List scan will be performed as
three matching index scan: (IC=1, IC2=1, IC3>0), (IC=1, IC2=2, IC3>0) and (IC=1, IC2=3,
IC3>0). If parallelism is supported they will execute in parallel.
MX – Multiple index scan.
More than one index is used to access a table. It is an efficient access path when no single index
is efficient and a combination of index provides efficient access.
R – Table space scan.
This is the worst type of access as the entire table will be searched to process the query.

MATCHCOLS
The number of index columns matched on an index scan.
If it is 0 all index keys and RIDs are read.
If one of the matching predicates is a range there will be no more matching columns. Example for
the index on T(IC1, IC2, IC3, IC4) for the following command the IC3 predicate won’t be used:
Select * from T where IC1=1 and IC2 > 1 and IC3 = 1. The position of the columns in the index
is used to decide that IC3 won’t be used.

INDEXONLY
If the columns needed for a SQL statement can be found in the index DB2 will not access the
table. INDEXONLY performance is very high.

PREFETCH
Prefetching determines in advance if a set of data pages is about to be used and then reads the
entire set into a buffer with a single asynchronous I/O operation.
S – Sequential prefetch: data pages read in advance are accessed sequentially.
Table space scan always uses sequential prefetch.
L – List prefetch: one or more indexes are used to select the RIDs list in advance.
D – Dynamic prefetch: the pages to be accessed will be non sequential.
Blank – Prefetch not expected.

SORTs
They add an extra step to the accessed data.
METHOD=3 – These sorts are used for ORDER BY, GROUP BY, SELECT DISTINCT or
UNION.
SORTC_UNIQUE, SORTC_ORDERBY, SORTC_GROUP_BY – Indicates an extra sort for an
UNIQUE, ORDER BY and GROUP BY clause.

62
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

System Tables

SYSIBM.SYSTABLESPACE
It has tablespace information
Important columns
. NAME -- Name of the tablespace
. STATUS -- It is used to check the status of the tablespace.
A - Available
C - Partitioning index not been created
P - Check pending status
S - Check pending status but scope is less than entire tablespace
. PGSIZE -- It tells either 4K or 32K page size.
. NTABLES -- It tells number of tables craeted in the tablespace
. CREATEDBY -- It tells about creator user id.
. STATSTIME -- It tells about timestamp of the last runstats
. LOCKRULE -- It tells about row, page, table, tablespace lock
A - lock type any
L - Large object
P - Page lock
R - Row lock
S - Tablespace lock
T - Table lock
. SEGSIZE -- It tells about number of pages in each segment.
It is zero for Simple and partitioned tablespace.
. PARTITIONS -- It tells about number of partitions in partitioned tablespace.
It is zero for Simple and segmented tablespace.
. LOG -- Y/N -- It tells about the changes are to be logged or not.
It tells about copy pending status of the tablespace.

SYSIBM.SYSTABLES
It contains one row for each table/view/alias
. NAME -- Name of the table
. TYPE -- Type of the object
T - Table
V - View
X - Auxiliary Table
A - Alias
. CREATOR -- Creator of the object
. DBNAME -- Database name in which this object is created.
. TSNAME -- Tablespace name in which this object is created.
. PARENTS -- Number of parent tables for this table.
. CHILDREN -- Number of child tables on this table.
. STATUS -- Status of the table.
I - Incomplete
X - Table has unique constraint and table definition is complete.
Blank - Table has no unique constraint and table definition is complete.
. CHECKFLAG -- It says about the check constraints
C - Check pending either with referential constraint or table check constraint.
Blank - There are no referential or table check constraints on the table.

63
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

. STATSTIME -- Timestamp of the last runstats on this table.


. TBCREATOR -- It is for an alias and it says creator of the referred table.
. TBNAME -- It is for an alias and it says referred table of the alias.
. CREATEDTS -- Time when the create statement was executed.
. ALTEREDTS -- Time when the alter statement was executed.

SYSIBM.SYSCOLUMNS
It contains a row for every COLUMN of a table/view
. NAME -- Name of the column
. TBNAME -- Name of table on which this column is defined
. TBCREATOR -- Authorization Id of the owner of the table
. COLNO -- Column number of the column in the table
. COLTYPE -- Data type of the column
. LENGTH -- length of the column
. NULLS -- Null or not Null
Y - Null
N - Not Null
. UPDATES -- Whether column can be updated.
Y - Can be updated
N - It cannot be updated for the below reasons
.Column is derived from function or expression
.Column is ROWID data type
.A read only view
. CREATEDTS -- Timestamp when the column was created.
. ALTEREDTS -- Timestamp when the column was updated.
. HIDDEN -- Column can be hidden or not.
P - Partially hidden. This column is hidden from select *
N - not hidden

SYSIBM.SYSRELS
It contains a row for every foreign key of the table
. CREATOR -- Creator of the table that has referential constraint (Child table).
. TBNAME -- Name of the child table that has referential constraint.
. RELNAME -- Referential constraint
. REFTBNAME -- Name of the parent table
. REFTBCREATOR -- Authorization Id of the owner of the parent table
. COLCOUNT -- Number of columns in the foreign key
. DELETERULE -- Delete rule for the referential constraint
A - No action
C - Cascade
N - Set Null
R - Restrict
. TIMESTAMP -- Date and time when the referential constraint was created
. ENFORCED -- Referential integrity is enforced by the system or not
Y - Enforced by the system
N - Not enforced by the system
. CHECKEXISTINGDATA -- Option for checking existing data
I - Immediately check existing data
N - Never check existing data

64
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SYSIBM.SYSINDEXES
It contains a row for every index of a table

. NAME -- Name of the index


. CREATOR -- Authorization ID of the owner of the index
. TBNAME -- Name of the table on which the index is defined
. TBCREATOR -- Authorization ID of the owner of the table
. UNIQUERULE -- whether index is unique
D - Duplicates are allowed
U - Unique
P - Unique and it is primary index
. CLUSTERRATIO -- Percentage of rows that are in the clustering order.
. STATSTIME -- Runstats time.
. INDEXTYPE -- Index type.
2 - Type 2 index
Blank - Type 1 index
D - Data partitioned secondary index

SYSIBM.SYSTABAUTH
It Records the privileges that users hold on tables and views

. GRANTOR -- Authorization id of the grantor


. GRANTEE -- Authorization id of the grantee/Application package/PUBLIC/PUBLIC*
. GRANTEETYPE -- Type of grantee
Blnak - An authorization id
P - An application plan or package. It is a package if COLLID is not blank
. TCREATOR -- Authorization id of the creator
. TTNAME -- Name of the table of view
. UPDATECOLS -- Update cols authorization
Blank - Authorization for all columns
* - Only for few columns. These columns can be seen in SYSIBM.SYSCOLAUTH
. ALTERAUTH -- Whether the GRANTEE can alter the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. DELETEAUTH -- Whether the GRANTEE can delete rrows from the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. INDEXAUTH -- Whether the GRANTEE can create indexes on the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. INSERTAUTH -- Whether the GRANTEE can insert rows into the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option

65
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

. SELECTAUTH -- Whether the GRANTEE can select rows the table or view
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. UPDATEAUTH -- Whether the GRANTEE can update rows of the table or updatable view
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. REFERENCESAUTH -- Whether the GRANTEE can create or drop foreign keys on the
table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. TRIGGERAUTH -- Whether the GRANTEE can create or drop foreign keys on the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. GRANTEDTS -- Time when the GRANT statement was executed

SYSIBM.SYSCHECKS
It contains a row for every check constraint
. TBOWNER -- Authorization id of the owner of the table
. CREATOR -- Authorization id of the creator of the check constraint
. TIMESTAMP -- Time when check constraint is created
. TBNAME -- Name of the table on which the check constraint is defined
. CHECKNAME -- Table check constraint name
. CHECKCONDITION -- Text of the table check constraint

SYSIBM.SYSPLAN
It contains one row for each application plan

. NAME -- Name of the application plan


. CREATOR -- Creator/owner of the application plan
. VALIDATE -- Object validation
B - Bind time
R - Run time
. ISOLATION -- How the tables are isolated from other applications
R - RR (Repeatable read)
T - RS (Read stability)
S - CS (Cursor stability)
U - UR (Uncommitted read)
. AQUIRE -- When resources are aquired
A - At allocation time
U - At first use
. RELEASE -- When resources are released
D - At deallocation time
C - Commit time

66
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

. EXPLAIN -- Explain option specified for the plan


Y - Explain the path info into USERID.PLAN_TABLE
N - No explain
. QUALIFIER -- Qualifier used for the unqualified tables in static sql statements
. BOUNDTS -- Timestamp of last bind
. RELBOUND -- Release when the package was bound or rebound
Blank - Bound Prior to version 7
K - Bound prior on version 7
L - Bound prior on version 8
. BOUNDBY -- Authorization id of last bind

SYSIBM.SYSPACKAGE
It contains a row for every package

. COLLID -- Name of the package collection


. NAME -- Name of the package
. OWNER -- Authorization id of the package
. BINDTIME -- Last bind time
. QUALIFIER -- Same as SYSIBM.SYSPLAN
. VALIDATE -- Same as SYSIBM.SYSPLAN
. ISOLATION -- Same as SYSIBM.SYSPLAN
. RELEASE -- Same as SYSIBM.SYSPLAN
. EXPLAIN -- Same as SYSIBM.SYSPLAN
. QUOTE -- SQL string delimiter for the SQL statements in package
N - Apostrophes
Y - Quotation mark
. COMMA -- Decimal point representation
N - period
Y - Comma
. HOSTLANG -- Host language
B - Assembler
C - OS/VS COBOL
D - C language
F - Fortran
P - PL/I
2 - VS COBOLII or IBM COBOL release 1
3 - IBM COBOL release 2 or subsequent release
. VERSION -- Version Identifier
. RELBOUND -- Same as SYSIBM.SYSPLAN

SYSIBM.SYSDUMMY1
It is used to execute a sql statement where the table reference is required but data is not required.
To achieve the below operations without any user defined tables.
String manipulation
Get system dates
To achieve date conversions
To do Arithmetic operations

67
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SYSIBM.SYSTRIGGER
It contains a row for each trigger
. NAME -- Name of the trigger
. CREATEDBY -- Authorization id of the creator of the trigger
. TBNAME -- Name of the table to which this trigger applies
. TBOWNER -- Qualifier of the name of the table to which this trigger applies
. TRIGTIME -- Time when triggered actions is applied
B - Trigger is applied before the event
A - Trigger is applied after the event
. TRIGEVENT -- Operation that activates the trigger
I - Insert
U - Update
D - Delete
. CREATEDTS -- Time when the trigger is created
. TEXT -- Trigger statement

Db2 Utilities

Unload- Load Utility

Sample Jcl:
//CDSUP3UL JOB (99247T),'unload and load',MSGCLASS=X,
// CLASS=A,REGION=8M,NOTIFY=&SYSUID
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=CEE.SCEERUN,DISP=SHR
//*
//STEP1 EXEC PGM=DSNUTILB,PARM=(DB2P,UTIL1)
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
UNLOAD DATA FROM TABLE QUAL1.ACR HEADER NONE
WHEN (COMPANY_CODE = '001')
NOPAD SHRLEVEL REFERENCE
/*
//SYSREC DD DSN=TSO.DB2P.ACR,  Data extracted into this file
// DISP=(,CATLG,DELETE),
// UNIT=SYSALLDA,SPACE=(CYL,(10,5),RLSE),
// DCB=(RECFM=VB,BLKSIZE=0)
//SYSPUNCH DD DSN=TSO.DB2P.ACR.BCARDS,  Control information used for next
// DISP=(MOD,CATLG,DELETE), load is copied into this file
// UNIT=SYSALLDA,SPACE=(TRK,(1,1),RLSE),
// DCB=(RECFM=FB,BLKSIZE=0,LRECL=80)
//STEP2 EXEC PGM=DSNUTILB,PARM=(DB2T,UTIL1)
//SYSPRINT DD SYSOUT=*
//SYSIN DD DSN=TSO.DB2P.ACR.BCARDS,DISP=SHR  Control information
//* generated in unload
//SYSREC DD DSN=TSO.DB2P.ACR,DISP=SHR  Data file that is extracted
//* from unload

Control information that is stored into TSO.DB2P.ACR.BCARDS is shown below.

LOAD DATA INDD1 SYSREC LOG NO RESUME YES ENFORCE NO


EBCDIC CCSID(01140,00000,00000)
SORTKEYS 4686768
INTO TABLE QUAL1.ACR

68
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

( "COMPANY_CODE"
POSITION( 00001:00003) CHAR(00003)
, "AGENT_ID"
POSITION( 00004:00013) CHAR(00010)
.
.
.
, "SERVICE_DATE"
POSITION( 00314:00323) DATE EXTERNAL
)

Terminate Utility

If any utility is failed in its execution, then it has to be terminated before that table is
used for any operation.
Execute the below command from the option 7 (Commands) of DB2I (DB2 interactive). You can
see active utilities that are running and utilities that are failed.
-DIS UTIL(*)

Sample JCL:
//USER1AB JOB (99247T),'TERMINATE',MSGCLASS=X,CLASS=C
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=CEE.SCEERUN,DISP=SHR
//*
//JS10 EXEC PGM=IKJEFT01
//SYSTSPRT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(DB2T)
-TERM UTILITY(UTIL1)
//*

Repair utility

Sample jcl:
//USERABL JOB (99247T),'Repair jcl',MSGCLASS=X,
// CLASS=C,REGION=8M,NOTIFY=&SYSUID
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
//*
//STEP1 EXEC PGM=DSNUTILB,PARM='DB2T,REPAIR1'
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD DSN=&&TEMP01,DISP=(NEW,DELETE,DELETE),
// SPACE=(16384,(20,20),,,ROUND),UNIT=SYSDA
//SYSREC DD DSN=&&SYSREC,DISP=(NEW,DELETE,DELETE),
// SPACE=(16384,(20,20),,,ROUND),UNIT=SYSDA
//SYSUT1 DD DSN=&&SYSUT1,DISP=(NEW,DELETE,DELETE),
// SPACE=(16384,(20,20),,,ROUND),UNIT=SYSDA

//SORTOUT DD DSN=&&SORTOUT,DISP=(NEW,DELETE,DELETE),
// SPACE=(16384,(20,20),,,ROUND),UNIT=SYSDA
//SYSIN DD *
REPAIR SET TABLESPACE dbname.tsname NOCHECKPEND/NOCOPYPEND
/*

69
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Reorg utility

Reorg command in DSNUTILB is recommended after the reorg recommended alter statement.
Otherwise the table cannot be used for any SQL operations.

Sample JCL:
//USER1AB JOB (99247T),'REORG',MSGCLASS=X,CLASS=C
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=CEE.SCEERUN,DISP=SHR
//*
//RUNST1 EXEC PGM=DSNUTILB,PARM=(DB2T,UTIL1)
//*
//SYSPRINT DD SYSOUT=*
//UTPRINT DD SYSOUT=*
//SYSIN DD *
REORG TABLE table_owner.table_name
/*

Runstats Utility

It is recommended to run the RUNSTATS command:


1. After large number of updates
2. After significant inserts/deletes have been made
3. After tables have been reorganized
4. After new indexes have been created
5. Before binding programs whose performance critical

Sample Jcl:
//TABCSPL1 JOB (99247M),'PPLUS SPECIAL JOB 0',MSGCLASS=X,CLASS=C
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=CEE.SCEERUN,DISP=SHR
//*
//RUNST1 EXEC PGM=DSNUTILB,PARM=(DB2T,UTIL1)
//*
//SYSPRINT DD SYSOUT=*
//UTPRINT DD SYSOUT=*
//SYSIN DD *
RUNSTATS TABLESPACE ( QUAL1.TSACR ) TABLE( QUAL1.ACR )
INDEX(ALL) UPDATE (ALL) HISTORY (ALL)
/*

Tables that are updated with UPDATE and HISTORY options


SYSTABLESPACE
SYSTABLEPART1
SYSTABLEPART_HIST1
SYSTABLES1
SYSTABLES_HIST1
SYSTABSTATS1,2
SYSTABSTATS_HIST1,2
SYSLOBSTATS3
SYSLOBSTATS_HIST3

70
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

INTEGRITY

Integrity consists of a set of rules used in DB2 to provide accuracy, validity or correctness of data
in database. Maintaining integrity is not an easy task in a multi user environment. So the task of
maintaining integrity is handled by the system than the user.
There are two general integrity rules in db2 for maintaining data integrity.

Entity integrity:
DB2 supports Entity integrity rule by enforcing the programmer to make the column declaration
of the primary key not null. If the primary key is composite then all the columns in that composite
key should be declared as not null.

Referential integrity:
It ensures the data integrity between the tables related by primary(parent) and foreign(child) keys.

INSERT rule
The insert rule is automatic and not explicitly specifiable on the foreign key declaration.
The rule states that Any row inserted into a dependent table must have its foreign key value as
either a NULL or, equal to the value of a primary key in the parent table that it references.

DELETE rule
This rule is explicitly specified for each foreign key in a table. The DELETE rule states the
requirements to be met when a row in a parent table is deleted. Each foreign key is associated
with its own DELETE rule. All applicable DELETE rules are used to determine whether or not a
delete is done.

RESTRICT option A row of a parent table cannot be deleted if rows exist in the dependent
table(s) with foreign key values equal to the primary key value of this row.

CASCADE option If a row of a parent table is deleted, then: all rows in the dependent table(s)
with foreign key values equal to the primary key value of this row will also be deleted. The delete
will also impact the dependents of the dependent table(s).

SET NULL option If a row of a parent table is deleted then all rows in the dependent table with a
foreign key value equal to the primary key value of this row will have its foreign key value
changed to NULL.

UPDATE rule
The UPDATE rule is automatic and not explicitly specifiable on a foreign key declaration.
This rule states the requirements to be met when the foreign key value of a row in a dependent
table is updated. It can be updated to a value that is NULL or to the value of a primary key in the
parent table that it references. ... primary key value of a row in a parent table is updated. The
primary key value of a row of a parent table cannot be updated if rows in the dependent table(s)
exist with foreign key values equal to the primary key value of this row.

71
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Concurrency

DB2 is a shared system, that is a system that allows any number of users to access the same
database at the same time. Any such system requires some kind of concurrency control
mechanism to ensure that concurrent transactions do not interfere with each other operation. The
absence of such a mechanism will lead to errors and inconsistencies in data

DB2 uses locks to control access to same database by multiple users. The basic idea of locking is
simple, when a transaction needs an assurance that some object that is interested in, will not
change in some unpredictable manner by another user. An exclusive lock on the object will
provide this assurance. The effect of the lock is to lock other transactions out of the object, and
thereby to prevent them from changing it. The first transaction is thus able to carry out its
processing in the certain knowledge that the object in question will remain in a stable state for as
long as the transaction wishes to.

If a transaction requests a lock that is not currently available, then the transaction simply waits
until it gets it. In practice the installation can specify a maximum wait time; If a transaction ever
reaches that threshold in waiting for a lock, it times out and the lock request is failed.

Locking Strategy
DB2 allows multiple users to access same object at same time, but they are controlled by locks.
DB2 selects appropriate locking mechanism based on concurrency control requirements inherent
in the application program. They are called implicit locks.
In addition to the implicit locking mechanism, DB2 provides certain explicit facilities.

These explicit facilities are


LOCKSIZE parameter of CREATE TABLESPACE statement.
ISOLATION parameter
ACQUIRE / RELEASE parameter
SQL statement LOCKTABLE.

Lock table statement can be coded in the application program to acquire an explicit lock on an
object on behalf of the application program. Other parameters are explained in the following
pages.
Example
LOCK TABLE SP IN EXCLUSIVE MODE;

LOCK SIZES AND TYPES


The size (scope) of a lock on data in a table describes the amount of data controlled.
The size is specified in the locksize parameter of create tablespace statement.
Locksize Tablespace:
This means that all locks acquired on data in the tablespace will be at the table space level.
Locksize Table:
This means that locks acquired on data in the table space will be at the table level.
Locksize Page:
This means that locks acquired on data in the table space will be at the table level.
Locksize Row:
This means that locks acquired on data in the table space will be at the row level.
Locksize Any:
This means that db2 will decide the appropriate physical unit of locking for the tablespace.

72
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Db2 always requires a Table or Tablespace lock before access to data is permitted.
Db2 may use Table or Tablespace lock alone to access data according to the locksize parameter.
If the locking strategy includes Row or Page locking then db2 locks Table or Tablespace before
locking Row or Page.

Modes of Table and Tablespace Locks

IS (Intent Share): The lock owner can read any data in the table if an ‘S’ lock can be obtained on
the target row or page.

IX (Intent Exclusive): The lock owner can read or change any data in the table provided an
‘X’ lock can be obtained on rows or pages to be changed and a ‘U’ or ‘S’ lock can be obtained on
rows to be read.

SIX (Share with Exclusive) : The lock owner can read any data in the table and change rows in
the table provides it can be obtain an ‘X’ lock on the target row or page for change .Row locks
are not obtained for reading.

S (Share): The lock owner can read any data in the table and will not obtain roe or table locks.

U (Update): The lock owner can read any data in the table and may changed data if an ‘X’ lock
on the table can be obtained .No row or page locks are obtained.
X (Exclusive): The lock owner can read or update any data in the table .Row locks are not
obtained.

Modes of Row and Page Locking

S (Share): The row is being read by only one application and is available for read only by other
applications.

U (Update): The row is being read by one application but is possibly to be changed by that
application. The row is available for read only by other applications.

X (Exclusive): The row is being changed by one application and is not available for other
application.
Row level locks are only requested by applications that have supporting locks at the table level.

73
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SQL CODES

-007 SQL statement contains illegal char


-029 An into class is required
-060 The specified data type has invalid length
-101 The SQL Statement exceeds an established DB2 limit.
too many tables or too many bytes in the statement
-118 Table or view is illegally named in both the data modification and from clause

-180 Syntax for string representation of a date or time is invalid


-181 String representation of date or time value is invalid
-182 The date or time value in an arithmetic expression is invaid
-183 the result of the arithmetic expression returns a date or time value i.e. not in
the range of values

-204 The object name is undefined


-206 The column name not found in a table given in from clause

-301 The host variable data type is invalid


-305 Null indicator variable is missing and the field returns null value

-501 A cursor must be opened before attempting to fetch from it or close it


-502 Trying to open a cursor which is already opened
-509 You cannot update from a different table than the one specified on the cursor
referred by the where current of clause
-530 Invalid foreign key value was specified for the constraint name
-531 A primary key value cannot be updated if foreign key currently exists that
reference that value
-532 The deletion violates the named referential constraint
-551 The user is attempting to perform an operation on the specified object for
which the user is not authorized or the table does not exist

-803 Primary key violation. Insert or update


-805 Program not found in the plan
-811 A cursor is not defined but the SQL is returning more than one row
-818 Timestamp mismatch

-904 The specified resource is unavailable


-911 The current unit of work has been rolled back
-913 The execution is unsuccessful due to a deadlock or time out
-922 A connection authorization failure an attempt was made to access DB2 from
TSO, CICS. So the connection attachment facility is inactive
-923 A connection was not established because the DB2 was unavailable

74
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

CICS
By Madhu Padala

1
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

2
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

INTRODUCTION TO CICS/VS
Batch processing
1. Data is batched together before processing.
2. Data is sequential from disk or tape.
3. Master file can only be used by one program at any given time.
4. Output consists of intermediate processed files, printed reports or updated master files.
5. Job is scheduled, and output is available in hours or days.
6. More data is processed which is fed from another batch or online system.
7. More validations and more processing logics are used.

Batch Example:
A Payroll Application Program is usually a Batch program.
1. At the end of a pay period, the hours (data) are submitted and grouped.
2. The data is organized sequentially to match the master file.
3. At a scheduled time, the data is processed and the master file is updated.
4. Output is received in the form of paychecks and printed reports to payroll department.

On-Line processing
1. Data is entered individually, in any order.
2. Transactions are initiated from the terminal.
3. Information is always current.
4. Output is displayed on the terminal.
5. Turnaround time is measured in seconds.
6. Less number of processing logics applied.
7. More validations are done on each field to reduce errors in the batch process.

On-line Example:
An automatic bank teller program is an example of on-line application.
1. Transactions are entered by customer at the banking machine.
2. Account balance is updated immediately after transaction.
3. Transactions are processed by computer in a few seconds.
4. Output is received at the banking machine.

Summary of Batch and On-line Systems


Batch On-line

Input Sequential: submitted as group, then Random, unrelated, edited


edited and verified immediately
Processing Sequential master file updating file Random, many users can access a
used by only one program at a time file at one time
Output Usually printed reports Displayed on terminal
updated files
Sequence of Read transaction, read master, Transactions processed as they occur
Operation process the data
Response Time Could be scheduled to be hours or Seconds or minutes
days
Example Monthly Bank Statements Order-entry system
Airline Reservation Systems

3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Advantages of the Online system


These days, the online system is so common that virtually every large mainframe installation has at least
on online application system. This is because the online system has advantages over the batch systems.
• Up-to-date file (information) can be shared among many users simultaneously and instantly.
• Data validation and editing can be done at the data entry time
Advantages of the Batch System
On the other hand, in spite of the ever-increasing popularity of the online system, the batch system has not
died out, and it still contributes to the large portion of data processing requirements. This is because the
batch system has advantage over the online system. Some of the advantages of the batch system are as
follows:
Certain information does not have to be updated or displayed on a real-time base. Users can wait until the
next day, the end of a week, or the end of a month. In this case, the batch system is sufficient for the
purpose If massive file updates or lengthy calculations are involved, the batch system should be used
because the online processing in these areas tends to be very costly in terms of resource consumption.

Loan process for Online vs Batch

Different phases of Loan process


Online 1. Fill a loan application form and validate
Batch 2. Verification
Send a request CEBIL and get response
Batch 3. Issue
Update of database with loan
Transfer of amount to account
Commission calculation
Insurance policy on loan
Reports
Confirmations to loan holder
Update EMI details for collection
Batch 4. Reject
Write all rejects into a file
Generate report on rejected loans
Send a reject letter to loan applicants
Online 5. Reject/Pending
Reject loans information can be seen in online
Updates can be done on pending loans to make it process
Online 6. Loan Inquiry
Entire loan database can be verified
Batch 7. Normal EMI process
Generate EMI on its due date and collect amount from same bank or other banks
Update database with EMI info
Generate EMI reports
Online 8. Track a failed EMI's then collect manually and insert these EMI's into online
Batch 9. Process these manually collected EMI's in a batch process
Online&Batch 10. Adjustments of int rates, partial pre closure, Full pre closure process
Batch 11. Normal closure process

4
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

CICS Activities
Primary data entry is done through online.
Examples:
Data entry
. Enters policy/account/loan application data
. Enter premium payment details
. Online reservations. Railway/airways
. Online trading
Stocks, Mutual funds
. Order booking on retail marketing
. Update payment / withdrawls on account master at bank
. Adjustment of late payments on credit or debit cards
. Cheque book requisitions
. Enter cheque info for transfers

Data Inquiry
. Credit balance, next payment details, last transaction inquiry
. New products inquiry
. Account info verification
. Online statements
. Account details/policy details/agents earnings

Data correction
. Correction on errored transactions
. Reversal of incorrect data entry

Steps required to execute CICS program

1. Create the below libraries


a. Source library  To Create BMS maps and COBOL+CICS programs
b. Copy library  To Create copybooks for files
To create DCLGEN Copybooks for DB2 tables
To route symbolic map(Copybook) from MAP compilation
c. Load Library  To create load module of BMS map(physical map)
To create load module of COBOL+CICS

2. BMS MAP design, coding and preparation


a. Design a map according to your requirement
b. Code the map in BMS assembler macros
c. Compile BMS map twice.
On the first compile to generate symbolic map (copybook). This is copied in COBOL+CICS
program to send and receive map fields from/into application program.
On the second compile to generate Physical map (Load module). This is registered into PPT table.

3. Write a COBOL+CICS program and prepare it.


a. Write a COBOL program with embedded CICS commands based on your requirement.
b. Copy symbolic maps and file copybooks

5
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

c. Compile COBOL+CICS program


Step1. Translate  Checks the syntax errors in CICS commands
DFHECP1$ Comments CICS commands and replaces them with COBOL CALL statements
Step2. Compile  Expands copybooks from the copy library given in SYSLIB
IGYCRCTL Checks syntax errors in the COBOL declaration and verbs
Generates object code
Step3. Linkedit  Checks and Expands sub-program load module from load library given in
IEWL SYSLIB Generates load module into Load library given in SYSLMOD

4. Create a file and load test data.


5. Register maps, programs, files and transaction in CICS system tables
Login to CICS , Clear screen and do the below activities.
CEDA DEF MAPSET(MAP1S) GROUP(G1)
CEDA INS MAPSET(MAP1S) GROUP(G1)

CEDA DEF PROGRAM(PGM1) GROUP(G1)


CEDA INS PROGRAM(PGM1) GROUP(G1)

CEDA DEF TRANS(TRX1) PROGRAM(PGM1) GROUP(G1)


CEDA INS TRANS(TRX1) GROUP(G1)

CEDA DEF FILE(FILE1) GROUP(G1)  Fill DSN with dataset name


CEDA INS FILE(FILE1) GROUP(G1)
CEMT SET FILE(FILE1)  To open and close file
To change default open mode
6. Execute program by entering Transaction ID
Login to CICS
Clear Screen
Enter Transid in the left corner of the screen and then enter

7. Debugging CICS program (Only CICS Commands)


Clear Screen
Enter CEDF and enter
Clear Screen
Enter Transid and enter

8. Execute a single command to check syntax errors


Clear Screen
CECI Command and enter

What to do when a map or program is modified


Method1:
CEDA INS MAPSET(MAP1S) G(G1)
CEDA INS PROGRAM(PGM1) G(G1)
Method2:
CEMT SET PROGRAM(MAP1S) NEWC  Specify Mapname in program entry
CEMT SET PROGRAM(PGM1) NEWC

How to take different test data in the file


Close the file in CICS with CEMT and edit data in TSO.

6
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

CICS concepts

What is CICS?
CICS is a subsystem executing under the MVS address space. It acts as an interface between the
application programs and the operating system and other system components such as the DB2 database
subsystem.
CICS provides the required command interfaces for an application program with the Operating System,
Database system and for Communication requirements.
CICS consists of a core portion known as the CICS nucleus. The CICS nucleus consists of a set of CICS
control programs for providing the required services such as data management, data handling, system
services, etc. This control programs work in tandem with the set of data available in user supplied CICS
Control tables. The system programmer maintains the CICS tables.
These control programs and tables control program execution. At start-up of CICS, these tables are loaded
into memory.
Each application program requires entries in one or more CICS tables depending on the application
requirement.

CICS CONTROL PROGRAMS AND TABLES

CICS CONTROL PROGRAMS (IBM SUPPLIED)

• FCP (FILE CONTROL PROGRAM)


• JCP (JOURNAL CONTROL PROGRAM)
• KCP (TASK CONTROL PROGRAM)
• PCP (PROGRAM CONTROL PROGRAM)
• SCP (STORAGE CONTROL PROGRAM)
• TCP (TERMINAL CONTROL PROGRAM)
• TDP (TRANSIENT DATA PROGRAM)
• TSP (TEMPORARY STORAGE PROGRAM)

CICS CONTROL TABLES (USER SPECIFIED)


Terminal Control Table (TCT):
All the terminals that are authorized to execute CICS transactions should have the entry in this table. The
CICS transactions are not executed through the terminals that don’t have the entry in this table.

Program Control Table (PCT):


The entire Trans id should have entry in this table. In this table the Trans id can be attached to a function
Keys. This is one way of initiating the transaction.

Program Processing Table (PPT):


The language environment about a tans id entered in this table. All the Sub programs should have the
entry in this table. This table also contains the information that a particular load module is in Real
memory or not. If the load module is not in the real memory at the time of execution of TRANSID, the
program load module will be copied not real memory by the storage control program.

File Control Table (FCT):


Manages all the I/O operations of files under CICS. All the files used by the application program should
be registered in FCT.

7
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Resource Control Table (RCT):


All the plan ids that are used to retrieve the data from Db2 database should have the entry in this table. It
also contains the information about how many users can connect concurrently with the database.

Destination Control Table (DCT):


Manages I/O operations of a transient Data Queue (TDQ).

Temporary Storage Table (TST):


Manages I/O operations on a Temporary Storage Queue (TSQ).

Journal Control Table (JCT):


Performs logging of data onto external files called Journals. System log file and other user journal files
should be registered in JCT.

CICS Users
1. Data entry operators
2. Customer care team
3. Business user’s team
4. Data correction team
5. Developer, SIT, UAT testers to place test transactions

CICS Startup
• CICS is submitted as a batch job.
• CICS System Initialization program (SIP) is the main job step
• SIP loads System Initialization Table (SIT)
• SIP further loads all control programs and tables
- Perform initial housekeeping tasks

CICS Shutdown
• Master terminal transaction is entered with shutdown option.
• CICS job produces various logs,statistics,dumps and other reports and ends.
• No transaction can be executed after that

CICS Timings

Region CICS UP CICS DOWN

PROD 6.00 AM 5.30 PM


UAT 6.00 AM 5.30 PM
SIT 2.00 PM 11.00 AM
TEST DEVELOPER Can UP DEVELOPER Can DOWN

Transaction
A unit of work that is done as an atomic operation - that is, the operation succeeds or fails as a whole. In
CICS, a transaction is identified by a 4 character ID, for e.g. TXN1 and is initiated, usually, by typing the
transaction id in the top left-hand corner of a blank screen. A transaction may take several tasks to
complete it. A simple update transaction may take several tasks for validations. Transaction is to update a
record in a file but terminal user may enter incorrect data and then program validates sends error message
to the screen. Each time terminal users corrects the data, a new task is generated. So this update
transaction may complete in several tasks.

8
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Task
Task is an instance of the execution of a particular transaction. Task is a logical unit of work. In pseudo
conversation task starts with procedure division and ends with RETURN TRANSID or RETURN
commands. A transaction from a terminal completes with multiple tasks. The same transaction can be
executed from 100 terminals, in this case 100 tasks are created at the same time in the main memory.
Each terminal user may execute that transaction in several tasks.

Multitasking
Multitasking means the OS allows more than one task to be executed concurrently, regardless of whether
the task uses the same program or different programs.

Multithreading
Multithreading is the system environment where the tasks are sharing the same program under the
multitasking environment. Multithreading is the subset of Multitasking, since it concerns tasks, which use
the same program. Under 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.
Therefore it requires special considerations such as reentrancy or serial reusability.

Reentrancy
A reentrant program is a program, which does not modify itself so that it can reenter to itself and continue
processing after an interruption by the OS, which during the interruption executes other OS tasks
including OS tasks of the same program. It is called reenter able program or serially reusable program.
Quasi-Reentrancy
Under CICS reentrancy is called Quasi-Reentrancy.

Conversation and Pseudo conversation

Conversation
In this method the user and Computer exchanges the information with a series of requests and answers.
During the Requests the system waits for the user response. So the computer resources are wasted.

9
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Pseudo conversation
In this method the instead of waiting for the user response the control will be sent to honor other tasks. So
in this technique the computer resources are used optimally. Pseudo conversational programs are more
efficient than other methods but involve a bit of programming.

1. Like a conversational program, you enter a TRANSID to begin.


2. The program checks to see if EIBCALEN = 0. This indicates that no data was passed from
"last time" since this is the first time the transaction is being executed.
3. The first time through, we SEND a map to the terminal.
4. The SEND MAP command is always followed by the RETURN command.
5. The terminal waits for input from the user. Press Space Bar.
6. As soon as input is entered the TRANSID executes the program again.
7. The program checks the EIBCALEN again. This time the program will take a different path
since a Communication area was defined by the last RETURN command.
8. The map is read into the program with the RECEIVE MAP command.
9. The input is processed.
10. The program sends the output to the terminal.
11. The RETURN command defines the COMMAREA and LENGTH and releases the program.
12. The terminal waits for input from the user.
13. Entering input starts the program again. It will repeat the path for each subsequent time until
data directing the program to terminate is entered.

Initiation of CICS Transaction


• A transaction identifier and data are entered in a terminal.
• TCP with TCT recognizes incoming data from the terminal.
• SCP (storage Control Program) acquires the storage for the Terminal Input-Output Area (TIOA)
• TCP (Terminal Control Program) places the data from the terminal into TIOA and sets the
pointer into the TCT (Terminal control Table) entry of the terminal.
• TCP (Terminal Control Program) passes control to KCP (Task Control Program), which realizes
the transaction identifier in the data in TIOA.

10
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

• SCP (Storage Control Program) acquires the storage for the Task Control Area (TCA), in which
KCP Prepares control data for this task.
• KCP through PCT tries to find the application program associated with the transaction.
• If PPT entry of the application program does not show the resident address of the program, KCP
passes control to PCP, which fetches the application program from the load library and places it
into the main storage.
• KCP passes control to the application program. The application program starts its processing.
The transaction has been initiated.

How can you start a CICS transaction other than by keying the transaction id at the terminal?
By coding an EXEC CICS START in the application program.
By coding the TRANSID and a trigger level on the DCT table.
By coding the TRANSID in the EXEC CICS RETURN command.
By associating an attention key with the PROGRAM CONTROL TABLE.
By embedding the TRANSID in the first four positions of a screen sent to the terminal.
By using the PROGRAM LIST TABLE.

Application Programming
CICS supports all major IBM product lines. The internals of these versions may be distinct but the
application-programming interface (API) is same for all of them. So the program developed in one
version is portable across many IBM hardware products.
In this section we will discuss the following:
• Programming languages supported
• The CICS command format
• The argument values to be passed to the CICS commands
• The EIB Block
• The response code after each CICS command
• How to transfer data between successive transactions
• How to code CICS Commands
• The structure of a CICS application program
• The programming language requirements (constraints)
• Steps to develop, prepare, sign on/signoff to CICS and execute a CICS transaction

CICS supports the host languages - COBOL, C, PL/1 and Assembler. In this, COBOL will be used as the
primary programming language. CICS commands can be embedded within a COBOL application
program.
Every CICS command must start with the keyword “EXEC CICS” and end with a delimiter. The
delimiter for COBOL is “END-EXEC”. For C and PL/I it is a semi-colon (“;”).
The ‘function’ is the CICS service requested. The ‘option’ is one of the options available/applicable for
the function requested. For example, for reading a file, a file name is to be given. The ‘argument value’
determines the characteristics of the value to be placed for the option.
The response of the CICS command execution will be made available by CICS in the argument value
associated with the key word “RESP”. The argument value for RESP option is of data type half word
binary, i.e., S9 (4) COMP. The response is also stored in a special variable called EIBRESP.

The arguments to the CICS command options can be one of the following:
Data Value:
• Constants are also permitted, for e.g., LENGTH (10). For alphanumeric constants, the value must be
contained within quotes.

11
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Data area: A Valid COBOL data name -


• Full word Binary - PIC S9 (8) COMP.
• Half word Binary - PIC S9 (4) COMP.

Name: A Valid COBOL data name (Character string).


Label: A COBOL paragraph or a section name.
Time in hhmmss format: PIC S9 (7) COMP - 3.
Pointer Reference: Pointer name.

Non valid COBOL statements

ENVIRONMENT DIVISION.
• Only the header is required in this section.
• INPUT-OUTPUT SECTION, FILE CONTROL, SELECT statements not required. Instead,
Files will have to be defined in the File Control Table (FCT) in CICS.

DATA DIVISION
• FILE SECTION is not required.
• LINKAGE SECTION is required.

PROCEDURE DIVISION
The following COBOL statements cannot be issued in a CICS application program because they invoke
o/s SVC calls.

- ACCEPT - DATE - DISPLAY - EXHIBIT


- RELEASE - SORT - STOP RUN - TRACE -SEARCH -SEARCH ALL
- Any I/O statements (OPEN, CLOSE, READ, WRITE, REWRITE, DELETE, START).

Executive Interface Block

The EIB Block contains, apart from information related to CICS communications, the following
EIBDATE, EIBTIME - Date and Time at which the transaction was started or The time it was refreshed
using the ASKTIME command

1. EIBCPOSN The cursor position in the map.


2. EIBTRNID transaction id (1 to 4 chars)
3. EIBTRMID terminal id (1 to 4 chars)
4. EIBTASKN task number of this task (s9(7)comp-3)
5. EIBCALEN length of communication area (S9(4) comp)
6. EIBDATE date when this task started (S9(7)comp-3)
7. EIBTIME time when this task started (S9(7)comp-3)
8. EIBAID attention id (1 byte)
9. EIBFN function code of the last command (2 bytes)
10. EIBRCODE response code of the last command(6 bytes)

EIBRESP:
The value returned in the attribute EIBRESP can be used for checking whether a CICS command was
executed successfully by CICS or not. The EIB variables are available in the copy book DFHEIBLK.
This copy book will be added by the translator at the time of translation. This copy book is inserted as a
first variable in the Linkage section of the Program.

12
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

COMMAREA:
The example above depicts the same transaction being executed again. This is a very common practice
and is the basis for the pseudo-conversational programming style normally employed in CICS
programming. The data between successive executions is passed through a COMMAREA, which is
coded as DFHCOMMAREA in the Linkage Section.
A corresponding data area must also be defined in the Working Storage section of the same program,
shown as WS-COMM-AREA in the above slide. This is the source of the data that is passed on to the
next execution of the transaction. It is always a good practice to code the DFHCOMMAREA. Otherwise,
the CICS translator will insert the DFHCOMMAREA in the linkage section with PIC X.
The CICS translator will also insert a copybook called DFHEIBLK before the DFHCOMMAREA. This
copy book pertains to the EIB (Execution Interface Block) and it contains vital information that can be
used by the application program.

Use of COMMAREA
1. It is mainly used to pass date from one task to another task of the same program
2. Without this it is highly difficult to write a program in Pseudo conversation.
It is used to keep track of program navigation in Pseudo conversation.

01 WS-COMM-AREA.
05 WS-FLAG PIC X(1).

LINKAGE SECTION.
01 DFHCOMMAREA.
05 LS-FLAG PIC X(1).

EXEC-CICS SEND
MAP('MAP1')
MAPSET('MAP1S')
FROM (MAP1O)
END-EXEC
EXEC-CICS RETURN
TRANSID('TRX1')
COMMAREA(WS-COMM-AREA)
END-EXEC

3. Length of the commarea is used to check if the program is executing for the first time or
subsequent times.
IF EIBCALEN = 0
PERFORM INITIAL-PARA
ELSE
PERFORM MAIN-PARA
END-IF

4. Keep a value into a WS-FLAG in the commarea and use it in the next task for navigation of the
program.
IF EIBCALEN = 0
PERFORM INITIAL-PARA
ELSE
EVALUATE LS-FLAG
WHEN '1'
PERFORM READ-PARA
WHEN '2'
PERFORM VALIDATE-UPDATE
END-EVALUATE
END-IF

13
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

5. It is also used to pass data to XCTL/LINK programs


6. It is used to check the fields are updated by the terminal user or not as shown below.
Task1 : Send map1 to enter a policy number
Terminal action: Enter policy number and enter
Task2 : Receive map1 and read policy master file and Move file fields to both map2 and commarea
Terminal action: updates file fields in map2
Task3 : Receive map2 and check map2 fields and DFHCOMMAREA fields.
If both are same then map2 fields are not updated by terminal user
If both are not same then map2 fields are updated by terminal user
In update programs, file record is moved both COMMAREA and MAP.
Verify COMMAREA value with map values, if both are different then field in the map are updated
by terminal user otherwise it is not updated. So it is used to check whether fields are updated or not.
7. Maximum limitation of COMMAREA is 64K but recommended is 25K.
The performance of the system is degraded when excess COMMAREA is used.

CICS TRANSLATOR

The CICS translator converts CICS commands into COBOL code so that it can be compiled by a standard
COBOL compiler. The CICS translator changes EXEC CICS commands into COBOL statements and
adds other necessary lines to your code.

CICS TRANSLATION EXAMPLE:


BEFORE TRANSLATION AFTER TRANSLATION
EXEC CICS LINK MOVE '+H D &' TO DFHEIV0.
PROGRAM ('A') MOVE 'A' TO DFHEIV1.
END-EXEC CALL 'DFHEIV1' USING DFHEIV0,DFHEIV1.

NOTE: When you compile a CICS program, the translator will automatically add many lines of code to
your program, so you don't have to. This code will show up on the compiled listing. The translator adds
some items to
1. WORKING-STORAGE SECTION for CICS to use.
2. LINKAGE SECTION so CICS can communicate with your program.

CICS TRANSLATION JCL


//TRN EXEC PGM=DFHECP1$,  CICS Translator
// PARM='COBOL3',
// REGION=4M
//STEPLIB DD DSN=CICSTS23.CICS.SDFHLOAD,DISP=SHR
//SYSPRINT DD SYSOUT=*
//SYSPUNCH DD DSN=&&SYSCIN,  Translated output
// DISP=(,PASS),UNIT=SYSDA,
// DCB=BLKSIZE=400,
// SPACE=(400,(400,100)) `
//SYSIN DD DSN=OZA183.SMF.CICS(PGM1),DISP=SHR  CICS program
//*
//COB EXEC PGM=IGYCRCTL,REGION=4M,  Compilation
// PARM='NODYNAM,LIB,OBJECT,RES,APOST,MAP,XREF,NOSEQUENCE'
//STEPLIB DD DSN=IGY.SIGYCOMP,DISP=SHR
//SYSLIB DD DSN=OZA183.SMF.COPYLIB,DISP=SHR
// DD DSN=CICSTS23.CICS.SDFHCOB,DISP=SHR
// DD DSN=CICSTS23.CICS.SDFHMAC,DISP=SHR
// DD DSN=CICSTS23.CICS.SDFHSAMP,DISP=SHR

14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

//SYSPRINT DD SYSOUT=*
//SYSIN DD DSN=&&SYSCIN,DISP=(OLD,DELETE)  Translated output to compile
//SYSLIN DD DSN=&&LOADSET,DISP=(MOD,PASS),  Object module
// UNIT=SYSDA,SPACE=(80,(250,100))
//SYSUT1 DD UNIT=SYSDA,SPACE=(460,(350,100))
//SYSUT2 DD UNIT=SYSDA,SPACE=(460,(350,100))
//SYSUT3 DD UNIT=SYSDA,SPACE=(460,(350,100))
//SYSUT4 DD UNIT=SYSDA,SPACE=(460,(350,100))
//SYSUT5 DD UNIT=SYSDA,SPACE=(460,(350,100))
//SYSUT6 DD UNIT=SYSDA,SPACE=(460,(350,100))
//SYSUT7 DD UNIT=SYSDA,SPACE=(460,(350,100))
//*
//LKED EXEC PGM=IEWL,REGION=4M,  Link edit
// PARM='LIST,XREF',COND=(5,LT,COB)
//SYSLIB DD DSN=CICSTS23.CICS.SDFHLOAD,DISP=SHR
// DD DSN=CEE.SCEELKED,DISP=SHR
//SYSLMOD DD DSN=OZASUP.CICS.LOADLIB,DISP=SHR  Load library
//SYSUT1 DD UNIT=SYSDA,DCB=BLKSIZE=1024,
// SPACE=(1024,(200,20))
//SYSPRINT DD SYSOUT=*
//SYSLIN DD DSN=CICSTS23.CICS.SDFHSAMP(DFHEILID),DISP=SHR
// DD DSN=&&LOADSET,DISP=(OLD,DELETE)
// DD DDNAME=SYSIN
//*STATEMENTS FOR CICMAPGM PROGRAM
//LKED.SYSIN DD *

Map coding Rules


12345678901234567890123456789012345678901234567890123456789012345678901234567890
10 20 30 40 50 60 70 80
7 6
1------789----- 16 72
NAME MACRO OPERAND,OPERAND,.... X
1234567891123456
AAAAAAA BBBBBB CCCCCCC,CCCCCCC,CCCCCCC

Name = Mapset name/ Map name/ Field name.


It is same as member name.Maximum length of the name is 7 chars.

Macro = DFHMSD -- Mapset definition


DFHMDI -- Map definition
DFHMDF -- Field definition
END -- End of mapset
Operands:
Mapset operands Map operands Field Operands
TYPE=&SYSPARM SIZE=(24,80) POS=(ROW,COL-1)
MODE=IN/OUT/INOUT LINE=1 LENGTH=N
LANG=COBOL COLUMN=1 ATTRB=(IC,UNPROT/PROT/ASKIP,NUM,
TIOAPFX=YES JUSTIFY=LEFT FSET/FRSET,
CTRL=(FREEKB,FRSET,PRINT,ALARM) BRT/NORM/DARK)
HILIGHT=OFF/BLINK/REVERSE INITIAL='VALUE'
UNDERLINE JUSTIFY=LEFT/RIGHT/BLANK/ZERO
PICIN=999
PICOUT=999.99
COLOR=color/default
CASE=MIXED
GRPNAME=grpname,OCCURS=number)
OUTLINE=(BOX/LEFT/RIGHT/OVER/UNDER)

15
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Specified Assumed
LEFT BLANK
RIGHT ZERO
BLANK LEFT
ZERO RIGHT
If justify is not specified and num is specified
then it takes Right and zero

Different types of fields

Different types of fields


|
_________________________________________
| | |
NAMED FIELDS UNNAMED FIELDS STOPPER FIELD/SKIPPER

Data fields Screen Headers Field to stop data on another


Fields sent and Field Lables data entry field
received from program Navigation lables

Named field goes to symbolic map. Unnamed field goes to physical map

Attribute for various Fields

Named Fields
Inquiry, only Send : ATTRB=(ASKIP,FRSET,BRT/NORM)
Inquiry, send and receive : ATTRB=(ASKIP,FSET,BRT/NORM)
Insert/Update : ATTRB=(IC,UNPROT,FSET,BRT/NORM)  IC on single field
Error Message : ATTRB=(ASKIP,FRSET,BRT/NORM)

Unnamed Fields
Headers/Labels/screen navigation : ATTRB=(ASKIP,FRSET,BRT/NORM)

Skipper Fields
All skipper fields : ATTRB=(ASKIP,FRSET,NORM),Length(1)

Stopper Fields
All stopper fields : ATTRB=(PROT,FRSET,NORM),Length(1)

Skipper Field
The skipper is an unlabeled 1-byte field with the auto skip attribute.
POLNUM DFHMDF POS=(06,38),LENGTH=4,ATTRB=(IC,UNPROT,FSET,BRT)
*
DFHMDF POS=(06,43),LENGTH=01,ATTRB=(ASKIP,NORM)
When the data entry on a field is overflowing from 1 field then it move to another unprotected field

Stopper Field
The stopper is an unlabeled 1-byte field with the prot attribute.
POLNUM DFHMDF POS=(06,38),LENGTH=4,ATTRB=(IC,UNPROT,FSET,BRT)
*
DFHMDF POS=(06,43),LENGTH=01,ATTRB=(PROT,NORM)

16
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

When the data entry on a field is overflowing then it is stopped. Now user has to reset key board to
overcome this.

FSET and FRSET

Field with FRSET is received only when the terminal user modifies it.
Field with FSET is received whether terminal user updates it or not.
Left most significant bit in attribute byte is MDT.
If MDT = 0 then that field is not received to the program
If MDT = 1 then that field is received to the program
FRSET makes MDT to 0
FSET makes MDT to 1

On what type of fields FRSET used?


All unnamed fields are defined with FRSET.
All named fields to send but not received. i.e. every field on inquiry screens used to send only
Error message is always declared with FRSET because it is only to send but not to receive.

On what type of fields FSET used?


All named fields on update and insert screens. All named fields to send and receive on inquiry screens

How to check if the field is updated or not when FSET and FRSET is used?
FSET FRSET

Before send map, Move value to both EVALUATE TRUE


field in the output map and to the field WHEN FIELDL > 0
in COMMAREA Updated
WHEN (FIELDL = 0) AND (FIELDF = X'80')
After Receive map, compare field in input Updated but erased
map and field in DFHCOMMAREA. WHEN OTHER
If both are same then the field is not Not updated
updated otherwise field is updated. END-EVALUATE.

How to set Attribute FSET/FRSET?


At Mapset level At field level Through program
CTRL=(FREEKB,FRSET) ATTRB=(..,..,FSET/FRSET) Move DFHBMFSE TO FIELDA
Example

Policy Browse Screen1

Policy Number :P043125210

PF3: EXIT Enter: Continue

17
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

FRSET
Case1: When terminal user not entered value and hit enter
Abends with MAPFAIL

Case2: When terminal user entered incorrect policy number


User action Transid entered
TASK1  Program started, Initial map sent
User action Terminal user entered incorrect policy number and entered
TASK2  Program started, map received, file read with record not found, handled error
and send map
User action Terminal user not changed policy and hit enter
TASK3  Program started, map received with mapfail, handled error and send map
This time Program not received policy number so low values sent with error message.

FSET
Case1: When terminal user not entered value and hit enter
User action Transid entered
TASK1  Program started, Initial map sent
User action Terminal user entered without entering policy number
TASK2  Program started, map received, low values received and sent error message

Case2: When terminal user entered incorrect policy number


User action Transid entered
TASK1  Program started, Initial map sent
User action Terminal user entered incorrect policy number and entered
TASK2  Program started, map received, file read with record not found, handled error
and send map
User action Terminal user not changed policy and hit enter
TASK3  Same as TASK2
Error message received but Policy number is still there.

Cursor positioning

Cursor positioning

Static Dynamic Symbolic Dynamic Relative

ATTRB=(IC,...) MOVE -1 TO FIELD2L EXEC CICS SEND


EXEC CICS SEND MAP(MAP1)
MAP(MAP1) MAPSET(MAP1S)
MAPSET(MAP1S) FROM(MAP1O)
FROM(MAP1O) CURSOR(250)  3*80 + 10
CURSOR END-EXEC  4th row 11th col
END-EXEC
Static
1. It is set on mapset definition
2. Default cursor positioning when map is sent
3. If IC is given on more than one field then cursor is placed on last field
4. Dynamic or relative can modify the default for that command only

18
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Dynamic
1. It is done through program
2. It is used to set cursor positioning on error fields in Update/Insert screens
3. Without this terminal user has to bring the cursor by using tab

Relative
1. It is done through program
2. It is more difficult than Dynamic cursor positioning
3. When field location is changed then modify program accordingly

How to receive Cursor positioning?


On data entry (Update/Insert) screens, when terminal user wants any help on a field values, then receive
the cursor into program and send help info into message area.
Cursor position is received into EIBCPOSN. Then based on the value in EIBCPOSN send help message
into the next send map.
EVALUATE TRUE
WHEN EIBCPOSN > 330 AND < 340
PERFORM 300-FIELD1-HELP

WHEN EIBCPOSN > 410 AND < 420


PERFORM 300-FIELD2-HELP

WHEN EIBCPOSN > 490 AND < 500


PERFORM 300-FIELD3-HELP

WHEN OTHER
PERFORM 300-INVALID-SELECTION
END-EVALUATE

Design Considerations on MAPS

. Use screen header, Screen name, error message and navigation area.
. Use meaningful label names and field names.
. Use FRSET on fields only for output.
. Use FSET on all fields of insert and update screens.
. Use IC on first unprotected field.
. Use Skipper on most unprotect fields this will improve data entry speed. I.e. cursor moves to the next
field when previous field is overflowing. The data will overflow to the next field.
. Use Stopper on previous field if the next unprotect field is important. When trying to overflow then
keyboard will be locked.
. Use error message with more lines to send more error messages at one time. This will increase error
correction time.
. Use alphanumeric fields on amount and number fields and then convert into numerics by using amount
conversion subroutines in the program.
. Use help area on insert and update screens to send help message when terminal user asking for help.
. Use Bight intensity on important fields and important headers.
. Use rare keys for update and delete confirmations, this will avoid unexpected updates/deletes.
. Use F10 and F11 to browse single record in multiple pages.
. Use F7 and F8 to browse more records on paging logic.
. Display Screen name, program name, date and time on every screen
. When a single record is shown on multiple screens then design it navigate any screen with
screen number.

19
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Program Considerations

. Write program always in a pseudo conversation technique.


. Set a value to flag in commarea at task termination and check that value when new task is generated.
This is used for program navigation.
. Use RESP instead of Handle condition. RESP has lot of flexibility over Handle condition.
. Use TSQ when multiple records are browsed. This reduces reading of file for every PF7 and PF8.
. Use TSQ name with Termid + TSQname and create it in main memory, so that it creates
. Move file records into COMMAREA before it is sent for update and check COMMAREA and map
fields after receive then ensure fields are updated or not.
. Update an attribute of each unprotected field to make it protect after update or insert.
. Create menu driven programs with XCTL to split the functionality of the main program.
. Try to convert all possible exceptions of a command and convert into meaningful error messages.
. Send a default values in the initial map on insert screens to reduce data entry.
. Validate all fields even the first field is errored and send all messages in the message area.
. Use clear and simple housing keeping logic. One should clearly understand the program logic
by looking into it.
. Use program processing logic in the top of the program, so that one can understand the
main navigation of the program.
. Use Dynamic symbolic cursor positioning technique rather than dynamic relative.

Symbolic Fields
BMS Member name MAP1S, Mapset name MAP1S, Map name MAP1, Copybook Name MAP1S

01 MAP1I.
02 FILLER PIC X(12).
02 FIELD1L PIC S9(4) COMP. 1.
02 FIELD1F PIC X(1). 2.
02 FILLER REDEFINES FIELD1F.
03 FIELD1A PIC X(1). 3.
02 FIELD1I PIC X(10).  Length defined in Map 4.
.
.
01 MAP1O REDEFINES MAP1I.
02 FILLER PIC X(12).
02 FILLER PIC X(3).
02 FIELD1O PIC X(10).  Length defined in Map 5.
.
.
Field1A and Field1F take the same memory area.
MAP1I and MAP1O occupy the same memory area.
MODE in MAPSET definition controls the input and output maps.
MODE=IN  Creates MAP1I
MODE=OUT  Creates MAP1O
MODE=INOUT  Creates both MAP1I and MAP1O

How to use OUTPUT map fields How to use input map fields

Move File-field/Default-value TO FIELD1O EXEC CICS RECEIVE


.. MAP('MAP1')
.. MAPSET('MAP1S')
.. INTO(MAP1I)
END-EXEC

20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

EXEC CICS SEND


MAP('MAP1')
MAPSET('MAP1S') Use fields of input map
FROM(MAP1O)
END-EXEC

Note: Both MAP1I and MAP1O occupies the same memory area. You can also use MAP1I in the
send map and MAP1O in receive map but the result will not be changed.

When to use 5 Different symbolic fields

Input fields
Field1L  To check whether field is updated or not when FRSET is used
To set cursor on error field dynamically
MOVE -1 TO Field1L
EXEC CICS SEND MAP('MAP1') MAPSET('MAP1S') FROM(MAP1O)
CURSOR
END-EXEC
Field1F  To Check if the field is erased when FRSET is used
IF Field1F = X'80' and Field1L > 0
Filed1 is updated
END-IF

IF Field1F = X'80' and Field1L = 0


Filed1 is updated but the data is erased
END-IF
Field1A  To change the default attributes of Field before sending map
Use DFHBMSCA fields to set this attribute
To protect a field when update is complete
To bright a field intensity
Though it is input map field but it is used for the output operation
COPY DFHBMSCA
MOVE DFHBMASB TO Field1A
Field1I  To receive map field value into application program

Output Fields
Field1O  To send a value to the map field from application program

Basic Commands

Send Map Receive Map


EXEC CICS SEND EXEC CICS RECEIVE
MAP('MAP1') MAP('MAP1')
MAPSET('MAP1S') MAPSET('MAP1S')
FROM(MAP1O) INTO(MAP1I)
[LENGTH(100)] [LENGTH(100)]
[CURSOR/CURSOR(230)] [TERMINALASIS]
[MAPONLY/DATAONLY] END-EXEC
[ALARM]
[ERASE/ERASEUP]
[FREEKB]
END-EXEC

21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

MAPONLY -- To send only Physical map TERMINALASIS-- Stops Lower case to Upper case
-- It is used 1st time translation.
-- It reduces traffic
DATAONLY -- To send only symbolic map
-- Map is with terminal and
only data is sent
ERASE -- Erase screen before send
ERASEUP -- Erase only unprotected fields.
If both are not coded it sends both physical
and symbolic map.
Error conditions Error Conditions
Mapset not defined Mapset not defined
LENGERR -- Length coded but incorrect LENGERR -- Length coded but incorrect
MAPFAIL -- All fields are FRSET
none of fields entered.
Note: If STORAGE=AUTO is given in MAPSET definition then FROM and INTO is not required
System will detect the name of the input and output maps.

RETURN Command
The RETURN command is used to return control to the next higher logical level, or CICS itself.
EXEC CICS RETURN
[TRANSID(name)
[COMMAREA(data-area)
LENGTH(data-value)]]]
END-EXEC.
If none of TRANSID, COMMAREA, or LENGTH is specified, and if COMMAREA had been passed by
a calling program, the RETURN command makes the data in COMMAREA available to the calling
program. That is, the called program does not have to use the COMMAREA option in the RETURN
command. If the TRANSID option is used, the specified transaction identifier will be the transaction
identifier for the next program to be associated with the terminal. . This is allowed only in the program at
the highest logical level. If the TRANSID option is specified, the COMMAREA and LENGTH option
can be used to pass data to the next task.

How to write CICS program

Declarations
1. Declare map Copybook in Working-Storage Section.
DFHAID to check the function key entered by terminal user
DFHBMSCA to change default attributes of fields through program
Copybooks of files/DB2 tables used in the program
2. Declare WS-COMM-AREA.
To make the program pseudo conversation
To pass data from one task to another task of the same program
To pass data from this program to another program
To pass a flag for program navigation when next task is started
3. Declare TSQ-AREA when TSQs are used
4. Declare editing characters when amount fields are to be sent to the screen.
5. Declare DFHCOMMAREA in Linkage section same as .

22
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Procedure Division code


1. Write housekeeping logic in starting of the program.
It is very important logic that says about program navigation.
2. Send map and return Transid
3. Receive map and process data
4. Use file Commands for read/write/rewrite/delete/startbr/readnext/readprev/endbr
5. Handle all error conditions to convert error messages either with Handle/Resp

Abend Handling

Handle Condition

1. Handle condition is a common abend handler for all CICS Commands in a program.
2. This is used to convert CICS COMMAND level abends into error messages and then send to the
terminal user for corrective action.
3. It executes the abend handling paragraph and will not come back. It is almost similar to
GO TO PARA statement.
4. Abends in the COBOL code is not handled with the HANDLE CONDITION
5. Code this HANDLE CONDITION prior to all other CICS Commands which are to be handled
6. Though this command is coded prior to all other commands, it is not executed on normal processing.
It is executed when ever other command is failed with the exceptions given in the handle condition.
7. If any CICS command fails with a condition which is not handled in Handle condition then the
program abends
8. Maximum of 12 conditions can be given in a single handle condition.
9. If more than 12 conditions are to be handled in a program then code second handle condition command
10. Commands coded with NOHANDLE or RESP are not handled with HANDLE CONDITION
Example
EXEC CICS HANDLE CONDITION
MAPFAIL(300-error-para1)
NOTFND(300-Error-para2)
NOTOPEN(300-error-para3)
END-EXEC
..
..
EXEC CICS RECEIVE
MAPSET('MAP1S')
INTO(MAP1I)
END-EXEC

EXEC CICS READ


DATASET('AGTMST')
RIDFLD(AGENT-NUM)
INTO(AGENT-REC)
END-EXEC

PROCESSING LOGIC

300-Error-para1.
move 'enter agent id ' to MSGO
PERFROM 100-send-map1.

300-Error-para2.
move 'Agent not found' to MSGO
PERFROM 100-send-map1.

23
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

300-Error-para3.
move 'AGTMST not opened' to MSGO
PERFROM 100-send-map1.

The Below situations where Handle condition cannot be used


1. When Same exception condition in different commands to be handled differently
2. When a stop loop is required on end of file
3. When a continue is required on certain exception conditions
4. Program with GO TO is not a better way of coding.
5. If link program has handle conditions then main program handle conditions will be effected in
link program if PUSH and POP are not used.

RESP

RESP option can be specified in any CICS command. Its function is similar to the return code in the files
of batch program. If RESP option is specified in a command, CICS places a response code at completion
of the command. The application program can check this code, and then proceed to the next processing.
This approach has an advantage over the HANDLE CONDITION command approach, because this
approach makes the program more structured. If RESP option is specified in a command, the
NOHANDLE option is applied to this command. Therefore, the HANDLE CONDITION requests will
have no effect in this case.
Programmer can have good control with RESP rather than HANDLE CONDITION.

With RESP programmer can do the below activities.


1. Same command at different location of the program can be handled different.
2. Any exception condition can be handled or ignored
3. On a single command more than 12 conditions can be executed
4. If any paragraph is to be executed with PERFORM PARA statement. So that it can come back to the
statement after the PERFORM. Whereas HANDLE CONDITION is GO TO PARA and it will not
come back.
5. With RESP2 option, one can get more accurate reason for the abend. But RESP2 cannot be used
without using RESP.

Procedure to utilize RESP:


1. Define a full word binary field ( S9(8) COMP) in the working storage section as the response field.
Ex. WS-CODE PIC S9(8) COMP.
2. Place the RESP option with the response field in a command (any CICS command).
3. After command execution, check the response code in the response field with
DFHRESP (xxxxx), where xxxxx is : NORMAL for normal completion.

Example
01 WS-MSG-GRP
05 WS-MSG PIC X(15).
05 WS-ERROR-CODE PIC 9(8).
01 WS-ERROR-CODE PIC S9(8) COMP.

EXEC CICS READ


DATASET('POLMST')
RIDFLD(POLICY-NUM)
INTO(POLICY-REC)
RESP(WS-RESP-CODE)
END-EXEC

24
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

EVALUATE WS-RESP-CODE
WHEN DFHRESP(NORMAL)
CONTINUE
WHEN DFHRESP(NOTFND)
MOVE 'POLICY NOT FOUND' TO MSGO
PERFORM 100-SEND-MAP1
WHEN DFHRESP(DISABLED)
MOVE 'POLMST IS DISABLED' TO MSGO
PERFORM 100-SEND-MAP1
WHEN DFHRESP(NOTOPEN)
MOVE 'POLMST NOT OPENED' TO MSGO
PERFORM 100-SEND-MAP1
WHEN OTHER
MOVE 'ERROR CODE IS' TO WS-MSG
MOVE WS-RESP-CODE TO WS-ERROR-CODE
MOVE WS-MSG-GRP TO MSGO
PERFORM 100-SEND-MAP1
END-EVALUATE

PROCESSING LOGIC
.
.
Handle condition Vs Resp

EXEC CICS HANDLE CONDITION EXEC CICS HANDLE CONDITION


NOTFND(300-ERROR-PARA) NOTFND(300-ERROR-PARA)
END-EXEC END-EXEC

EXEC CICS READ EXEC CICS READ


DATASET('POLMST') DATASET('POLMST')
RIDFLD(POLICY-NUM) RIDFLD(POLICY-NUM)
INTO(POLICY-REC) INTO(POLICY-REC)
END-EXEC RESP(WS-RESP-CODE)
END-EXEC
PROCESSING LOGIC PROCESSING LOGIC

EXEC CICS READ EVALUATE WS-RESP-CODE


DATASET('AGTMST') WHEN DFHRESP(NORMAL)
RIDFLD(AGENT-NUM) CONTINUE
INTO(AGENT-REC) WHEN DFHRESP(NOTFND)
END-EXEC MOVE 'POLICY NOT FOUND' TO MSGO
PERFORM 100-SEND-MAP1
END-EVALUATE

PROCESSING LOGIC PROCESSING LOGIC

300-ERROR-PARA. EXEC CICS READ


MOVE 'RECORD NOT FOUND' TO MSGO DATASET('AGTMST')
PERFORM 100-SEND-MAP1. RIDFLD(AGENT-NUM)
INTO(AGENT-REC)
RESP(WS-RESP-CODE)
END-EXEC

EVALUATE WS-RESP-CODE
WHEN DFHRESP(NORMAL)
CONTINUE
WHEN DFHRESP(NOTFND)
MOVE 'AGENT NOT FOUND' TO MSGO
PERFORM 100-SEND-MAP1
END-EVALUATE

25
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

NOHANDLE

If it is used in any CICS command, then all exceptions in that CICS command are not handled by the
HANDLE CONDITION. All Exceptions in that command are ignored. But every CICS command should
be handled. NOHANDLE is used to avoid explicit declaration of the WS-RESP-CODE

Example

EXEC CICS READ DATASET('FILE1')


RIDFLD(KEY-FIELD)
INTO(FILE1-REC)
NOHANDLE  Here NOHANDLE is used to avoid RESP
END-EXEC

EVALUATE EIBRESP  Resp code is moved into EIBRESP. No need to declare it.
WHEN DFHRESP(NORMAL)
PERFORM PARA1
WHEN DFHRESP(NOTFND)
PERFORM PARA2
END-EVALUATE

IGNORE CONDITION

EXEC CICS IGNORE CONDITION


LENGERR
END-EXEC
This is applicable for all the length errors that occur in the program.

HANDLE ABEND
HANDLE ABEND: To detect an ABEND.
The HANDLE ABEND command is used to intercept an abnormal termination (ABEND) with in
program, and to activate, cancel, or reactivate an exit for the ABEND processing.
The format of the HANDLE ABEND is as follows:
EXEC CICS HANDLE ABEND
[PROGRAM (name) |
LABEL (label) |
CANCEL |
RESET]
END-EXEC
PROGRAM or LABEL is used to activate an exit to a program or a paragraph, respectively, for the
ABEND processing.
CANCEL is used to cancel the previously established HANDLE ABEND request.
RESET is to reactivate the previously cancelled HANDLE ABEND request.

ABEND: To force an ABEND.


The ABEND command is used to terminate a task intentionally, causing an ABEND.

EXEC CICS ABEND


[ABCODE (name)]
END-EXEC.
ABCODE is used to specify the user ABEND code (1 to 4 characters).

26
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

PUSH, POP Commands

Push Handle
Suspends the current effect of HANDLE CONDITION, IGNORE CONDITION, HANDLE ABEND and
HANDLE AID commands.

Pop Handle
Reinstates the effect of HANDLE CONDITION, IGNORE CONDITION, HANDLE ABEND and
HANDLE AID commands to what they were before the previous PUSH HANDLE was called.

Example:
If one program call the any subprogram within it. Then in SUB program we use PUSH command to
sustained all the Handle conditions of main program, and before the control giving back to main program
we use POP command to reactivate all the sustained Handle conditions of Main program.
Use of PUSH and POP conditions is to sustain all the Handle error conditions in Subprogram.
Example:-
PGMA PGMB

EXEC CICS HANDLE CONDITION EXEC CICS PUSH


MAPFAIL(300-error-para1) END-EXEC
NOTFND(300-Error-para2) EXEC CICS HANDLE CONDITION
NOTOPEN(300-error-para3) NOTFND(200-Error-para2)
END-EXEC END-EXEC

EXEC CICS RECEIVE EXEC CICS READ


MAPSET('MAP1S') DATASET('ADVMST')
INTO(MAP1I) RIDFLD(AGENT-ID)
END-EXEC INTO(ADV-REC)
END-EXEC
EXEC CICS READ
DATASET('AGTMST') PROCESSING LOGIC
RIDFLD(AGENT-NUM)
INTO(AGENT-REC) EXEC CICS POP
END-EXEC END-EXEC
EXEC CICS RETURN
END-EXEC
EXEC CICS LINK
PROGRAM('PGMB')
COMMAREA(WS-COMM-AREA)
END-EXEC

PROCESSING LOGIC 200-Error-para1.


move 'adv rec not found' to MSGO
PERFROM 100-send-map2.
300-Error-para1.
move 'enter agent id ' to MSGO
PERFROM 100-send-map1.

300-Error-para2.
move 'Agent not found' to MSGO
PERFROM 100-send-map1.

300-Error-para3.
move 'AGTMST not opened' to MSGO
PERFROM 100-send-map1.

27
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

File Commands and its Examples

All file related commands are shown with three files as shown below.

Files
AGTMST
01 AGENT-REC.
05 AGENT-ID PIC X(4).  KEY A001A20080305...
05 AGENT-STATUS PIC X(1). A002A20070507...
05 AGENT-DOJ PIC X(8). A003A20010911...
05 COMM-PERCENT PIC S9(3)V9(2) COMP-3. A004T20010911...
.
.
POLMST
01 POLICY-REC.
05 POLICY-NUM PIC X(4).  KEY P001A20090225...
05 POLICY-STATUS PIC X(1). P002A20110314...
05 ISSUE-DATE PIC X(8). P004A20090421...
05 TOTAL-PREM PIC S9(9)V9(2) COMP-3.
.
.
PREMMST
01 PREM-REC.
05 PREM-KEY.
10 POLICY-NUM PIC X(4). -- KEY1 P001200902250001....
10 PREM-DATE PIC X(8). -- KEY2 P001201002250002....
10 PREM-NUM PIC 9(4). -- KEY3 P001201102250003....
05 PREM-AMT PIC S9(7)V9(2) COMP-3. P001201202250004....
05 LATE-CHRGS PIC S9(5)V9(2) COMP-3. P002201103140001....
. P002201203140002....
. P004200904210001....
. P004201004210002....
P004201104210003....
P004201204210004....

Random read with Equal option

EXEC CICS READ


DATASET ( 'FILE1' )
INTO (FILE1-REC)  Record definition in Working storage.
RIDFLD (FILE1-KEY)  Key-field
LENGTH (N)  (Optional) a value or a field with S9(4)comp.
EQUAL  Default
END-EXEC.

Exp Conditions
NOTFND -- Record not found
DUPKEY -- Random read on alternate key and it is a non unique AIX. In this case read file in dynamic.

Common Exceptions on any file command


DISABLED -- File is disabled. File should be enabled to use it.
FILENOTFOUND -- File is defined in FCT but it is deleted in TSO.
NOTOPEN -- File is not opened. If the file is not opened then CICS will open it. But if the file is used in
batch then it fails.
LENGERR -- Actual record length and the length of the layout specified in INTO option are not correct.
DSIDERR -- File is not registered in FCT.

28
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Ex1: Read AGTMST on Agent Id A002 with EQUAL option

MOVE 'A002' TO AGENT-ID

EXEC CICS READ


DATASET ('AGTMST')
INTO (AGENT-REC)  A002A20070507...
RIDFLD (AGENT-ID)
LENGTH (100)
EQUAL
END-EXEC.

Ex2: Read POLMST on Policy Number P002 with EQUAL option

MOVE 'P002' TO POLICY-NUM


EXEC CICS READ
DATASET ('POLMST')
INTO (POLICY-REC)  P002A20110314...
RIDFLD (POLICY-NUM)
LENGTH (100)
EQUAL
RESP(WS-RESP-CODE)
END-EXEC.

Random read with Generic option

READ command with the GENERIC option is used to read a nonspecific record based on the generic key
( not full key ). Both INTO and SET options can be used. An additional KEY LENGTH ( generic key
length) option should be specified with GENERIC option.

EXEC CICS READ


DATASET ( 'FILE1' )
INTO (FILE1-REC)  Record definition in Working storage.
RIDFLD (FILE1-PARTIAL-KEY)  Partial Key
KEYLENGTH (M)  Partial key length
GENERIC
LENGTH (N)  length of record
END-EXEC.

Exp Conditions
INVREQ Key length specified is greater than the actual key length.
same as above

Ex: Read first premium from PREMMST on policy P004 with generic option

MOVE 'P004' TO POLICY-NUM IN PREM-KEY

EXEC CICS READ


DATASET ('PREMMST')
INTO (PREM-REC)  P004200904210001....
RIDFLD (POLICY-NUM)
KEYLENGTH (4)
GENERIC
LENGTH (100)
END-EXEC.

29
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Random read with GTEQ option


It is used to read a nonspecific record whose key is equal to or greater than the full key data specified.
This is useful when you know the full key, but you don’t know for sure that the record with that key
exists in the file.

EXEC CICS READ


DATASET ( 'FILE1' )
INTO (FILE1-REC)  Record definition in Working storage.
RIDFLD (FILE1-KEY)  Key-field
GTEQ
LENGTH (N)  Optional
END-EXEC.

Ex1: Read PREMMST on policy P003 with GTEQ option

MOVE SPACES TO PREM-KEY


MOVE 'P003' TO POLICY-NUM IN PREM-KEY

EXEC CICS READ


DATASET ('PREMMST')
INTO (PREM-REC)  P004200904210001....
RIDFLD (PREM-KEY)
GTEQ
LENGTH (100)
END-EXEC.

Ex2: Read PREMMST and get the premium paid after 20110101 on policy P004

MOVE 'P00420110101' TO PREM-KEY

EXEC CICS READ


DATASET ('PREMMST')
INTO (PREM-REC)  P004201104210003....
RIDFLD (PREM-KEY)
GTEQ
LENGTH (100)
END-EXEC.

Random read with UPDATE option

A combination of the READ command with the UPDATE option and the REWRITE command is used to
update a record. Between these two commands, exclusive control over the record will be maintained for
this task, so that no other tasks can access this record for updates. Therefore the interval between these
two commands should be as short as possible.

EXEC CICS READ


DATASET ('FILE1')
INTO (FILE1-REC)  Record definition in WS.
RIDFLD (FILE1-KEY)  Key
LENGTH (N)  Optional
UPDATE
END-EXEC.

Exp Conditions
INVREQ  If the dataset is not defined in update mode. To avoid this change it to update mode with
CEMT.

30
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

The READ command with the UPDATE option normally maintains exclusive control
over the record read until:
• The record is updated by the REWRITE command.
EXEC CICS REWRITE
DATASET ('FILE1')
FROM (FILE1-REC)  Record definition in WS.
END-EXEC.
Exp Conditions
INVREQ -- Rewrite command is issued without a prior read command with update option
When trying to update key field
• The transaction is normally or abnormally completed.
• If you think the read update option is not required, then UNLOCK command is prepared.
EXEC CICS UNLOCK
DATASET ('FILE1')
END-EXEC.

Ex1: Read A001 and update with status 'T'

MOVE 'A001' TO AGENT-ID


EXEC CICS READ
DATASET ('AGTMST')
INTO (AGENT-REC)
RIDFLD (AGENT-ID)
LENGTH (100)
UPDATE
END-EXEC.

MOVE 'T' TO AGENT-STATUS


EXEC CICS REWRITE
DATASET ('AGTMST')
FROM (AGENT-REC)
END-EXEC.

Write
The WRITE command is used to write a record directly into a file based on the key specified.
The Format for the WRITE command for VSAM/KSDS is as follows:

EXEC CICS WRITE


DATASET ('FILE1')
FROM (FILE1-REC)  Record definition in WS.
RIDFLD (FILE1-KEY)  Key
LENGTH (N)  Optional
END-EXEC.

Exp Conditions
INVREQ  File is not write enable
DUPREC  Duplicate record is found
NOSPACE No disk space available

Ex1: Insert agent record with agent id A005

MOVE 'A005' TO AGENT-ID


MOVE 'A' TO AGENT-STATUS
MOVE 20120304 TO AGENT-DOJ
MOVE 12.00 TO COMM-PERCENT

31
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

.
.
EXEC CICS WRITE
DATASET ('AGTMST')
FROM (AGENT-REC)
RIDFLD (AGENT-ID)
LENGTH (100)
END-EXEC.

Write with Massinsert options

The WRITE command with the MASSINSERT option is used to add a group of records whose keys are
in ascending order into a file. If there are many records to be added as a group, this option will provide
high performance in writing records. Since the MASSINSERT option causes exclusive control over the
file, the file must be released by the UNLOCK command after the completion of the writing command.
MASSINSERT must be explicitly specified as the option.
Ex:
Procedure division.
MOVE ‘0001’ TO FILE1-KEY.
MASS-INS-LOOP.
ADD 1 TO THE REC-A-KEY-SEQ.
……
….. ( Prepare the record content.)

MOVE 35 TO REC-LEN.
EXEC CICS WRITE
DATASET ('FILE1' )
FROM (FILE1-REC)
RIDFLD (FILE1-KEY)
LENGTH ( N )
MASSINSERT
END-EXEC.

If REC-A-KEY-SEQ < 99
GO TO MASS-INS-LOOP.
EXEC CICS UNLOCK
DATASET (‘FILE1’)
END-EXEC.
It gives high performance in writing the records

Delete after read with update

The DELETE command is issued without the record key information (i.e RIDFLD) after the READ
command with UPDATE option has been completed. The record which was read by the
READ/UPDATE command will be deleted from the file.
EXEC CICS READ
DATASET ('FILE1')
INTO (FILE1-REC)  Record definition in WS.
RIDFLD (FILE1-KEY)  Key
LENGTH (N)  Optional
UPDATE
END-EXEC.

EXEC CICS DELETE


DATASET ('FILE1')
END-EXEC.

32
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Exp Condition
INVREQ -- Delete command without RIDFLD is issued and without prior read/update

Ex1: Read Agent Id A004 and delete it if that agent is terminated


MOVE 'A004' TO AGENT-ID
EXEC CICS READ
DATASET ('AGTMST')
INTO (AGENT-REC)  Record definition in WS.
RIDFLD (AGENT-ID)  Key
UPDATE
END-EXEC.

IF AGENT-STATUS = 'T'
EXEC CICS DELETE
DATASET ('FILE1')
END-EXEC
END-IF.

Direct Delete approach


In this approach, the DELETE command is issued with the full key information in the RIDFLD field. The
record specified will be directly deleted from the file.

EXEC CICS DELETE


DATASET ('FILE1')
RIDFLD (FILE1-KEY)  Key
END-EXEC.

Exp Condition
DUPKEY  Duplicate key is found
NOTFND The record specified is not found
INVREQ  If the file is not updatable

Ex: Read Agent Id A003 with direct delete approach


MOVE 'A003' TO AGENT-ID
EXEC CICS DELETE
DATASET ('AGTMST')
RIDFLD (AGENT-ID)
END-EXEC

Delete with generic option


In this approach, the DELETE command is issued with the GENERIC option. A group of records, which
satisfy the generic key specified, will be deleted from the file.
EXEC CICS DELETE
DATASET ('FILE1')
RIDFLD (FILE1-PARTIAL-KEY)  Partial Key
KEYLEN(N)  Partial key length
GENERIC
NUMITEM(M)  Number of record that are deleted
END-EXEC.

Exp Condition
NOTFND -- The record specified is not found
INVREQ -- The key length specified is greater than the actual key length of the record

33
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Ex: Delete all premiums on policy P003 from PREMMST

EXEC CICS DELETE


DATASET ('PREMMST')
RIDFLD (POLICY-NUM)  Partial Key
KEYLEN(4)  Partial key length
GENERIC
NUMITEM(WS-NUM)  Number of record that are deleted
END-EXEC.

Sequential/Dynamic Access

Sequential/Dynamic access of VSAM files under CICS is called browsing. The following commands are
used for this access mode.
STARTBR - To establish a position for a browse operation
READNEXT – To read the next record.
READPREV – To read a previous record.
RESETBR – To establish another position for a new browse.
ENDBR – To complete a browse operation.

Format for STARTBR command for VSAM/KSDS.


EXEC CICS STARTBR
DATASET ('FILE1')
RIDFLD (FILE1-KEY)  File1-key
EQUAL/GTEQ/GENERIC
[KEYLEN(N)]
END-EXEC.

Exp Condition
NOTFND -- The record specified is not found
INVREQ -- The file is defined no browse

Format of READNEXT command for VSAM/KSDS


EXEC CICS READNEXT
DATASET ('FILE1')
RIDFLD (FILE1-KEY)
INTO (FILE1-REC)
LENGTH ( N )  SHOULD BE SPECIFIED
END-EXEC.

When reading variable length records give the maximum length .

Exp Condition
ENDFILE -- End of file is detected
LENGERR -- The actual record is greater than the length specified
It may arise with VB records. It should be cautious while writing these.
INVREQ -- No prior startbr

Format of READPREV command for VSAM/KSDS


EXEC CICS READPREV
DATASET ('FILE1')
RIDFLD (FILE1-KEY)
INTO (FILE1-REC)
LENGTH ( N )  SHOULD BE SPECIFIED
END-EXEC.

34
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Exp Condition
ENDFILE -- End of file is detected
INVREQ -- No prior startbr

RESETBR
The RESETBR command is used to reestablish another starting point with in the same browse operation
against the same file. The RESETBR perform exactly same as the STARTBR command, except that
reposition is much faster because the file is already in the browse mode by the prior STARTBR. Without
issuing the ENDBR command, the RESERBR command makes it possible to reposition the dataset for
the new browse operation. The RESETBR command can also be used to change the characteristics of
browse, like from generic key positioning to full key positioning.

Format of RESETBR command for VSAM/KSDS


EXEC CICS RESETBR
DATASET ('FILE1')
RIDFLD (FILE1-KEY)
GTEQ
END-EXEC.

Exp Condition
NOTFND -- The record specified is not found
INVREQ -- The file is defined no browse

ENDBR command
At the physical end-of-file or logical end-of-file the browse operation must be terminated. The ENDBR
command is used to terminate the browse operation, which was initiated by the prior STARTBR
command.
EXEC CICS ENDTBR
DATASET ( ‘FILE1’ )
END-EXEC.

Exp Condition
INVREQ -- No prior startbr

Ex1: Browse all premiums on Policy P002 from PREMMST.

MOVE LOW-VALUES TO PREM-KEY


MOVE 'P002' TO POLICY-NUM
EXEC CICS STARTBR
DATASET ('PREMMST')
RIDFLD (PREM-KEY)
GTEQ
END-EXEC.

MOVE 'N' TO Stop-loop

PERFORM UNTIL Stop-loop = 'Y'


EXEC CICS READNEXT
DATASET ('PREM-MST')
RIDFLD (PREM-KEY)
INTO (PREM-REC)
RESP (WS-RESP)
END-EXEC

35
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

EVALUATE WS-RESP
WHEN DFHRESP(NORMAL)
IF POLICY-NUM NOT = 'P002'
PERFORM PROCESS-PARA
ELSE
MOVE 'Y' TO STOP-LOOP  STOP-LOOP when read next returns
different policy
EXEC CICS ENDBR
DATASET ('PREMMST')
END-EXEC
END-IF

WHEN DFHRESP(ENDFILE)  Stop-loop when End of file is reached


MOVE 'Y' TO STOP-LOOP
EXEC CICS ENDBR
DATASET ('PREMMST')
END-EXEC
END-EVALUATE
END-PERFORM

Ex2: Browse all premiums in PREMMST.

MOVE LOW-VALUES TO PREM-KEY


EXEC CICS STARTBR
DATASET ('PREMMST')
RIDFLD (PREM-KEY)
GTEQ
END-EXEC.

MOVE 'N' TO STOP-LOOP


PERFORM UNTIL STOP-LOOP = 'Y'
EXEC CICS READNEXT
DATASET ('PREM-MST')
RIDFLD (PREM-KEY)
INTO (PREM-REC)
RESP (WS-RESP)
END-EXEC

EVALUATE WS-RESP
WHEN DFHRESP(NORMAL)
PERFORM PROCESS-PARA
WHEN DFHRESP(ENDFILE)  STOP-LOOP when End of file is reached
MOVE 'Y' TO STOP-LOOP
EXEC CICS ENDBR
DATASET ('PREMMST')
END-EXEC
END-EVALUATE
END-PERFORM

Ex3: Get last policy from POLMST.

MOVE HIGH-VALUES TO POLICY-NUM

EXEC CICS STARTBR


DATASET ('POLMST')
RIDFLD (POLICY-NUM)
GTEQ
END-EXEC.

36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

EXEC CICS READPREV


DATASET ('POL-MST')
RIDFLD (POLICY-NUM)
INTO (POLICY-REC)
END-EXEC

EXEC CICS ENDBR


DATASET ('POLMST')
END-EXEC

Ex4: Get last Premium on policy P001 from PREMMST.

Move HIGH-VALUES TO PREM-KEY


Move 'P001' TO POLICY-NUM IN PREM-KEY

EXEC CICS STARTBR


DATASET ('PREMMST')
RIDFLD (PREM-KEY)
GTEQ
END-EXEC.

EXEC CICS READPREV


DATASET ('PREMMST')
RIDFLD (PREM-KEY)
INTO (PREM-REC)
END-EXEC

EXEC CICS ENDBR


DATASET ('PREMMST')
END-EXEC

Ex5: Get Premium paid after 20110101 on policy P001 from PREMMST.

Move High-Values TO PREM-KEY


Move 'P001' TO POLICY-NUM IN PREM-KEY
Move '20110101' TO PREM-DATE IN PREM-KEY

EXEC CICS STARTBR


DATASET ('PREMMST')
RIDFLD (PREM-KEY)
GTEQ
END-EXEC.

EXEC CICS READPREV


DATASET ('PREMMST')
RIDFLD (PREM-KEY)
INTO (PREM-REC)
END-EXEC

EXEC CICS ENDBR


DATASET ('PREMMST')
END-EXEC.

37
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Update during browse in online


STARTBR EITHER WITH PARTIAL KEY OR FULL KEY

PERFORM UNTIL CONDITION


READNEXT
ENDBR
READ WITH UPDATE
CHANGE VALUE OF THE RECORD
REWRITE
STARTBR WITH THE FULL KEY OF LAST UPDATED RECORD
READNEXT
END-PERFORM.

Update during browse in Batch


STARTBR EITHER WITH PARTIAL KEY OR FULL KEY

PERFORM UNTIL CONDITION


READNEXT
CHANGE VALUE OF THE RECORD
REWRITE
STARTBR WITH THE FULL KEY OF LAST UPDATED RECORD
READNEXT
END-PERFORM.

Other CICS Commands

SET Command
It is used to open, close, enable or disable the file from the program
EXEC CICS SET
DATASET('FILE1')
OPEN/CLOSED/ENABLED/DISABLED
END-EXEC.

ASSIGN Command
It is used to get the userid of terminal user into application program.It is used update fields like last-
change-userid
EXEC CICS ASSIGN
USERID(WS-USER-ID)
END-EXEC.

HANDLE AID Command


Handle aid executes after receive command. Same function key on different screens cannot be processed
differently.
EXEC CICS HANDLE AID
PF3 ( END-ROUTINE)
PA1 ( CANCEL-ROUTINE)
ENTER ( NORMAL-ROUTINE)
ANYKEY (WRONG-KEY-ENTERED)
END-EXEC.

If EIBAID = DFHENTER
PERFORM…

38
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

SEND TEXT Command


It is used to send the text message without a BMS map.
EXEC CICS SEND TEXT
FROM ( WS-MSG-TEXT )
LENGTH( WS-MSG-LEN )
HEADER(WS-HEADER)
ERASE
FREEKB
END-EXEC.

START & RETREIVE Command


The START Command is used to start a transaction at the specified terminal and at the specified time or
interval. Optionally data can be passed to-be-initiated transaction.
It is used to start a new transaction ID in another terminal.
The RETRIEVE Command is used to retrieve the data passed by the START command, which has issued
in the other transaction in order to initiate this transaction.
EXEC CICS START
TRANSID('TRN1')
TIME(185000)
TERMID('TRM6')
END-EXEC

EXEC CICS START


TRANSID('TRN1')
AT HOURS(18) MINUTES(50)
TERMID('TRM6')
END-EXEC

EXEC CICS START


TRANSID('TRN1')
TIME(185000) --> HHMMSS
TERMID('TRM6')
FROM(WS-FIELD)
LENGTH(100)
END-EXEC

EXEC CICS RETRIEVE


INTO(DATAFLD)
LENGTH(LENG)
END-EXEC

Ask Time Command


The ASKTIME command is used to request the current data and current time. The EIBDATE and
EIBTIME fields have the values at the task initiation time.
EIBDATE is defined as PIC S9(7) COMP-3 . --> 0CYYDDD
Vlaue in EIBDATE Actual value
0000001 19000101
0100001 20000101
0112032 20120201
EIBTIME is defined as PIC S9(7) COMP-3 . --> 0HHMMSS
Vlaue in EIBTIME Actual value
0240000 Midnight
0120000 Noon
0000000 Day just started

39
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

How to get the latest date and time


01 utime pic s9(15) comp-3. --> Milli seconds from 19000101
01 ws-date pic x(10).
01 ws-date-yyyymmdd redefines ws-date pic 9(8).
01 ws-time pic x(8).
01 ws-time-hhmmss redefines ws-date pic 9(6).

EXEC CICS ASKTIME


ABSTIME(utime)
END-EXEC.
ASKTIME updates EIBDATE and EIBTIME fields with the latest date and time.
If utime has the value 002837962864828 in milliseconds on completion of the ASKTIME ABSTIME
command, this gives the values 06-12-89 for date and 19:01:05 for time.

FORMATTIME Command
The FORMATTIME command is used to receive the information of date and time in various formats.
EXEC CICS FORMATTIME
ABSTIME (UTIME)
YYYYMMDD (WS-DATE)
DATESEP ('/')
TIME (WS-TIME)
TIMESEP (':')
END-EXEC.
1989/06/12 if datesep is used
19890612bb if datesep is not used. b is space
19:01:05 if timesep is used
190105bb if timesep is not used

ENQ/DEQ Command

These are used to have exclusive control on the Auxiliary TSQ before it is read/write/rewrite
EXEC CICS ENQ
RESOURCE(TSQ-ID)
END-EXEC
EXEC CICS READQ TS
QUEUE(TSQ-ID)
INTO(TSQ-REC)
ITEM(ITEM-NUM)
END-EXEC

Modify the value in TSQ-REC


EXEC CICS WRITEQ TS
QUEUE(TSQ-ID)
FROM(TSQ-REC)
REWRITE
END-EXEC

EXEC CICS DEQ


RESOURCE(TSQ-ID)
END-EXEC.

40
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Difference between LINK and CALL

LINK CALL

1. Syntax 1. Syntax
In Main-program In Main-program
EXEC CICS LINK CALL 'SUB1' USING WS-VAR1,
PROGRAM('SUB1') WS-VAR2
COMMAREA(WS-COMM-AREA)
END-EXEC

In Sub-program In Sub-program
LINKAGE SECTION. LINKAGE SECTION.
01 DFHCOMMAREA PIC X(N). 01 LS-VAR1 PIC..
01 LS-VAR2 PIC..
PROCEDURE DIVISION.
.. PROCEDURE DIVISION USING LS-VAR1,
.. LS-VAR2
EXEC-CICS RETURN ..
END-EXEC ..
EXIT-PROGRAM.
2. It is a static call. 2. It is a dynamic call .

Difference between XCTL and LINK

XCTL LINK

1.Program control is transferred to another same 1.Program control is transferred to another lower
level program and calling program is terminated level program and calling program is not
terminated.
2.Use XCTL in the called program to go back to 2.Use RETURN to go back to Calling program
the calling program
3.It is used to transfer control to another 3.These are common functionality subprograms
functional program. It is used in menu driven It is used for validations, amount conversions,
programs. Interest calculations .
4.Program with XCTL is assigned to 4.Program with LINK has only PPT
a transaction in PCT entry and no PCT entry
i.e. It has both PPT and PCT entries
5.Return in XCTL takes to CICS or Higher level 5.Return in LINK always takes Higher level
program program
6.Syntax 6.Syntax
In Main-pgm MAIN1 In Main-pgm MAIN1
EXEC-CICS XCTL EXEC-CICS LINK
PROGRAM('MAIN2') PROGRAM('SUB1')
[COMMAREA(WS-COMM-AREA)] [COMMAREA(WS-COMM-AREA)]
END-EXEC END-EXEC

In MAIN2 In Sub-pgm
LINKAGE SECTION.
LINKAGE SECTION. 01 DFHCOMMAREA PIC X(100).
01 DFHCOMMAREA PIC X(100).
EXEC-CICS RETURN
END-EXEC

41
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

How to read on record key and alternate record key

File layout:
01 POLICY-REC.
05 POLICY-NUM  Record key
05 POLICY-STATUS
.
.
.
05 SSN  Alternate key

Ex: Base cluster is OZA183.SMF.POLMST


Aix is OZA183.SMF.POLMSTX
Path is OZA183.SMF.POLMSTX.PATH

How to define Alternate index and how to read it in program


Register Path
Define a logical name POLMSTX with CEDA and assign path in DSN
CEDA DEF FILE(POLMSTX) G(SMF)
DSN: OZA183.SMF.POLMSTX.PATH

How to read on alternate key


MOVE 'S001' to SSN
EXEC CICS READ
DATASET(POLMSTX)
RIDFLD(SSN)
INTO(POLICY-REC)
END-EXEC

How to read on record key


Move 'P001' to POLICY-NUM
EXEC CICS READ
DATASET('POLMST')
RIDFLD(POLICY-NUM)
INTO(POLICY-REC)
END-EXEC

ESDS File reads


01 WS-RBA-NUM PIC S9(8) COMP.
01 FILE1-REC.
05 FIELD1 PIC X(4).
05 FIELD2 PIC X(3).
.
.
Sequential read from top to bottom Sequential read from bottom to top

MOVE LOW-VALUES TO WS-RBA-NUM MOVE HIGH-VALUES TO WS-RBA-NUM


EXEC CICS STARTBR EXEC CICS STARTBR
DATASET('FILE1') DATASET('FILE1')
RIDFLD(WS-RBA-NUM) RIDFLD(WS-RBA-NUM)
RBA RBA
EQUAL EQUAL
END-EXEC END-EXEC

42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

MOVE 100 TO WS-LEN MOVE 100 TO WS-LEN


EXEC CICS READNEXT EXEC CICS READPREV
DATASET('FILE1') DATASET('FILE1')
RIDFLD(WS-RBA-NUM) RIDFLD(WS-RBA-NUM)
INTO(FILE1-REC) INTO(FILE1-REC)
LENGTH(WS-LEN) LENGTH(WS-LEN)
RBA RBA
END-EXEC END-EXEC
Keep this readnext in loop until Keep this readnext in loop until
ENDFILE ENDFILE

Random read with RBA num

MOVE 500 TO WS-RBA-NUM


MOVE 100 TO WS-LEN
EXEC CICS READ
DATASET('FILE1')
RIDFLD(WS-RBA-NUM)
INTO(FILE1-REC)
LENGTH(WS-LEN)
RBA
END-EXEC

RRDS File reads

01 WS-RBA-NUM PIC S9(8) COMP.

01 FILE1-REC.
05 FIELD1 PIC X(4).
05 FIELD2 PIC X(3).
.
.
Sequential read from top to bottom Sequential read from bottom to top

MOVE LOW-VALUES TO WS-RBA-NUM MOVE HIGH-VALUES TO WS-RBA-NUM


EXEC CICS STARTBR EXEC CICS STARTBR
DATASET('FILE1') DATASET('FILE1')
RIDFLD(WS-RRN) RIDFLD(WS-RRN)
RRN RRN
EQUAL EQUAL
END-EXEC END-EXEC

MOVE 100 TO WS-LEN MOVE 100 TO WS-LEN


EXEC CICS READNEXT EXEC CICS READPREV
DATASET('FILE1') DATASET('FILE1')
RIDFLD(WS-RBA) RIDFLD(WS-RBA)
INTO(FILE1-REC) INTO(FILE1-REC)
LENGTH(WS-LEN) LENGTH(WS-LEN)
RRN RRN
END-EXEC END-EXEC

Keep this readnext in loop until Keep this readnext in loop until
ENDFILE ENDFILE

43
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Random read with RBA num


MOVE 500 TO WS-RRN
MOVE 100 TO WS-LEN
EXEC CICS READ
DATASET('FILE1')
RIDFLD(WS-RRN)
INTO(FILE1-REC)
LENGTH(WS-LEN)
RRN
END-EXEC

Transient Data Control


The CICS Transient Data Control Program (TDP) allows a CICS transaction to deal with sequential data
called Transient Data files. A transient data file can be used either for input file or an output file, but not
both.
There are 2 type of TDQ: Intrapartition TDQ and Extrapartition TDQ.
Although same CICS commands are used for both Intrapartition TDQ and Extrapartition TDQ, the
applications of these two types of TDQ are very different.
A 1 to 4 character identifier called “destination id” identifies each TDQ. All destination ids must be
registered in the Destination Control Table (DCT).

Intrapartition TDQ
An Intrapartition TDQ is a group of sequential records that are produced and processed by the same
and/or different transactions within a CICS region. This is why the word “Intrapartition” is used.
Only sequential process is allowed for TDQ queue. Once a record is read from a queue, the record will be
logically removed from the queue that is the record cannot be read again.
The Intrapartition queue are used for the various applications such as:
• Interface among CICS transactions.
Application program 1 ----- TDQ ---- Application program 2 ----- report.
• Automatic Task Initiation (ATI).
• Message routing.
• Message broadcast.

Extrapartition TDQ
An Extrapartition TDQ is a group of sequential records which interfaces between the transactions of the
CICS region and the systems (or batch jobs ) outside of the CICS region. This is why the word
“Extrapartition” is used.
In the Input Extrapartition TDQ, records are produced by the programs outside of the CICS region (e.g.
batch jobs, TSO, PC) to be processed by the CICS transaction as input,
Whereas in the Output Extrapartition TDQ, the records are produced by the CICS transactions as output
to be processed outside of CICS.
Each Extrapartition TDQ is a separate physical file, and it may be on the disk, tape or plotter. This implies
that each file must be open within the CICS region when it is OPEN/Close status of a file, while the file
can be opened or closed through the CEMT during a CICS session.
• Interface to batch (or TSO, or PC) jobs.
CICS application program ---- TDQ --- file ---- batch program.
• Interface from batch (or TSO, or PC) jobs.
Batch program --- File --- TDQ --- CICS Application Program.

44
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

The following are the available commands for Transient Data Control:
WRITEQ TD: To sequentially write a record in a TDQ. Valid for both Intrapartition
and Extrapartition TDQ.
READQ TD : To sequentially read a record in a TDQ. Valid for both Intrapartition
and Extrapartition TDQ.
DELETEQ TD: To delete an Intrapartition TDQ. Not valid for the Extrapartition TDQ.
If you omit TD part in the command, CICS assumes it as TS (temporary Storage), don’t forget to write
TD with the command.

WRITEQ TD:
Ex: EXEC CICS WRITEQ TD
QUEUE (‘MSGS’)
FROM (WS-AREA)
LENGTH (WS-LENGTH)
END-EXEC.
MSGS is the name of the TDQ, defined in the DCT. (1- 4 charecters)
FROM defined the name of the area from which the data is to be written.
LENGTH is the length of the record.
READQ TD:
Ex: EXEC CICS READQ TD
QUEUE (‘MSGS’)
INTO (WS-AREA)
LENGTH (WS-LENGTH)
END-EXEC.
A record of the TDQ ‘MSGS’ will be read into WS-AREA. The actual length of the record will be placed
in WS-LENGTH.

Destination Control Table (DCT)


The Primary function of DCT is to register control information of all TDQs. The CICS Destination
Control Program (DCP) uses this table for identifying all TDQs and performing input/output operations
against them.
DFHCDCT TYPE=INTRA,
DESTID=name,
TRANSID=name,
TRIGLEV=number,
REUSE=YES|NO
For the Automatic Task Initiation (ATI) TRANSID and TRIGLEV must be specified.
TRANSID is the transaction id of the transaction to be initiated.
TRIGLEV indicates the number of the records in TDQ, which triggers the transaction to be initiated.
Once a record of Intrapartition TDQ is read by a transaction, the record is logically removed, but it still
occupies the space.
If REUSE=YES is specified, this space for the logically deleted record will be used for other TDQ
records. Records are recoverable.
If REUSE=NO is specified, the logically deleted records are recoverable.

Extrapartition TDQ:
DFHDCT TYPE=EXTRA,
DESTID=name,
DSCNAME=name,
OPEN=INITIAL | DEFERED
DFHDCT TYPE-SDSCI,
DSCNAME=name,
TYPEFILE=INPUT | OUTPUT | RDBACK

45
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

If OPEN= INITIAL is specified, the file will be open at the CICS start-up time.
If DEFERED is specified, the file will be closed until it is specifically opened by the CEMT.
DSCNAME defines the data control block name (1 to 8 characters). For one DSCNAME, a
corresponding DFHDCT entry must be made with TYPE=SDSCI and the same DSCNAME, which in
effect indicates DDNAME of the Extrapartition dataset in JCL of CICS job itself.
TYPEFILE indicates the file to be input, output or input (read backward).

Automatic Task Initiation (ATI)


The Automatic Task Initiation (ATI) is a facility through which a CICS transaction can be initiated
automatically. The number of the records in an Intrapartition TDQ triggers the transaction initiation.
Ex:
DFHDCT TYPE=INTRA,
DESTID=’MSGS’,
TRANSID=MSW1,
TRIGLEV=1000
When the number of TDQ record reaches 1000 in Intrapartition TDQ “MSGS”, CICS will automatically
start transaction MSW1.

Temporary Storage Control

The CICS Temporary Storage Control Program (TSP) provides the application programs with an ability
to store and retrieve the data in a Temporary Storage Queue (TSQ).
A temporary Storage Queue (TSQ) is a queue of stored records (data). It is created and deleted
dynamically by an application program without specifying anything in the CICS control tables, as long as
data recovery is not intended. Therefore application program can use TSQ as a scratch pad memory
facility for any purposes.
A TSQ is identified by the queue id (1 to 8 bytes), and the relative position number called item number
identifies a record within a TSQ.
The records in TSQ, once written, remain accessible until the entire TDQ is explicitly deleted.
The records in the TSQ can be read sequential or directly.
The records in TSQ can be read, re-read and even updated.
TSQ can be accessed by any transactions, in the same CICS region.
TSQ can be written in the auxiliary storage. The auxiliary storage is an external VSAM file (DFHTEMP)
established by the system programmer. It is always available to application programs, which implies that
no file open/close is required.

Available Commands.
WRITEQ TS: To write or Rewrite a record in a TSQ with Item number.
READQ TS: To read a record in a TSQ with Item number.
DELETEQ TS: To delete a TSQ. All records in the TSQ will be deleted.

WRITEQ command (No Update)


The write command is used to write a record (item) in a TSQ. This is the basic command without the
option for update.
Format:
EXEC CICS WRITEQ
QUEUE (tsq-qid)
FROM (tsq-data)
LENGTH (tsq-length)
ITEM (tsq-item)
MAIN | AUXILIARY
END-EXEC.

46
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

QUEUE names the queue id (QID).


FROM defines the area from which data is to be written.
LENGTH (Half word binary field S 9(4) COMP) indicates the length of the record.
ITEM (Half word binary field S 9(4) COMP should be provided, to which CICS places the actual item
number of the record written.
MAIN indicates TSQ to be written in the main storage.
AUXILIARY is specified, the TSQ will be written in the external VSAM file.
If the TSQ with this QID does not exist, a new TSQ with this QID will be created, and the new record is
written to the TSQ. The relative record number of the TSQ will be written into tsq-item by CICS.
If TSQ with this QID already exists, CICS will simply write a record in the existing TSQ at the next to
the last existing record, and place the relative number of the record into tsq-item.

READQ Command (Direct Read).


EXEC CICS READQ
QUEUE (qid)
INTO (ws-data)
LENGTH (ws-length)
ITEM (tsq-item)
NUMITEMS (ws-comp) (OPTIONAL)
NEXT (OPTIONAL)
END-EXEC.
The READQ command is used to read a particular record (item) of a particular TSQ.
By giving the Item number for ITEM option you can retrieve the exact record.
NUMITEMS: If you wish to know the number of ITEMS in the TSQ, specify NUMITEMS
(ws-comp) where ws-comp is S9(4) COMP field.
NEXT: If the next option is specified, the task will read the next sequential logical
Record in the TSQ specified.

READQ command (Sequential Read)


Same as above, only difference is in application program.
Put the READQ command in loop by incrementing the TSQ-ITEM data-field of ITEM.

WRITEQ Command with REWRITE Option


The WRITEQ command with REWRITE option is used to rewrite a record (item) of a TSQ, which has
been read. Same as WRITEQ, only difference is REWRITE option should be included.

DELETEQ Command
The DELETEQ command is used to delete a TSQ entirely.
EXEC CICS DELETEQ
QUEUE (qid)
END-EXEC.
The specified TSQ is deleted and all the records in the TSQ will be deleted.

Difference between TSQ And TDQ

Temporary Storage Queue (TSQ)


• Records in Temporary Storage can be read more than once.
• Records in TSQ can be read randomly.
• You may update an existing item in a TSQ.
• TSQ names can be dynamically defined in the application program.
• TSQ cannot be accessed in batch.
• TSQ cannot start transaction automatically.

47
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Transient Data Queue (TDQ)


• Transient Data Queues can be read only once.
• Records in TDQ can be read only sequentially.
• A record in a TDQ cannot be updated.
• TDQs name must first be defined in the DCT (Destination Control Table).
• TDQ may be used by batch application.
• TDQ can start transaction automatically.

Abend codes Related to Exceptional Conditions


CODE - CONDITION CODE - CONDITION CODE - CONDITION
AEIN - DUPREC AEXJ - ROLLEDBACK AEYO - NOPASSBKWR
AEIE - EODS AEXK - END AEYP - SEGIDERR
AEID - EOF AEXL - DISABLED AEYQ - SYSIDERR
AEIJ - NOSTART AEXV - VOLIDERR AEYR - ISCINVREQ
AEIK - TERMIDERR AEXW - SUPPRESSED AEYT - ENVDEFERR
AEIL - FILENOTFOUND AEXX - TASKIDERR AEYU - IGREQCD
AEIM - NOTFND AEX0 - TCIDERR AEYV - SESSIONERR
AEIO - DUPKEY AEX1 - DSNNOTFOUND AEYX - USERIDERR
AEIP - INVREQ AEX2 - LOADING AEYY - NOTALLOC
AEIQ - IOERR AEX3 - MODELIDERR AEYZ - CBIDERR
AEIR - NOSPACE AEX4 - UOWNOTFOUND AEY0 - INVEXITREQ
AEIS - NOTOPEN AEX5 - PARTNERIDERR AEY1 - INVPARTNSET
AEIT - ENDFILE AEX6 - PROFILEIDERR AEY2 - INVPARTN
AEIU - ILLOGIC AEX7 - NETNAMEIDERR AEY3 - PARTNFAIL
AEIV - LENGERR AEX8 - LOCKED AEY7 - NOTAUTH
AEIW - QZERO AEX9 - RECORDBUSY AEZE - CHANGED
AEIZ - ITEMERR AEYA - INVERRTERM AEZF - PROCESSBUSY
AEI0 - PGMIDERR AEYB - INVMPSZ AEZG - ACTIVITYBUSY
AEI1 - TRANSIDERR AEYC - IGREQID AEZH - PROCESSERR
AEI2 - ENDDATA AEYE - INVLDC AEZI - ACTIVITYERR
AEI3 - INVTSREQ AEYG - JIDERR AEZJ - CONTAINERERR
AEI4 - EXPIRED AEYH - QIDERR AEZK - EVENTERR
AEI8 - TSIOERR AEYJ - DSSTAT AEZL - TOKENERR
AEI9 - MAPFAIL AEYK - SELNERR AEZM - NOTFINISHED
AEXC - RESIDERR AEYL - FUNCERR AEZN - POOLERR
AEXF - ESCERROR AEYM - UNEXPIN AEZO - TIMERERR
AEXG -
AEYN - NOPASSBKRD AEZP - SYMBOLERR
UOWLNOTFOUND
AEXI - TERMERR AEZQ-TEMPLATERR

48
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

Other Abend codes


ABMG Requested BMS Service not included at system generation
ABMP PA/PF key not defined for page retrieval.
AExx Exceptional conditions encountered during the run
(For Ex: AEIN-Duplicate records, AEIT-EOF).
AEY7 Resource security check failed
AEY9 Unsupported command issued Or DB2/IDMS Database is not up.
AICA Transaction abended as a runaway task.
AKCS Deadlock timeout encountered
AKCT Read timeout encountered
ABMO BMS map not in Mapset.
APCT Call for non-existent pgm.
ASRA Abend due to program interruption
ASRB Abend due to OS abend intercepted by CICS.

What is ASRAABEND in CICS?


It occurs when program interruption takes place.
Ex: when alphanumeric string moved to numeric data item or when arithmetic calculations performed on
nonnumeric data item or when an attempt made to read an occurrence of a table beyond the defined
occurrences.
How do you resolve ASRA?
In COBOL ,issue the CEBR commands and get the offset/instruction.

What is the preparation step for CICS –COBOL-DB2 program?


DB2 pre-compilation: This step comments all the SQL statements and replaces them with COBOL
CALL statements. This step does syntax checking and produces the DBRM, which is a SQL source code.

CICS translation: This step comments all the CICS statements and replaces them with host language
CALL statements. This Step follows the above step

COBOL compilation: This compiles the host language source code.


Link edit: This step applies certain operating features to the code which has been precompiled, translated
and compiled to form the load module.

Bind: It requires DBRM prepared in the pre compile step as an input. This performs the following
function
Syntax checking: Bind does syntax checking of the SQL even after it is over in pre compilation process.

Optimisation: Bind invokes a sub component called optimiser, which determines the access path for the
SQL statements in the application program. This access path can be a sequential search or selection of an
index. If it is a selection of an index then bind will prepare a compiled code, which will have explicit
references to this index.
Package and plan creation: Bind prepares the package, which will be the compiled form of the SQL
source code in the DBRM. This package will contain many internal control structures. This will be bound
finally to an application plan. An application plan is nothing but a list of packages.

Authority checking: Bind also performs authority checking as whether the id has got authority to
execute all the code in DBRM. It checks for the authority to assign the package to a collection. It also
checks whether all the packages in a plan can be executed.

49
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS

50

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy