Fresher Notes PDF
Fresher Notes PDF
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
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
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
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
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.
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
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.
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.
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.
7
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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.
STOP RUN.
100000-INITIALIZATION.
100000-EXIT.
EXIT.
200000-PROCESS.
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
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
9
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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'.
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
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 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.
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).
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)
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
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.
14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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
Move M to N.
Display 'N:' N.
RESULT:
N: 'AB '
15
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
Move M to N.
Display 'N:' N.
RESULT:
N: ' AB '
Move N to M.
Display 'M:' M.
RESULT:
M: 'ABC'
Move N to M.
Display 'M:' M.
RESULT:
M: 'BCD'
It is rarely used in report formats.
Redefines clause
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.
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'.
17
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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.
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 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.
The exceptions are the COMPUTE and the DIVIDE with REMAINDER.
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
ADD Examples
SUBTRACT Examples
MULTIPLY Examples
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]
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
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.
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.
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
Case1 Case2
MOVE X TO Y MOVE X TO Y
MOVE X TO Y MOVE X TO Y
23
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
Case1 Case2
MOVE X TO Y MOVE X TO Y
Case3 Case4
MOVE X TO Y MOVE X TO Y
Case5 Case6
MOVE X TO Y MOVE X TO Y
MOVE X TO Y MOVE X TO Y
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
01 A PIC S9(3)V99.
01 B PIC X(5).
MOVE A TO B. It is not recommended
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.
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
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.
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
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.
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.
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 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
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
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.
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.
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'.
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
31
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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.
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.
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
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.
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
Case1 Case2
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.
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.
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
36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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
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
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.
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
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
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.
40
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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.
Subscript Index
42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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
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
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 ...
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
45
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
Case1 Case2
Case3 Case4
STATIC DYNAMIC
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
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
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
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
DISPLAY A. --> It is 7
DISPLAY A. --> It is 6
48
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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.
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
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.
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.
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.
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.
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.
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
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
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
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
FILE CONTROL.
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.
CLOSE TRXN-FILE.
STOP RUN.
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
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.
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
INPUT SHR File should be existing and other jobs can read it
OLD File should be existing and other jobs cannot read it
57
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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.
Write Statement
Syntax:
Move identifier/literal to Logical-record
Write Logical-record
Write Logical-record from ws-record
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
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
IN COBOL IN COBOL
WORKING-STORAGE SECTION.
01 WS-STATUS PIC X(2) VALUE SPACES.
59
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
Method1 Method2
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.
60
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
Method3 Method4
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.
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.
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.
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.
CLOSE IN-FILE
OUT-FILE.
63
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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)
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
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.
DATA DIVISION.
FILE SECTION.
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.
CLOSE IN-FILE
OUT-FILE.
STOP RUN.
INPUT-PROC.
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
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.
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.
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.
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)
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
SYSIN
IGYCRCTL
SRCLIB(pgm1),disp=shr (COBOL COMPILER)
SYSLIN(Object Module)
&&obj,disp=(old,delete)
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=*
70
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com COBOL
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.
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
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
Coding Rules
Cols
1234----10 72
Null statement
//
3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
JOB STATEMENT
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.
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
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
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.
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
Method2
COND=(CC,RO)
Stepname is optional. When omitted, it takes maximum return code of the prior steps.
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
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
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)
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
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
Syntax:
//ddname DD operand1,operand2....
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.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
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
12
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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)
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.
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
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.
System abends
SOC7
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
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
21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
//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
Proc Overrides
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
23
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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
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
Case1: Override INFILE of PS10 with production file Case2: Override second concatenated file in INFILE of PS20 with
production file
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
24
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
25
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
//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)
26
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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
27
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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
28
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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
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*
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.
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.
30
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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
This is my first mail sent from mainframes Message part of the mail
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
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..
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.
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
33
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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
IDCAMS
Create GDG base
//STEP1 EXEC PGM=IDCAMS
//SYSIN DD *
DEFINE GDG(NAME(OZA183.SMF.GDGBASE) -
LIMIT(5) -
NOEMPTY -
SCRATCH)
/*
34
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
/*
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)
/*
35
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
Sort
36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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
37
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
38
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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)
/*
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
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))
/*
42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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
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
/*
45
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com JCL
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 '*'
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
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.
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
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).
.
.
IF EMP-STATUS = 'T'
MOVE IN-REC TO OUT-REC
WRITE OUT-REC.
200000-EXIT.
EXIT.
Get the details of employees of the employee numbers given in another sequential file.
SELECT IN-FILE ASSIGN TO INFILE.
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).
.
.
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
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.
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
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.
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.
9
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM
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.
1. SSN-NUMBER
2. TAX-NUMBER
3. PAN-NUMBER
4. PASSPORT-NUMBER
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.
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.
READ file-name
KEY IS Alternate-key-field
Through Rewrite statement, changing primary key is not allowed but changing alternate key is
allowed.
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.
12
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM
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.
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
13
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM
Data component
R R R C
LR1 LR2 … LRn FREE UNUSED D …….. D D I
SPACE SPACE Fn F2 F1 D
F
14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM
15
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM
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
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
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
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.
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
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
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)
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
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)
/*
20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM
//*
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)
21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com VSAM
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.
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
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.
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
3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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.
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
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
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
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
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
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)
/*
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
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 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.
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 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 |
-------------- --------------
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
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;
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';
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
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.
10
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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 .
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.
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
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.
Data type depends on the nature of the data itself and will always be one of two types NUMERIC
or CHARACTER .
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 .
13
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
A powerful database management language that performs the function of data manipulation, data
definition and data control and a non-procedural language.
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]
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.
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.
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;
Example:
CREATE VIEW EMP_VIEW
AS SELECT EMPNO,NAME,DEPT,JOB FROM EMPLOYEE.
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);
19
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
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.
20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
IN DBNAME.TSNAME;
21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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;
+------------------------------------------------------------------+
¦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
DEPARTMENT TABLE
+-------------------------------+
¦DEPTNO¦ DEPTNAME ¦ MANAGER¦
+------+---------------+--------¦
¦ 100 ¦ PRODUCTION ¦ 737466 ¦
¦ 200 ¦ ACCOUNTING ¦ 865403 ¦
¦ 300 ¦ PERSONNEL ¦ 491640 ¦
¦ 400 ¦ ENGINEERING ¦ 604985 ¦
+-------------------------------+
INSERT format1:
It assigns values to columns in the order the columns appear in the table.
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¦
+-------------------------------------------------+
25
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
+------------------------+
¦ 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.
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.
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¦
+------------------------------------------------------------------------+
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
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.
+-------------------------------+
¦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¦
+-------------------------------+
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 <=.
+------------------------+
¦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.
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.
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.
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
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.
Ex: To find the average salary of all employees from the EMPLOYEE table.
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
SQL only counts each different value once. There are 4 unique values.
DEPTNO
100 <----
500 <----
300 <----
100
300
100
200 <----
500
100
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.
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.
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.
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 .
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
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
36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
JOINS
SELECT * FROM PARTS;
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
37
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
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
39
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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;
EX: DELETE
FROM EMPLOYEE
WHERE EMPNO = 737654;
EMBEDDED SQL
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.
40
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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.
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.
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'.
42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
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
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).
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
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
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
OPEN cur1
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.
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
+-------------+
¦ 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)
+-------------+
48
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
49
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
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.
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
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.
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.
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
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.
54
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
Dynamic Sql
01 WS-STMT.
05 WS-STMT-LEN PIC S9(04) COMP.
05 WS-STMT-TEXT PIC X(50).
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.
Declare Cursor
EXEC SQL
DECLARE C1 CURSOR FOR 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)
DELETE grants the privilege to delete rows from the table or updatable view
. Ability to delete rows from table and updatable views
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
57
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
Examples:
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
Revoke
ALTER
CONTROL
DELETE
INDEX
INSERT
REFERENCES
SELECT
UPDATE (COLUMN)
Examples:
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.
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
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%'
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.
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
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
SYSIBM.SYSTABAUTH
It Records the privileges that users hold on tables and views
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
66
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
SYSIBM.SYSPACKAGE
It contains a row for every package
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
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
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
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)
/*
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.
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;
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.
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.
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
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.
3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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
5
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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.
7
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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
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
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.
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
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.
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
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
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.
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.
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 *
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
Named field goes to symbolic map. Unnamed field goes to physical map
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.
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
How to check if the field is updated or not when FSET and FRSET is used?
FSET FRSET
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
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
Cursor positioning
Cursor positioning
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
WHEN OTHER
PERFORM 300-INVALID-SELECTION
END-EVALUATE
. 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
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
20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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.
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
Output Fields
Field1O To send a value to the map field from application program
Basic Commands
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.
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
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
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.
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.
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.
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
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
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
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.
26
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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
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
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....
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.
28
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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.
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
29
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
Ex2: Read PREMMST and get the premium paid after 20110101 on policy P004
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.
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.
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:
Exp Conditions
INVREQ File is not write enable
DUPREC Duplicate record is found
NOSPACE No disk space available
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.
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
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.
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
IF AGENT-STATUS = 'T'
EXEC CICS DELETE
DATASET ('FILE1')
END-EXEC
END-IF.
Exp Condition
DUPKEY Duplicate key is found
NOTFND The record specified is not found
INVREQ If the file is not updatable
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
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.
Exp Condition
NOTFND -- The record specified is not found
INVREQ -- The file is defined no browse
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
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.
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
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
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
36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
Ex5: Get Premium paid after 20110101 on policy P001 from PREMMST.
37
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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.
If EIBAID = DFHENTER
PERFORM…
38
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
39
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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
40
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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 .
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
File layout:
01 POLICY-REC.
05 POLICY-NUM Record key
05 POLICY-STATUS
.
.
.
05 SSN Alternate key
42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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
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
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.
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).
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.
46
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
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.
47
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
48
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com CICS
CICS translation: This step comments all the CICS statements and replaces them with host language
CALL statements. This Step follows the above step
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