COBOL Course - Modules 1 Thru 12 - CICS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 610
At a glance
Powered by AI
The document discusses various tools and resources for learning and working with COBOL, including job searching, online courses, reference materials, and developing a personal brand.

Networking, the internet (job boards, search engines), degrees/qualifications, resumes/cover letters, and interviewing skills are mentioned as tools for job searches.

The formats mentioned include remote instructor-led training, hands-on workshops using an IBM mainframe system, and self-study of materials.

Enterprise COBOL

For Business Application Programming


August 20th 2020
IBM Trademarks and Copyrights
© Copyright IBM Corporation 2008 through 2020.

All rights reserved – including the right to use these materials for IDz instruction.

The information contained in these materials is provided for informational purposes only, and is provided AS IS without warranty of
any kind, express or implied. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to,
these materials. Nothing contained in these materials is intended to, nor shall have the effect of, creating any warranties or
representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement
governing the use of IBM software. References in these materials to IBM products, programs, or services do not imply that they
will be available in all countries in which IBM operates.

This information is based on current IBM product plans and strategy, which are subject to change by IBM without notice. Product
release dates and/or capabilities referenced in these materials may change at any time at IBM’s sole discretion based on
market opportunities or other factors, and are not intended to be a commitment to future product or feature availability in any
way.

IBM, the IBM logo, the on-demand business logo, Rational, the Rational logo, and other IBM Rational products and services are
trademarks or registered trademarks of the International Business Machines Corporation, in the United States, other countries
or both. Other company, product, or service names may be trademarks or service marks of others.
Thanks to the following individuals for their course contributions
• David Hawreluk/IBM
• Danny Amir
• Eran Lotan
• Tim McKeoun
• Karen G. Thomas/IBM Retiree
• Onno Van Den Troost/IBM
• Peter Haumer/IBM
• Alisa Morse/IBM
Thank you!
• Timothy Donnelly/IBM
• Lauren Li/US/IBM
• Greg Lambert/IBM
• Ken Taylor/IBM
• Richard Burford/COBOL and Assembler Expert
• Maria Cruz/COBOL Maintenance and Support Programmer 3
COBOL Course - Overview
Length:
• 24 Hours of Remote Instructor-Led class time
• 48 Hours of workshop/homework/quiz time required to read materials, create/run labs & answer questions

Format:
• Remote Instructor-Led Training
• Hands-on Workshops done using an IBM mainframe system in Dallas TX, U.S.

Book & Reference Materials


• Redbook on COBOL provided by IBM
• The course PDF handout – containing workshops, examples, terms, concepts & vocabulary
• Links to free online learning sources
• All the instruction in the course is done in English

Course Objectives:
• After successfully completing the course, attendees will be able to program simple (College-Level) COBOL programs, and advance to
more complex topics through independent study or some other learning venue

IBM Intermediate-Level eBadge: http://ibm.biz/EnterpriseCOBOLforBusinessApplicationProgramming 4


COBOL Course - Prerequisites
Minimum attendee qualifications:
• High School Diploma - with a high level of math competency
• Quality typing skills - speed & precision
• Basic PC, Internet, GUI tooling knowledge and skills
• Zip/Unzip
• Windows, Mac or Linux OS navigation, files/folders terms & concepts

PC/Laptop configuration:
• Windows, Mac or Linux
• Fast/Current CPU
• Min. 4GB RAM
• 8GB is preferable
• Min. 100 Megs Disk

• Connectivity to the Internet - with free & clear access to port 8080
• Note that some corporate Intranets may firewall off specific ports that may be needed for class

• Additional software installation will be required


If you intend to do the hands-on portion of the class you will need to find four
hours/week - over and above class time - to code and test your programs. 5
Syllabus
• About the course:
• https://community.ibm.com/community/user/ibmz-and-
linuxone/groups/community-
home?CommunityKey=b0dae4a8-74eb-44ac-86c7-
90f3cd32909a

• Detailed Syllabus:
• https://community.ibm.com/community/user/ibmz-and-
linuxone/viewdocument/enterprise-cobol-for-business-
appli?CommunityKey=b0dae4a8-74eb-44ac-86c7-
90f3cd32909a&tab=librarydocuments

• Additional Learning Resources for


DevOps/IDz
• https://community.ibm.com/community/user/ibmz-and-
linuxone/groups/community-
home/librarydocuments?LibraryKey=3bc593ed-04e0-
4cde-b23e-c6e326d591b5&CommunityKey=b0dae4a8-
74eb-44ac-86c7-90f3cd32909a

6
How to take this class
Course
1. Attend class: Workshops
Please mute your phones.
2. Do the workshops and
Application
--------------------------------------------------
Ask questions as they arise during
review questions
class - in the Webex Chat area.
3. Solidify and extend
In order to lock-down your learning
Read questions that others pose you have to code, build and test COBOL your COBOL knowledge:
programs. Read COBOL program code.
There are absolutely no silly
questions. There will be a number of conceptual Learn from the "Additional Learning
reviews on the language, tools or z/OS Tools" links at the end of each
environment. Use the internet/Google module - which point to free:
to search for COBOL topics.
• Video-based instruction
• Books & white papers on the web

IMPORTANT NOTE:
If while you are taking this class you find that you do not have time to complete the workshops between sessions, continue to attend class, ask
questions, go to the "Office Hours" weekly session and try to stay on track. Learning a software language is a cumulative/sequential process
(topics build upon one another). Please make every attempt to "keep up" with the materials.
7
Add more on PDS/PDSE

UNIT COBOL for z/OS - Module 1


Mainframe and I/T Terms & Concepts:
• What is the nature of?
• Software
• Hardware
• Computer Programs/ Application Programs
• Operating System
• I/O - Data Files & Data Bases
• What is an Algorithm?
• Source file ➔ Executable program
• Application programs vs. Systems programs
• Development, Maintenance and Production Support
work
• Accessing the mainframe:
• ISPF/3270
• ZOD/IDz
• VS Code/ZOWE
8
Why are you here?

…and what do you intend to


do with Enterprise COBOL
programming skills when
you finish this class?
9
Why are we learning COBOL - in June 2020?
From “Exactly what is COBOL and why is COBOL still a widely used language in IT?”
• COBOL Equates to 80% of the world’s actively used code: > 220,000,000,000 lines
• 200 times as many COBOL transactions take place each day than Google searches
• Every year, COBOL systems are responsible for transporting up to 72,000 shipping containers, caring for 60 million patients,
processing and connecting 500 million mobile phone users.

From “COBOL Is Everywhere. Who Will Maintain It?” Why is it that COBOL still supports large-scale,
complex, long-lived business computing? Even more
• About 95 percent of ATM swipes use COBOL code; Reuters
perplexing … how does a 60-year old software
• COBOL powers 80 percent of in-person transactions; Reuters language deliver 1.5B new lines of code - for the sorts
• Every day, COBOL systems handle $3 trillion in commerce of complex AppDev requirements that comprise 2020
production enterprise systems?
And from “The inevitable return of COBOL”
• 1,500,000,000 (1.5 Billion) lines of new COBOL written each year
• Graduates who take Cobol electives earn starting salaries of $75,000 compared to starting salaries of $62,500 for those
who did not; Wall Street Journal
• As many as 75% of all rewrite projects have resulted in failure [Reuters]
• When Commonwealth Bank of Australia replaced its core COBOL platform in 2012 it took 5 years and cost $749.9 million
10
What is a mainframe?

• IBM z14

Transmogrified…

- 146 Billion instructions/second


- Terabytes of file capacity/exceptionally fast I/O
- Most secure platform on the planet
- Integrates with virtually all modern software 11
What is z/OS?
• The operating system that runs an IBM System z
mainframe
COBOL Programs run as
Business Applications

Mainframe
systems are System Software is written and
maintained in Assembler
often referred
to as LPARs
"Logical Partition"

12
What kinds of files do mainframes support?
IBM System z handles an extensive variety
of data, file systems and databases:
• Sequential Files ("QSAM" … "Flat File"):
• Typically hold large amounts of business data in records that
are read and written consecutively
• Partitioned Data Sets ("PDS" … "PDSE" … or "Library")
• A collection of sequential files, all of the same type - contained
in a single file for convenient access - similar to a Windows folder
• Your COBOL programs
• Your Compiled/Linked Load Modules

• Indexed Files ("VSAM"):


• Files that can be accessed thru key value lookups - Dewey Decimal System
• Hierarchical Databases ("IMS" … "DL/1" … "IDMS")
• Business data accessed according to information rules that mirror a hierarchy
• Relational Data Based Management Systems (DB2, Oracle, Teradata, etc.)
• SQL Databases The I/O technology (capacity and speed) of System z are a
13 • Data Warehouses, Data mining, Analytics primary reason why COBOL programmers still roam the planet
What do the Compiler and Link Editor do?
• Like all computers, mainframes execute program binary
instructions - "machine code" - literally ones & zeroes
• Humans are much better at writing application business logic in
high-level, English-like languages - such as: COBOL, C, Java
• The COBOL Compiler converts programs written in COBOL into machine language
instructions - literally 1s and 0s: 101101000110111011110010111000101010110101100101110100101011
• The Link Editor converts the output from the Compiler into an executable format called a
"Load Module"
Process Produces Stored in
1.Write COBOL COBOL Source File Source Library (PDS)
program
2.Compile COBOL Object file Compiled Object
program Library (PDS) - or
simply deleted
3.Link-Edit Object Load Module - Load Library (PDS) Ready to be loaded into and executed on System z
file
14
What is JES?
• JOB Entry Subsystem - Subsystem of z/OS that
manages the resources of a mainframe LPAR that are
accessed by jobs run in "batch" mode
- Responsible for Batch Job management:
• JCL Reads and interprets JCL
• Queues and schedules jobs - based on work priority and file
availability
• Handles Job Output - "SPOOL" files Simultaneous Peripheral Operations on-line

• Manages disposition of programs and files after the Job ends

Offline (batch)
Files and
Databases
JCL JOBs
File access

Batch
Application
JES Submit Jobs
TSO users
Scheduling products 15
Program
What is JCL?
• Job Control Language - A scripting language - submitted to JES - that defines
the resources and requirements needed to run a batch application
• JCL is used universally on z/OS - during development, and running production.
• Because of its relatively short list of keywords, JCL can seem simple. But because it
has to tell z/OS everything about a job; What to do with files - with subsequent
programs - How to handle program failures - etc. "production-level JCL" can be
anything but simple.
• A JOB named "MYJOB"
• Comprised of a single STEP: "MYSORT"
• Which invokes a z/OS "sort" routine
• The sort routine expects to find four file
declarations (DD Cards)
• The sort input is the file: zprof.area.codes
• The sort output is written to a special type of file
associated with the JOB called a "spool file"

• https://en.wikipedia.org/wiki/Job_Control_Language
• https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zconcepts/zconc_whatisjcl.htm 16
What are Business Applications?
• Custom software that automates a
company's "business rules":
• How business a company's business is transacted

• Business Applications are based on:


• A company's commercial policies and procedures
• The meaning (semantics) of data and the operations on a company's data
• COBOL has been the business application software
language of choice since 1960
• The "shelf-life" of business applications written in COBOL can be anywhere
between 10 and 40+ years
17
What is COBOL?
• COmmon Business-Oriented Language
• COBOL (all caps) is an English-like computer language designed
specifically for writing Business Applications that run on IBM
mainframes. The language per se is legislated by a vendor
neutral committee called the ANSI committee.
• Since the 1960s corporations have built & deployed COBOL business applications on
mainframe computers - as they do to this day - because of COBOLs Runtime-Speed,
Reliability, Security, Capacity - the language's fit for purpose.
• The types of business applications COBOL is used for include:
• Batch jobs:
• Reports, Audit,
• Payroll, Accounting, Finance
• Banking, Insurance, Manufacturing, Retail, Government - all vertical markets
• Online - transaction processing
Note that this class utilizes IBM Enterprise
• ATM COBOL Version 6.2 - your shop may be on a
• Credit Card Transactions different COBOL level, but material covered in
• Airline Reservations this Entry Level course will most likely apply. 18
Who develops COBOL Programs?
Application developers
write business logic in
COBOL

End Users define the


business specifications for
the COBOL applications

System programmers install,


configure and maintain z/OS
and Systems Applications

https://onezero.medium.com/ibm-rallies-cobol-engineers-to-save-overloaded-unemployment-systems-eeadf13eddce
19
How are COBOL Applications Developed?
1. Developers receive programming specifications from a systems analyst or application
architect. They read every last word of the document.
• And when they fully-understand the "spec" they launch their development tools (IDE)
2. They access the programs to change or they create new programs. Programs are stored in a
PDS (Library) sometimes referred to as a: "Source Code Library"
3. They code solutions using "algorithms" or "coding patterns". If the requirements are
complex they can use Flow Charts or Pseudocode to visualize the solution.
4. After coding, they "Build" ("compile & link") the program to create an executable
5. They Unit Test their work
• If the program is part of a Batch they run "JCL" to test their program
• If the program runs "Online" they will work with Systems Administrators to setup their testing
• They may need to create new test data in order to do this step
6. When their code passes the Unit Tests
• They move the code to the next phase of testing - typically "Integration Test"
Program documentation is
• They document their development work. Many shops require developers to the only means of describing
"document as they go" - adding COBOL comments while doing step 3 above "WHAT" a program does. 20
What kinds of work do COBOL programmers do … in 2020?

• The vast majority of COBOL


New • Create brand new COBOL code -
projects involve maintaining starting from business requirements
existing production programs
COBOL
• These programs are Development
typically:
• Between 10 and 40 years old


Between 5K and 20K LOC
Structurally complex Application • Support "production" jobs
and transactions - where the
• Critical to the business corporate business is run

Production Support
• Enhance and Modify
existing code

Program Maintenance
21
COBOL Program Source Files - Storage and Management
In this course you will create and access
COBOL programs that are stored as
"members" in a PDS (Library)

ZOD Source
Server
Control
Management
System

zserveros
Corporations often employ products called "Source Control Management Systems" (SCM)
These products store and manage program files - they govern application updates and version
control - automate Compile/Link and more. They are considered a necessity in large COBOL
programming shops where hundreds of developers change software daily. Git is one such SCM.
22
Development Toolsets (IDEs)
Integrated Development Environment

VS Code Z Open Editor


ISPF
Z Open Development (ZOD)

IBM Developer for z Systems (IDz)


What tools are available in ZOD/IDz?
• Mainframe "explorer" - GUI access to files, programs, jobs and other mainframe resources
• Intelligent editors - that provide COBOL-language-specific code development
• Debugger - the means of understanding the code you've written as it's executed by z/OS
• DevOps tools - that integrate with modern development strategies and project work

The ZOD Debugger


Which displays your code
as it executes line-by-line

24
"Online" …vs… "Batch"
The speed and capacity of z/technology allows LPARs to provide mainframe cycles to different environments
simultaneously. Environments such as Production vs. Test …and… Online vs. Batch Processing
• Online systems provide real-time access to applications that process business transactions in < 1 second
• Credit cards and ATMs
• Airline reservations
• Batch systems are launched by Jobs that are submitted (by you or a scheduling product) .Upon launch, Jobs
are prioritized, scheduled, executed and managed by JES - the Job Entry Subsystem

Online Systems–TP Region(s) Batch Region(s)


Online application users
JCL JOBs

JES
Online COBOL Developers
Online
Online
Applications Job Scheduler
Applications z/OS
Applications
z14 Batch
Online Batch Offline
Files and Region Supervisor Batch
Jobs Files and
Job
Databases CICS or IMS TM Jobs Databases
"Production" …vs… "Test"
• Production LPARs - The platform and environment that services customer-facing business applications:
• Online Transactions that interface with people doing business

• Batch Jobs that process data for reports, analytics and other corporate data requirements

• Test LPARs - The mainframe system where you code, build/test the business applications that will eventrually run "in production"

Test ➔

Separate and
complete
computing
environments
26
What sources are available for learning more about z/OS & COBOL?
• IBM Knowledge Center
• You just knew this was going to be the first option
• But in fact, the information in the Knowledge Center on COBOL, z/OS, ISPF and System Z topics is terrific - well-organized & search-able

• Free Video-based Instruction


• A plethora of sites and offerings - many quite good
• Some are "bait-and-switch" (caveat emptor)

• For-pay Video-based Instruction


• A number of quality vendors provide on-site training
• Benefits include actual/immediate instructional feedback loop, content & scheduling customization

• For-pay Classroom Instruction


• On-site ("F2")
• Remote Instructor-Led

• Free Books
• A few COBOL and z/OS books on the web
• Have not found an absolute ton of quality

• (not) Free Books


• Some excellent COBOL learning materials
• See links ahead in these slides
• Buying used is not a stupid way to go 27
Module 1 - Summary
In this module you were introduced to the basics of mainframe systems.
There is an enormous amount of additional tech-information about System z -
Linux, Unix, z/OS, I/O, file systems & databases, CICS, IMS, etc. that lies ahead.
But for the purpose of learning Enterprise COBOL this module was a start
• Businesses depend on COBOL for their success.
• The COBOL language defines the business rules for application software.
• COBOL programs written more than 40 years ago continue to be valuable and run businesses today.
• COBOL works hand-in-hand with JCL to exploit the mainframe environment.
• After learning the COBOL language, one must gain experience in the unique business environment for the
COBOL application
• COBOL programming today consists primarily of maintaining and supporting existing production applications
• Every shop will have a formally prescribed method of developing COBOL applications - called a Software
Development Life Cycle (SDLC)
• The SDLC will include:
• Tools used
• Steps and procedures for developing code, testing code, storing code and working on project teams

• You will have to choose and install a tool (client IDE) for this class - unless your company already has one 28
Supplementary Learning Links for this class - 1 of 4
Why Mainframes ….. And all about Mainframes
• https://www.ibm.com/it-infrastructure/servers/mainframes - Primary IBM mainframe web page

• https://www.youtube.com/results?search_query=Why+mainframes - YouTube search on "why mainframes"?

• https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zmainframe/zconc_whousesmf.htm - Excellent primer on "why mainframes"?

• https://mainframedebate.com/2017/03/10/in-the-beginning-a-history-of-the-io-channel/ - Tech white papers


• https://www.youtube.com/watch?v=eGlC3WXL8FQ - Lengthy and deep presentation on mainframes

• https://en.wikipedia.org/wiki/System_software - Systems Software (technical deep-dive - over and above what's necessary for this class)

Why COBOL ….. And all about COBOL


• https://freedomafterthesharks.com/2016/06/27/exactly-what-is-cobol-and-why-is-cobol-still-a-widely-used-language-in-it/

• https://devops.com/the-beauty-of-the-cobol-programming-language-v2/

• https://www.youtube.com/results?search_query=why+cobol

• https://developer.ibm.com/mainframe/2019/02/26/cobol-and-the-enterprise-business-programming-paradigm/

• https://www.bi4all.pt/en/news/en-blog/is-cobol-still-alive/

• https://en.wikipedia.org/wiki/COBOL

• http://www.simotime.com/sim4home.htm

• https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zmainframe/zconc_whousesmf.htm

• http://www.isedj.org/1/52/ISEDJ.1(52).Carr.pdf Note that these site links are not


• https://www.tutorialride.com/cobol/cobol-tutorial.htm IBM endorsements - they are
29
simply lists of internet resources
• https://towardsdatascience.com/forget-about-python-learn-cobol-and-become-a-crisis-hero-7f15e75ff377
Supplementary Learning Links for this class - 2 of 4
The IBM Redbook Series on z/OS, ISPF and JCL
• PDS: https://www.youtube.com/watch?v=brXvCnFrDdM

• COBOL program naming conventions: https://www.youtube.com/watch?v=WqL3oghmocc

• Access to TSO: https://www.youtube.com/watch?v=ted-xhdG2_s

• Enterprise z/OS overview; https://www.youtube.com/watch?v=pcNQ2GJ5N1w

• Everything mainframe: https://www.youtube.com/watch?v=pcNQ2GJ5N1w&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM

• TN3270 https://www.youtube.com/watch?v=GD_9SF69yzU&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM&index=5

• TSO: https://www.youtube.com/watch?v=hpVYPGMtgcQ&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM&index=6

• ISPF: https://www.youtube.com/watch?v=vrCqIaB_23U&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM&index=7

• ISPF/Editor: https://www.youtube.com/watch?v=1PI3AQ20sEI&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM&index=8

• SDSF: https://www.youtube.com/watch?v=S4apMxxXlyM&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM&index=9

• JCL: https://www.youtube.com/watch?v=LNFqR2MWOxg&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM&index=17

• JES: https://www.youtube.com/watch?v=16qQvwIETAY&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM&index=18

• JES: https://www.youtube.com/watch?v=9w6duPvzgaY

30
Supplementary Learning Links for this class - 3 of 4
IBM Academic Initiative Series - a deep-dive into z/OS and System z
• https://www.youtube.com/playlist?list=PL-LacKscR5B3zSpro8PCHQMRFepH6rWJT
• http://wwwlgis.informatik.uni-kl.de/cms/fileadmin/users/kschmidt/mainframe/lutzkuehner/Chapter03_zOS_Intro_Foils.pdf -
Excellent z/OS Admin slide deck

Job Control Language: JCL - an excellent online tutorial into this critical topic
• https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zjcl/zjclc_basicjclconcepts.htm

VS Code/ZOWE - links for installing and using this IDE during class
• https://www.youtube.com/watch?v=SdUsAI52QmY
• https://www.youtube.com/watch?v=la1_Ss27fn8
• https://www.youtube.com/watch?v=77o14aHUuSo
• https://youtu.be/G_WCsFZIWt4 - Installation

IBM's IDz and ZOD resources - learning videos, training, product downloads, blogs, announcements
• https://developer.ibm.com/mainframe/idzrdz-remote-training/
• https://developer.ibm.com/mainframe/idz-learning-portal/ 31
Supplementary Learning Links for this class - 4 of 4
• Mainframe COBOL textbook:
• https://www.murach.com/shop/murachs-mainframe-cobol-detail

• Tutorials Point - a quality series of COBOL language videos:


• https://www.youtube.com/playlist?list=PLWPirh4EWFpEwRypgRSofF7Ui91yeCeMi

• Another excellent set of language learning web-ages:


• https://riptutorial.com/cobol

• More COBOL learning and example pages:


• http://www.techtricky.com/cobol-date-functions-list-add-find-duration
• https://www.codepoc.io/tutorials/cobol/23/basic-programming
• http://www.mftutor.com/length-function/
• https://mainframe-forum.blogspot.com/2013/08/inspect-in-cobol-example-cobol-inspect.html

• University of Limerick - a series of online PDF lessons backed by coding examples *** *** Course built using a PC COBOL product or environment
• http://www.csis.ul.ie/cobol/

• A comprehensive video series on LinkedIn ***


• https://www.linkedin.com/learning/learning-cobol/introduction-to-cobol

• Another comprehensive series on COBOL:


• http://www.mainframegurukul.com/tutorials/programming/cobol/cobol-tutorial.html?ref=hackr.io

• A two-hour video on simple COBOL constructs used to create and run programs ***
• https://www.youtube.com/watch?v=TBs7HXI76yU Note that these site links are not
• An aggregation page from various sources on COBOL instruction: IBM endorsements - they are
• https://hackr.io/tutorials/learn-cobol 32
simply lists of internet resources
Module 1 - Review Questions
• Define the following:
• COBOL
• CICS
• Business Application Programs
• System Software
• z/OS
• Data Files & Data Bases
• Source file
• IMS/TM
• Program design algorithm
• JES
• JCL
• The ZOD Remote Systems view

• What is the difference between: Google any of the terms & concepts before Module 2 to
cement your learning.
• A source file and an executable program
• A PDS and Sequential file
• A batch program and an online program
• Program Development, Maintenance and Production Support 33
Workshop: Install ZOD on Windows using P2 - 1 of 3

• From: https://developer.ibm.com/mainframe/products/downloads/eclipse-tools/
• Scroll down the page - find the entry for IBM z/OS Open Development  Check the box then click Select

• Click Select for Aqua 3.2 (Eclipse Photon v4.8)

• Click Select for Eclipse p2


Workshop: Install ZOD on Windows using P2 - 2 of 3

• Click Select for Starting from fresh

• Click either the 32-bit (older machines)


or 64-bit (newer machines)

• Click on "I agree" or "I do not agree"


• Note that the Download requires "agree"

Important note: If given the choice Save the download file (select: Save not Open)
Workshop: Install ZOD on Windows using P2 - 3 of 3

• ZOD will begin downloading


• Note that this will take several minutes
depending on the speed of your machine
and your network.

• After the download finishes unzip the file into a


directory on your PC
• Use Windows Extract All, 7-Zip, etc.

• After the unzip finishes open the folder you unzipped the file into
• Double-click: Z_Open_Development.exe
Workshop: Launch ZOD
When you launch ZOD it will prompt you for a Workspace. Select the default directory.
The first time you launch ZOD it will take a few seconds to finish configuring. You'll be prompted to choose a
backdrop (theme), Secure Password Hint, etc. These choices are up to you.

1. After the product finishes configuring, you'll see a "Welcome Page" - which you should close.
2. Next open the z/OS Projects Perspective from the Window menu

3. From the menu select:


- Window ➔ Perspective ➔ Open Perspective ➔ Other…
- Scroll down and choose: z/OS Projects
If you choose a white background ZOD should look like this
after you've selected the z/OS Projects Perspective
Workshop: Connect to your mainframe
To do the workshops in the course, you will need to login to a TSO account:
1. From Remote Systems/New Connection Double-click: z/OS…

2. Enter the Host name: zserveros.centers.ihost.com - and click Finish


3. Right-Click over your new connection and select Connect
4. Enter the User ID: and Password you received from IBM in an eMail
5. Click OK
Click OK at any other pop-up prompt

Note: If you're using another mainframe in


class you will need its Host name and Port#
Workshop: Explore files on your mainframe
Your instructor will have created a
number of files for you on zserveros.

The files can be seen and accessed


using the Tree-Control within your
connection in Remote Systems
• Expand MVS Files
• Expand "My Data Sets"
• Scroll up and down
UNIT COBOL for z/OS - Module 2
z/OS IDE and Development tools:
• Mainframe Environment:
• Your code libraries:
• COBOL
• JCL
• Jobs and Job results (SYSOUT)
• Exploring the tools in your z/OS IDE
• Exploring your mainframe

In order to become productive writing COBOL code and finishing the workshops in this
course, please spend time using your Client IDE (ZOD, IDz, Zowe, or ISPF)
Navigation, Edit, Compile/Link/Go, Accessing Batch Job output, Debugging
40
Client tools and this course
• To do the labs and workshops in this course you may use one of several
client IDEs:
• ISPF - thru 3270 Emulation
• IDz - IBM Developer for Z Systems
• ZOD - Z Open Development
• VS Code/Zowe

ISPF
• Cannot use the IBM zserveros mainframe
• Must use your company's machine
IDz/ZOD
• Probably cannot use your company's mainframe
• Although some shops may have the server installed
• The IBM machine supports both products
VS Code/Zowe
• Cannot use zserveros
• Probably cannot use your company's machine
• Might be able to use the Master-the-Mainframe machine

41
ISPF and COBOL
To get a job in the COBOL industry you will need
quality ISPF development skills and techniques:
• Connecting and setting ISPF preferences
• ISPF Vocabulary and navigating the ISPF "Dialogs"
• Browse/Edit Files =1 and =2 Note that for ISPF you will need to use
• Especially ISPF Editing techniques your own mainframe for the workshops
• Compile/Link =4 - an understanding of the panels
ISPF is accessed using "3270-Emulation"
• SDSF - Batch Job Output - Navigation and usage
• How to run REXX and CLIST apps =6
• The Data Set Utilities panel =3.x
• And other ISPF-based tools such as: DB2I/SPUFI, File Manager, etc.

• There are several free and/or reasonably-priced 3270-emulation packages available:


• https://sourceforge.net/projects/x3270/
• https://www.ericom.com/solutions/tn3270/

Also - note that ISPF is covered during week 10 of the class 42


ISPF 3270-Users and this Class
If you intend to use ISPF to do the workshops/labs in this course - and you don't
already have ISPF experience, there are a number of excellent - and free - web-based
tutorials available:
• ISPF "A-Z" https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zcourses/zcourses_ispfintro.htm
• The PDFs may be easier to learn from
• ISPF Basics (YouTube): https://www.youtube.com/watch?v=vrCqIaB_23U&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM&index=7
• ISPF/Editor (YouTube): https://www.youtube.com/watch?v=1PI3AQ20sEI&list=PLnJzIOiv6cVTEMMtbyo_UnQQ_JHCA9FqM&index=8

As mentioned on the previous slide, you will need to be able to:


• Connect to TSO/ISPF - understand the navigation model, how to access the dialogs, and use the
primary PF-Keys: F3, F5, F6, F7, F8
• You must be able to edit the source files in your LEARN.COBOL libraries
• You'll need to know how to use your "compile PROC" panels to Compile/Link and Run your programs
• And how to submit batch jobs and access their output - from either:
• SDSF
• Outlist
• How to debug your code
• And how to use the =3 (Data Set Utility panel) to; Allocate new data sets, copy files, delete and
rename data sets 43
VS Code/ZOWE and this Course
• The IBM Z Open Editor is a free extension for
Visual Studio Code (VS Code) that provides
language support for COBOL, PL/I and JCL.
• Along with this language support it also
provides content assistance for applications that
call CICS, MQ, IMS and DB2 APIs. If you want to use VS Code/Zowe you will need to
use your own mainframe for the workshops and labs

VS Code/ZOWE - links for installing and using this IDE during class
• https://github.com/openmainframeproject/cobol-programming-course/blob/master/COBOL%20Programming%20with%20VSCode.md -
Using VS Code to develop COBOL applications
• https://www.youtube.com/watch?v=SdUsAI52QmY - "Master the Mainframe" and VS Code
• https://www.youtube.com/watch?v=77o14aHUuSo - A YouTube video using VS Code for COBOL development
• https://youtu.be/G_WCsFZIWt4 - How to install the ZOWE Explorer
• https://ibm.github.io/zopeneditor-about/ - Primary IBM Z Open Editor page

A series of installation & configuration steps for VS Code/ZOWE are on the


next three slides. 44
Instructions to experiment with IBM Z Open Editor
These instructions are provided to introduce you to the new IBM Z Open Editor, in • Continue with the instructions on creating a connection to z/OS. The steps for creating
conjunction with Zowe Explorer, to allow you to experience its powerful capabilities for IBM a connection in Eclipse Che can also be applied to VS Code.
z/OS development and processing. IBM Z Open Editor and Zowe Explorer are extensions
for Microsoft Visual Studio Code (VS Code) that can be downloaded for free from the VS • Note: For the question about base path, you can leave this blank and press Enter
Code Marketplace. to continue.

• IBM Z Open Editor provides language support for COBOL and other IBM Enterprise • While Step 5 of creating a connection shows how to add the same connection to
languages. `USS`, you can use the same steps to add the connection to the `JOBS` view as
well.
• Zowe Explorer provides remote access to z/OS systems via VS Code’s graphical
user interface. 3. Open the course files

** Items to note when running this exercise: • You can get a local copy of the course files by downloading and unzipping the COBOL
Course Setup Zip File: https://community.ibm.com/community/user/ibmz-and-
• Since IBM Z Open Editor has not yet integrated with Debugger, the COBUCLD JCL linuxone/viewdocument/cobol-course-setup-zip-file-for-c?CommunityKey=b0dae4a8-
has not been included. 74eb-44ac-86c7-90f3cd32909a&tab=librarydocuments
• The editor also does not yet handle files that contain COMP fields and contains no • In VS Code, open the local folder where you placed the course files: File > Open
HEX value view. Folder.

1. Open VS Code 4. Follow the steps on the next slide to upload/create the course files from your local
directory to the mainframe
• Search for IBM Z Open Editor in the VS Code Marketplace
(https://marketplace.visualstudio.com/items?itemName=IBM.zopeneditor). • Note that there are three sets of files to upload/create:
• Please read the Details tab where you can find a link to full documentation and the i. Upload the COBOL, COPYLIB, and JCL files
Prerequisites required to use the extension.
ii. Create the OBJ and LOAD datasets
• Install the IBM Z Open Editor VS Code extension. (Zowe Explorer will automatically
be co-installed if it is not already on your system.) iii. Upload the data files

2. If you do not have access to a z/OS system with z/OSMF enabled, you can request • (Continued on next slide.)
an ID to IBM's Master The Mainframe host:
• Follow the instructions in the link above to obtain a user ID and activate z/OSMF.
(URL: https://developer.ibm.com/mainframe/2019/12/11/ibm-z-open-editor-in-the-
cloud-with-eclipse-che/#optional-exploring-zos-using-zowe-explorer)
• Note: For Step 5, enter “activate zosmf” (without the quotes) into the bot's chat
instead of entering your username. The bot will then prompt you for your user ID.
• After entering your user ID, you will receive a message that your ID has access to
Zowe.

45
Instructions to experiment with IBM Z Open Editor - continued
4. (Continued) Follow the steps below to upload/create the course ii. Create the OBJ and LOAD datasets
files from your local directory to the mainframe
• zowe files create pds '<userid>.COBOBJS.OBJ'
Notes:
• zowe files create pds '<userid>.LEARN.LOAD' --rf U --rl 0 --bs 4096
• Replace instances of <userid> in these steps with your actual user ID.
• In the Terminal window, cd to the directory where the files are located.
iii. Upload the data files
• Note for RSE API users: If your host has RSE API enabled, you can run
the commands against RSE by simply replacing files with rse. • Notes:
o You can upload all data files at once, or only the ones that are required for the program you are
i. Upload the COBOL, COPYLIB, and JCL files currently working on.
o Uploading all data files at once will prevent you from having to comment out DDNames in the
A. Option 1 - Zowe Explorer COBUCLG JCL. If you upload them only as you need them, then you will need to comment out any
• In the `DATA SETS` view, place the cursor over the connection DDNames and instream data in the `GO` step of the JCL for any files not yet uploaded.
o To comment out a line in JCL, insert an * in column 3 of that line.
name.
• Use the Terminal to cd into the DDS0001.LEARN.DATA.FILES directory, and use the following commands
• Click on the `Create New Data Set` icon. to upload the data files:
• Select `Data Set Partitioned`. • zowe files create ps '<userid>.LEARN.INSCLAIM' --rl 90 --bs 9000
• zowe files ul ftds 'DDS0001.LEARN.INSCLAIM' '<userid>.LEARN.INSCLAIM'
• Enter a data set name such as: <userid>.LEARN.COBOL
• zowe files create ps '<userid>.LEARN.ACCT.DATA' --rl 170 --bs 1700
• Right click on the newly created PDS. • zowe files ul ftds 'DDS0001.LEARN.ACCT.DATA' '<userid>.LEARN.ACCT.DATA' --binary
• Select `Upload Member`, and then select the member(s) you want • zowe files create ps '<userid>.LEARN.OUTFILE' --rl 178 --bs 1780
to upload from the local folder and click `Upload File`. • zowe files ul ftds 'DDS0001.LEARN.OUTFILE' '<userid>.LEARN.OUTFILE'
• Repeat these steps for COPYLIB (<userid>.COBOL.COPYLIB) • zowe files create ps '<userid>.LEARN.PAYROL01'
and JCL (<userid>.LEARN.JCL). • zowe files ul ftds 'DDS0001.LEARN.PAYROL01' '<userid>.LEARN.PAYROL01'
• You can view all data sets for your user ID by clicking the • zowe files create ps '<userid>.LEARN.INVALS'
magnifying glass icon by your connection name, and then entering • zowe files ul ftds 'DDS0001.LEARN.INVALS' '<userid>.LEARN.INVALS'
<userid>.* as your search term.
• zowe files create ps '<userid>.LEARN.FAVIN'
B. Option 2 - Zowe CLI • zowe files ul ftds 'DDS0001.LEARN.FAVIN' '<userid>.LEARN.FAVIN'
• In the Terminal window, enter the following commands: • zowe files create ps '<userid>.LEARN.B37'
• zowe files ul ftds 'DDS0001.LEARN.B37' '<userid>.LEARN.pro'
• zowe files create pds '<userid>.LEARN.COBOL'
• zowe files create ps '<userid>.LEARN.PAYCHECK.DATA'
• zowe files ul dir-to-pds 'DDS0001.LEARN.COBOL' • zowe files ul ftds 'DDS0001.LEARN.PAYCHECK.DATA' '<userid>.LEARN.PAYCHECK.DATA'
'<userid>.LEARN.COBOL'
• zowe files create ps '<userid>.LEARN.PAYROL3A' --rl 90 --bs 9000
• Repeat these steps for COPYLIB ('<userid>.COBOL.COPYLIB') • zowe files ul ftds 'DDS0001.LEARN.PAYROL3A' '<userid>.LEARN.PAYROL3A'
and JCL ('<userid>.LEARN.JCL’).
46
Instructions to experiment with the IBM Z Open Editor – continued (2)
5. Follow course instructions for editing COBOL programs
6. Edit, Submit, and View Job Output
Edit the JCL
• Open <userid>.LEARN.JCL(COBUCLG) from the Zowe `DATA SETS` view.
• Edit the JCL as per the course instructions and save.

Submit the JCL


• In the Zowe `DATA SETS` view, right click on the COBUCLG member and select `Submit Job`.
• Take note of the job number (JOBxxxxx) in the message box in the lower right corner of the screen.

View JOBS
• In the Zowe `JOBS` viewer, click on the Search icon.
• Select `Job Id search` from the selection list.
• Enter the job number: JOBxxxxx
• The job displays in the view.
• Expand the job to see the JES files.
• Click on the appropriate DD file to view job output.
• If you are not seeing an anticipated job file, you may need to refresh your `JOBS` view.

Helpful links:
• IBM Z Open Editor documentation: https://ibm.github.io/zopeneditor-about/Docs/introduction.html
• Installing Zowe CLI : https://docs.zowe.org/stable/user-guide/cli-installcli.html
• Using Zowe CLI: https://docs.zowe.org/stable/user-guide/cli-usingcli.html
47
ZOD Architecture
ZOD is a modern GUI Integrated Development Environment for z/OS business
application development
▪ Runs on Windows, Linux, or Mac
▪ Integrates with a company's existing TSO/ISPF Application Development tools

ZOD interacts with z/OS through a host-based listener/server

Mainframe Resources

ZOD Client Software


z/OS Listener
"Started Task"
• z/OS Data Sets
- COBOL Programs
I/O • JES
• Jobs and Job output
• Online resources
• SCM
• REXX (similar to .bat files)
Security/Authorization
Compile/Link
 ZOD Terms and Concepts: “Workspace”
• When you launch ZOD it prompts you for a "workspace"
• Which is simply a folder on your workstation that contains the ZOD
development environment meta-data:
• "Workbench state” – how things looked when you last closed ZOD
• Your preferences and settings
• Connections to your mainframe
• …
Workstation
Hard-drive

 C:\your_PC.zod
C:\your_PC.zod

Default ZOD
Workspace 49
Connect to zserveros - Review
To do the workshops in the course, you will need to login to the TSO account:
1. From Remote Systems/New Connection Double-click: z/OS…
2. Enter the Host name: zserveros.centers.ihost.com - and click Finish
3. Right-Click over your new connection and select Connect
4. Enter the User ID: and Password you received from IBM in an eMail
5. Click OK
Click OK at any other pop-up prompt

Note: If you're using another mainframe in


class you will need its Host name and Port#
Workshop: Explore your files on zserveros
Your instructor will have created a
number of files for you on zserveros.

The files can be seen and accessed


using the Tree-Control within your
connection in Remote Systems
• Expand MVS Files
• Expand "My Data Sets"
• Scroll up and down
 IDE Terms and Concepts - ZOD View
ZOD is organized as a collection
of tabbed resize-able windows
called Views

Views display information or


provide access to ZOD functionality Remote
specific to the View title (tab): Systems
z/OS View
- Remote Systems
Projects
Views
- Projects
View
- Syntax errors

- Program Outline

- Analysis tools

- Debug Monitors

- etc.

Properties View

All of the Views that you see above, are organized into a
ZOD Perspective
 IDE Terms and Concepts - “Perspective”
A Perspective is a named collection of Views organized around a given development task: Debugging
programs, Writing/Testing COBOL, Modifying mainframe files, ABEND resolution, etc.

Work with Perspectives starting


from the Window menu
• Open
• Reset

z/OS Projects Perspective


– Tools for z/OS project work:
▪ Access to datasets and Jobs
▪ Editors
▪ Syntax Checking and Compiling source
▪ Search
▪ Etc.
 IDE Terms and Concepts - “Context Menu”
You will frequently access the “Context Menu” by: 1. Selecting something then
2. Pressing the Right-Mouse button


Right-mouse or "Context" Menu
Speedy access to the available actions
specific to the selected element:
▪ Delete
▪ Search
▪ Move
▪ Copy
▪ Rename
▪ …
54
ZOD and your files on the IBM mainframe (zserveros)
Your instructor will have created a
number of files for you on zserveros
belonging to your TSO-ID:

Remote Systems View

LPAR Connection

MVS Files ➔

Your TSO-ID
Your Files
The files can be accessed using the
tree-control within your connection in
Remote Systems
• Expand MVS Files
• Expand "My Data Sets"
• Scroll up and down
• Double-click to expand a PDS and open
a file into the ZOD editor
 z/OS Terms and Concepts - “Partitioned Data Set”
In this course you will create and access PDS
COBOL and JCL files that are stored as
members in a PDS (Library)
PDS

Partitioned Data Set: Also called a PDS or Library z/OS resources Rendered in
ZOD as a Tree Control
• Consists of 0 ➔ many individual files - called "members"
• Plus an Index used to access individual PDS members RTPOT39.LEARN.COBOL
A PDS is similar to a PC folder
A PDS holds "source files"
• Your COBOL programs
• JCL files
Your executables ("Load Modules") reside in a PDS
in a "Load Library"
 ZOD Terms and Concepts - “Remote Systems”
The Remote Systems "tree control" organizes and
displays links to your data sets:
• Libraries - which expand to show the individual PDS member

z/OS Resources Available Through Your Connection


names
• Sequential and Indexed Data Sets

Libraries

COBOL Programs
Library Members
• Jobs submitted to the Job Entry Subsystem (JES)
• "My Data Sets"
• An MVS "File Filter" that displays only resources with your TSO ID

Sequential Datasets
in the first qualifier
• We will show you how to create MVS File Filters later in this course.
Navigate within DSN list
Navigate within PDS member list

JES Job
Output
Navigate up/down the list of data sets 57
Editing z/OS Files - Opening a file in the Editor
From Remote Systems…
Find the file you want to edit:
-Double-click the PDS member name …or…
-Right-click and select: Open



58
Navigating within a source file

PC Keys:

Up-down slider bar


• PgUp
• PgDn
• Ctrl/Home
• Ctrl/End
Scroll
 Wheel

Using your mouse:


1. Move the slider bars:
▪ Up and down
▪ Right and left Left-right slider bar

2. Left-click the “up and down” scrolling arrows:


▪ To scroll one line at a time through the source file
3. Click your mouse inside the source:
▪ Use your Mouse Wheel to scroll 3 lines at a time
Editing source files - 1 of 2
MS-Windows style editing operations:
▪ Enter - opens a new line
▪ Hot-Keys abound:
▪ Ctrl+S
▪ Ctrl+A
▪ Ctrl+C
▪ Ctrl+V
▪ Ctrl+Z
▪ Ctrl+F (Find/Replace) ➔
▪ Shift+End
▪ Shift+Home
▪ Shift and PgUp
▪ Shift and PgDn
▪ Etc.
▪ Many COBOL-specific features
▪ Click a "variable" - selects (marks) all other variables in the file
▪ Expand/Condense COBOL "paragraphs"
▪ Block Editing - available on the toolbar
Editing source files - 2 of 2 - COBOL Features

ZOD features a large number of time-saving


COBOL and JCL advanced editing tools:
▪ Hover over a "variable" displays its definition

▪ Typos "syntax errors" are caught during typing

▪ Tooltips suggest different keywords and variables

Tooltip
▪ Intellisense typing ("Content Assist" in this class) -
is available for code development:
▪ By pressing Ctrl+Spacebar, ZOD will suggest different
keywords and variables to add to the text
Space
+ bar
Resizing and Closing a ZOD View
You might wish to see more program source at-a-glance.
There are several ways to do this, but the easiest way is to Resize the view by
dragging the view frame:
- Move your mouse-cursor over the right-hand border of the editor window
It will turn into an East-West facing pointer 

- When the cursor point changes shape:


- Left-click, and holding the left-mouse button down, drag to the right or left and resize the view

You can also select the bottom window border. Left-click and hold + drag to make the window's height larger

Close the editor by


Closing a View ➔ clicking the Red X

• Note that if you’ve made any changes to a file in the editor, you will be prompted to save 62
Maximizing and Restoring ZOD Views
It's often useful to maximize
and restore views for various
development tasks.

• Steps: 

• To maximize a view:
• Double-click in the
middle of the view tab

• You can also click the


Maximize icon in the
top-right hand corner of
the view

• To restore all views:


• Double-click (again) in


the middle of the tab

• Or click the Restore icon


on the far right of the
Editor 63
Split Screen - Different views of a single program

Same program file

Split in two different frames

Synchronized updates between frames

Maximize/Restore View
For Full-Screen Work

64
Resetting the z/OS Projects Perspective
When you're first getting used to new software, it's easy to do things inadvertently – like close views, or
resize them – making the views too small or too big, etc.

To restore your workbench to its last-saved GUI state access the Window menu and Reset your
Perspective:

Steps (do the following):


• Close a few of the views
• Resize the editor or some other view
• Now:
1. Left-click the Window menu
2. Click:

• Perspective >
• Reset Perspective…
• At the prompt, click Yes

65
Create a new file by Copy/Pasting an existing file

From Remote Systems:


▪ Find the file you want to clone (copy verbatim)
▪ Right-click the file and select Copy

▪ Right-click on the name of the Library and select Paste

▪ Rename the file - and click OK

A "cooler" way to do this:


Drag 'n drop a file on top of a
PDS in Remote Systems 66
Create a new file in Remote Systems - and copy code into it
Right-click on <USERID> LEARN.COBOL
and select:
New >
Create Member…

Name the file anything you'd like

▪ Scroll down in the LEARN.COBOL PDS - and open your new file
▪ Scroll up in LEARN.COBOL and open PAYROL01.CBL
 Switch from one file to the other by clicking the editor tab
▪ Select and copy (Ctrl+C) few lines of program source from PAYROL01
▪ Paste (Ctrl+V) the lines into your new file - and save your changes: Ctrl+S
▪ Right-Click over your new File and select: Delete 67
Create a new file with Save As…
If - after you finished your edits to a
program you'd like to save the file with a
different name:
From the File menu on top of the
Workbench, click:
1. File > Save As
2. Expand the destination containers
3. Select a PDS
4. Name the new file and click OK

68
Compile/Link/Run a COBOL Program
To run your first batch job (from Remote Systems):
1. Expand MVS Files and My Data Sets
2. Find and expand <USERID>.LEARN.JCL and open COBUCLG
3. Replace MYPROG with HELLOW
• Note that HELLOW must be UPPER CASE
4. Right-click inside the Editor and Submit the Job to zserveros
5. Click Notify
• The Job should end with a completion code of 0000
• If you get a different completion code please check with your instructor.
Either way - click the hyper-link to the JOBID and expand and explore the JES
output in: GO:RUN:SYSOUT
70
Compile/Link/Debug a COBOL Program
From Remote Systems, expand <YOURID>.LEARN.JCL; Open COBUCLD and Replace: MYPROG with MILLARD
• Right-click in the code and Submit the job. Close the Job Submit confirmation dialog when it appears
• When you are prompted to "Confirm Perspective Switch" click "Switch"
• To watch your program execute, click the Step Into icon on the toolbar - or press F5 repeatedly

• When your program finishes return to the z/OS Projects Perspective (top right corner of ZOD)

If you are using the IBM system, change


the TSOID in the TEST statement to
your TSO-ID for zserveros

Debugging provides a real-time view of what's happening in your COBOL program - both
Your TSO-ID to the data values and to both the program's flow of execution and data field values
Job Control Language - First Look
// Two forward slashes begin each line

1.
2. //* Two forward slashes followed by an * denotes a
3. comment line in the JCL file
4.
5.

1. JOB statement - Defines the beginning of the Job and specifies the resources needed to run the Job

2. //* statement - JCL comments - note that comments can be entered anywhere on a line (see 5.)

3. EXEC statement - Specifies the program to be run

4. //STEPLIB - Specifies the Data Set Name (DSN) of the Load Library where the executable form of HELLOCOB can be found by
the operating system (z/OS)

5. //SYSOUT - an Output DD statement. Specifies where output data should go. In this case - the Job's "SYSOUT" file - a text file
that is automatically created by JES when it runs your batch program.

https://www.tutorialspoint.com/jcl/jcl_overview.htm
Module 2 - ZOD and IDz 7 Month Licenses
Steps…

The license extensions can be found at:


https://community.ibm.com/community/user/ibmz-and-linuxone/viewdocument/zod-license-update?CommunityKey=b0dae4a8-74eb-44ac-86c7-90f3cd32909a&tab=librarydocuments

72
MVS File Filters - for copying files that are not yours
1. Right-Click on MVS Files and select: New > Filter…

2. Type in a TSO-ID and Wildcard characters ➔


• Hit Next > then Finish

3. Expand the new filter. Right-click on the file you wish to copy and
select: Copy
4. Right-click on top of an existing Filter
• Select Paste

73
Module 2 - Summary
• Define the following ZOD/IDz terms & concepts:
• View
• Content Assist
• Perspective

• How do you:
• Work with a program in Full-Screen (Maximized) mode
• Split screen
• Perform look-ahead (Intellisense) typing
• Enlarge - or resize a View
• Reset the Views back to the installation defaults
• Compile/Link-Edit and run a program
• Compile/Link-Edit and Debug a program

Additional ZOD Learning Links


• https://www.ibm.com/support/knowledgecenter/en/SSUFAU_2.0.0/com.ibm.etools.getstart.wsentdev.doc/topics/aintro.html
• https://www.ibm.com/support/knowledgecenter/en/SSUFAU_1.0.0/com.ibm.zod.navigation.doc/topics/kc_product_welcome_zod.html
• https://www.youtube.com/watch?v=vRxdhlaRqA0 74
Workshop - 2.1
1. After you've installed ZOD or IDz, launch the product
2. Create a z/OS connection from your client to your LPAR
3. Login to your mainframe using the User ID and Password sent to you by your instructor or in-house course administrator
4. Explore all of the <YOURID>.LEARN.** data sets using the Remote Systems view - or ISPF 3.4
5. Expand <YOURID>.LEARN.COBOL - and double-click the HELLOCOB PDS member
• Glance over the program, noting the columns, keywords, lines, text, etc.
• Close the file and (if you get prompted) do not save any changes

6. Expand <YOURID>.LEARN.JCL - and double-click the COBUCLG PDS member


• Glance over the JCL statements noting the columns, keywords, etc. Change the SET COBPGM='HELLOCOB'
• Right-click and select: Submit ➔ <your connection>
• At the prompt click which will open a Remote Console view - and let you know when the job completes

7. When the job finishes you should get a 0000 completion code ➔
• Expand the Job
• Open GO:RUN:SYSOUT

When you are


finished close/exit
• Be able to trace the SYSOUT text back to the HELLOCOB program statements
that created the output ZOD 75
Workshop 2.2 - Editing COBOL Programs
From Remote Systems:
- Expand the PDS: <YOURID>.LEARN.COBOL
- Double-Click: HELLO3.cbl

Note the following:


▪ COBOL syntax coloring
▪ Column numbers along the top of the View
▪ Scroll bars for file navigation
▪ Misspell DIVISION… what happened?
 Press Ctrl+z to undo the edit
▪ Misspell DISPLAY… Click the spellchecker
Spellchecker
light bulb and click Change to "DISPLAY"
Lightbulb
▪ Remove a period from one of the lines…
what happened?
 Press Ctrl+z to undo the edit
▪ Change the text in several of the text fields
that are being displayed.
▪ Save your changes by clicking: Ctrl+S
76
Workshop 2.3 - Editing COBOL Programs
From Remote Systems: Copy and paste a line: Ctrl+C … Ctrl+V
OPEN: <YOURID>.LEARN.COBOL(EMPPROJ)
Select to end of line: Shift+End
Try the following edit operations in the source file:
Save changes to the file: Ctrl+S
Press Enter to add a new line
Type some text - then press Ctrl+Z Page up/Page down using PC keys
Type in some text - press Enter. Press Ctrl+End - then Ctrl+Home
Type in more text - Press Enter.
Find an click on the ZOD Outline view.
Press Ctrl+Z (twice)
Expand Procedure Division. Scroll down and
click a COBOL paragraph name. Read some of the
code in the paragraph.
Editing COBOL code with From the program source, press Ctrl+F - and
ZOD is similar to editing Find TOT-PROJ-COST
with docs with Microsoft
tools like MS-Word, etc. Click your mouse-pointer in: TOT-PROJ-COST
and press F3
Scroll to the bottom of the file and hover your
mouse over: TOTAL-DASH-LINE
Close the file - Do not save your changes 77
Optional Workshop 2.4 - Show most recent files
There are two easy ways using IDz/ZOD to access the most recent file you've been working on:
1. Right-click on the LEARN.COBOL library. Select Show In ➔ Remote Systems Detail
• From the Remote System Details view, click: Last Modified

2. From the File menu - select:


Recent Files

78
Optional Workshop 2.5 - In order for you to become productive writing COBOL code as well as
finishing the labs in the course, spend time using your Client IDE;
Open ended lab Navigating the tool, Editing programs, Compile/Link, Test/Debug

Go through the slides in Module 2 again and try all of the


techniques. Repeat the techniques you feel will be useful in
your work. You will build up "muscle memory" when it
comes to development tools - in order to become
productive using ZOD/IDz/Zowe or ISPF
If you're using ZOD/IDz: Reset your perspective
• Maximize/Restore/Resize the Editor and other views
• Create a "sandbox" program by editing WARDRPT, and
Saving it as: SANDBOX
• Then edit the SANDBOX and experiment:
• Add lines/Delete/Modify lines/Copy/Paste lines
• Create another sandbox program
• Copy/paste lines back and forth between the two programs
• Use Content Assist (Ctrl+Spacebar) a few times

Challenge Workshop: You may notice a syntax error in WARDRPT - a


missing variable. Code the following in WORKING-STORAGE:
01 OFCODE PIC X(2). Better? 79
Optional Topic: COBUCLG Runtime Conceptually

3. HELLOW
LEARN.LOAD
• Multi-step process to create an
executable from COBOL source code
LEARN.JCL(COBUCLG)
• Common to all COBOL Business LEARN.COBOL(HELLOW)
//SET COBPGM='HELLOW'
Applications: 1.
• Details vary considerably
from shop to shop
1.

SYSOUT
1. Compile program to .OBJ LEARN.OBJ(HELLOW)
• If syntax errors, stop

2. Link-Edit .OBJ to .EXE (Load Module) 2.


• If Link errors, stop

3. Run Load Module (GO) 2.


LEARN.LOAD(HELLOW)
More info on COBUCLG
https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.z
os.zappldev/zappldev_116.htm
3.

80 JCL Conceptually
Optional Topic: COBUCLD Runtime Conceptually

HELLOW
LEARN.LOAD
GO Step

LEARN.JCL(COBUCLD)
LEARN.COBOL(HELLOW)
//SET COBPGM='HELLOW'

SYSOUT
LEARN.OBJ(HELLOW)

• Same Compile/Link/GO PROC


• GO step contains z/OS command to
LEARN.LOAD(HELLOW)
start the Debugger - for your program
• Again, tools & procedures vary from
This step invokes the Debugger
shop-to-shop
81
Optional Workshop 2.6 -
Create a Trace Debug log file

Debug Console Command:


• SET AUTOMONITOR ON LOG
Forces the Debugger to track each statement as it's
executed and write it to the Debug Console
• Using this technique you can copy and paste your
program's dynamic execution and trace forward
and backward through any portion of your code
• You can also copy all of the statements to hard-
copy:
1. Right-click
2. Select Export History
3. Specify a file – preferably an MS-Word doc,
as the formatting will be retained

82
SET AUTOMONITOR ON LOG
UNIT COBOL for z/OS - Module 3

Basic COBOL Language Model:


• COBOL Syntax
• Language constructs
• 80-columns
• A/B Margins
• Comment column
• Divisions of a COBOL program
• Literals: String & Numeric
• Code & run simple programs
Video tutorials for this Module: • Analyze and debug programs
• https://www.youtube.com/watch?v=pkcFQyKieP0
• https://www.youtube.com/watch?v=KTEEEVxbK18
83
The COBOL Language - Yesterday, Today and Tomorrow
COBOL programs are structured by the rules of the COBOL language. These
rules are defined by a combined business/vendor/academic committee: CODASYL

There are many rules, options, and keywords in COBOL. In this course we will try
to provide the general (80/20) industry use of Enterprise COBOL you will likely
run into in corporate work on z/OS Business Applications.

Many of the seeming anachronisms in COBOL remain because IBM was asked to
"grandfather-in" language syntax for the benefit of customer-base.

The COBOL language and program structure was loosely based on the metaphor
of a book - split into: Divisions, Sections, Paragraphs, Sentences and Words and
readable by business professionals.
• The fact that COBOL is English-like and readable does not mean that
COBOL programs are easy to understand … not until you learn COBOL. 84
ZOD
EMPPAY - Sample Program Server

z/OS
From your development client, open:
<USERID>.LEARN.COBOL(EMPPAY) I/O

LEARN.COBOL

• MEMBER
• MEMBER
•…
• EMPPAY
•…
• MEMBER
• MEMBER
•…

85
Areas Within COBOL Programs
A COBOL source file is made up of 80 byte records.
Why 80 characters?
Each record is broken up into five Areas:
2. Comment
Column
1. Sequence number area: Cols 1 ➔ 6
Reserved for opt. record sequence numbers 1.
Sequence
3. "A" 4. "B" 5.
Number Area Area "Identification"
2. Comment Column: 7 Area
Area

An * or / in col. 7 designates the line as a comment


3. "A" Area: Cols 8 ➔ 11
Where you define:
DIVISION names
SECTION and PARAGRAPH names
Names of certain types of data variables

4. B Area: Cols 12 ➔ 72
Used to code COBOL instructions:
DISPLAY
MOVE
GOBACK

5. Identification Area: Cols 73 ➔ 80 86


• May be left blank
Division
Program Structural Hierarchy Paragraph
Division
SECTION
• A Program can contain four DIVISIONs
• Only the IDENTIFICATION DIVISION is mandatory

• Each DIVISION can contain zero ➔ many SECTIONS


or zero ➔ many Paragraphs Data Definition
Elements

• Each SECTION can contain zero ➔ many Paragraphs


Division
• Each Sentence contains one ➔ many Statements. Procedural
Statements
• Each Statement begins with a Keyword

Keywords
Procedural
Statements

Procedural
COBOL is "Code in a Structured Document", Statements
Bob Reselman 87
COBOL Programs as "Structured Documents**"
Comment
Paragraphs, Sections and Division Column

names must be defined starting in


the A Area Sequence
Number
A B Identification
Area Area Area Area

Division
Paragraph
Division
Section
Data Definition
Statements

Division

Procedural
Statements

**"COBOL is Code in a Structured Document",


Bob Reselman 88
Cracking the Code: DIVISIONS in a COBOL Program
IDENTIFICATION DIVISION.
PROGRAM-ID. EMPPAY.
1. IDENTIFICATION DIVISION. DATA DIVISION.
• Names the program in the WORKING-STORAGE SECTION.
01 EMP-RECORD.

Data Definitions
PROGRAM-ID paragraph 05 EMP-NAME.
2. ENVIRONMENT DIVISION. 10 EMP-FNAME PIC X(15).
10 EMP-LNAME PIC X(15).
• An optional DIVISION that associates 05 EMP-HOURLY-RATE PIC 9(3)V99.
z/OS data files with the program 05 EMP-OT-RATE PIC V99.
05 EMP-HOURS PIC 9(3).
3. DATA DIVISION. 05 EMP-PAY PIC 9(7)V99.
• Defines the data a program processes; PROCEDURE DIVISION.
Records in files & variable definitions MOVE "Millard" TO EMP-FNAME.
MOVE "Fillmore" TO EMP-LNAME.
are coded in the FILE SECTION and MOVE 19 TO EMP-HOURS.

Procedural Statements
WORKING-STORAGE SECTION MOVE 23.50 TO EMP-HOURLY-RATE.
IF EMP-HOURS > 18
MOVE .25 TO EMP-OT-RATE
4. PROCEDURE DIVISION. ELSE
• Contains executable COBOL MOVE ZERO TO EMP-OT-RATE.
instructions - Sentences & Statements COMPUTE EMP-PAY =
(EMP-HOURS * EMP-HOURLY-RATE) * (1 + EMP-OT-RATE).
beginning with a Keyword and ending DISPLAY "Name: " EMP-NAME.
with a period. DISPLAY "Hours Worked: " EMP-HOURS.
DISPLAY "Hourly Rate: " EMP-HOURLY-RATE.
DISPLAY "Bonus-Rate: " EMP-OT-RATE.
DISPLAY "Gross Pay: " EMP-PAY.
GOBACK. 89
Cracking the Code: DATA DIVISION and
WORKING-STORAGE SECTION
Variables are containers for values used by the
program.

Variables ("fields" … "data items") are defined in


the DATA DIVISION.

Variable definitions describe the type and


define the max size of the value that can be
stored in a variable.

Code temporary variable definitions for the


internal processing of data that your program
uses in the WORKING-STORAGE SECTION.

90
Cracking the Code: Variable Definitions - 1 of 2

• Level Number
• Describes a data hierarchy or Group field:
• Defined fields that contain "lower-level" defined fields
i.e. NAME comprised of FIRST-NAME & LAST-NAME
• There are a few "reserved" level numbers: 77, 88
• 77 and 01 variable definitions begin in the "A Area"
• 77 Variables are "standalone" or "Singleton" variables
• They cannot contain lower-level defined fields

Level
• Variable Name Number
Variable Name Variable/Type Size
• Can be up to 30 characters long and can contain the
following characters: 05 EMP-HOURS PIC 9(3).
• Alphanumeric
• Dash 1. 2. 3.
• Underscore
3-Part Definition
• Must start with an alpha or number
91
• Cannot be a COBOL "reserved word" (MOVE, IF, etc.)
Cracking the Code: Variable Definitions - 2 of 2
• Type and maximum size - the PIC clause
• Alphanumeric data: PIC X(…).
• Allows character or numeric values

• Numeric data: PIC 9(…).


• Allows only numeric values

• Digits within parens define field max size

• Example:
01 EMPLOYEE-REC.
05 COMPANY-NAME PIC X(40).
05 EMPLOYEE-AGE PIC 9(03).
05 RETIRED-INDICATOR PIC X(01).
05 ADDRESS.
10 STREET-ADDRESS PIC X(30).
10 CITY PIC X(30).
10 STATE PIC X(02).
92
92 10 ZIP PIC 9(05). 92
Cracking the Code: PROCEDURE DIVISION
and Program Flow

Code executable statements in the


PROCEDURE DIVISION
Executable statements are comprised of
Operational verbs … Value(s) … Variables
• MOVE
• IF
• COMPUTE
• DISPLAY

Code "literals" in the PROCEDURE DIVISION:


• Numeric Literal ➔ PIC 9 fields
• Alphanumeric Literal ➔ PIC X fields
• Enclosed in apostrophes or double-quotes

Statements in the PROCEDURE DIVISION execute


sequentially - one after the next - until execution
encounters "branching statements".
93
Literals
Cracking the Code:
PROCEDURE DIVISION Rules
Keywords begin in the "B Area"
• MOVE - Transfers a value to a variable
• Left-to-right operation
• IF - conditional test
• IF <condition>
• Imperative statement
• ELSE
• Imperative statement
• END-IF.

• COMPUTE
• Calculate a result
• Right-to-left algebraic operation
• DISPLAY
• Write output to a Job's "SYSOUT spool file"
• GOBACK - Ends the program 94
COBOL Language Coding Rules -
Summary
• Basic COBOL Syntax and language constructs:
• 80-columns - per line
• A/B Margins (A Area / B Area)
• Divisions of a COBOL program
• IDENTIFICATION DIVISION
• ENVIRONMENT DIVISION
• DATA DIVISION: Variables: Type & Maximum Size
• PROCEDURE DIVISION

• COBOL Paragraphs
• Used to structure a program's solution to a
business problem.
• Breaking one large problem into small ones
• We cover Paragraphs in Module 4

• COBOL Sentences
• COBOL Statements
• COBOL Verbs: DISPLAY, MOVE, COMPUTE, etc. 95
COBOL Program Big Picture Review - Topics in Module 3
Identification Name the executable Program-ID. EMPPAY.

Define connections to external data sets:


Environment Both Indexed and Sequential files

Declare data variables that contain values to 77 Standalone variable declaration


01 Data Hierarchy (Group) variable definitions
be processed (manipulated) in the
05
PROCEDURE DIVISION 10
Data

Code the executable statements that IF/ELSE


Procedure process the variable values in the DATA MOVE
DIVISION Literals: Numeric and Alphanumeric
DISPLAY
GOBACK

Supplementary web videos and resources:


https://www.youtube.com/watch?v=H-xek9caXb0&list=PLWPirh4EWFpEwRypgRSofF7Ui91yeCeMi&index=4 - Defining Variables
https://www.youtube.com/watch?v=8tT4eJg3GJM&list=PLWPirh4EWFpEwRypgRSofF7Ui91yeCeMi&index=5 - Basic COBOL Verbs
96
Module 3 - Demo
Like EMPPAY, "MILLARD"
demonstrates various COBOL
constructs:
• DIVISIONS and SECTIONS
• Paragraph - What is its name?
• DATA DIVISION variables
• Definitions
• Numeric vs. Alphanumeric types
• Data Hierarchy

• Comments
• PROCEDURE DIVISION Keywords:
• MOVE
• IF/ELSE
• COMPUTE
• DISPLAY

97
The JCL JOB Statement //DDNAME DD DSN=ABCD

//STEPNM EXEC PGM=S…

• The JOB statement is the first control statement in a job. It marks the beginning of a //JOBNM JOB 504,SMIIH

job and also specifies the name of the job.


• The JOB statement also might provide details and parameters that apply to all job steps within the job,
such as accounting information and conditions for job termination. It also may contain any comments that
help describe the statement.
• This JCL example contains one JOB statement:
//JOBNUM1 JOB 504,SMITH PAYROLL
//STEP1 EXEC PGM=PROGRAM1
//DD1 DD DSN=HLQ.OUTPUT
• The name field contains the job name "JOBNUM1". In every JOB statement, the name field contains a one- through eight-character name
that identifies the job so that other JCL statements or the operating system can refer to it. Be sure to assign a unique name for each job.

• The parameter field defines information that applies to the entire job, contains an accounting number (504) and the programmer's name
(SMITH). These parameters are positional and must appear in the order shown.

• The comment field contains PAYROLL.

• The end of a job is indicated by a null statement, which consists of only two forward slashes (//), or is marked by the beginning of another
JOB statement. In this sample, JOBNUM1 ends with a null statement.

Excellent web-page that describes batch Job Flow description:


https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zconcepts/zconc_batchjeses.htm 98
Module 3 Review Questions
1. Which of these variable names are correct? What is wrong with the incorrect ones?
01 CUSTOMER-REC PIC 30.
05 COMPANY-NAME PIC X(40).
05 EMPLOYEE AGE PIC 9(03).
05 9RETIRED-INDICATOR PIC X(01).
05 ADDRESS.
05 STREET-ADDRESS PIC X(30).
10 CITY PIC X(30.
10 STATE PIC X(02).
10 MOVE PIC 9X(11).
10 ZIP_CODE PIC X(05).

2. Is this record layout syntactically correct ➔


3. How can you tell COBOL SECTIONS from paragraphs?
4. If it's correct which of these statements that reference the fields are "legal"?
• MOVE 10 TO EMP-NAME.
• MOVE 'SMITHFIELD HOMES' TO EMP-FNAME.
• MOVE EMP-FNAME TO EMP-OT-RATE.
• MOVE EMP-OT-RATE TO EMP-PAY.
• MOVE '10' TO EMP-HOURS. 99
COBOL Workshop Structured Development Guidelines
• Working-storage:
Upon getting an assignment
• Flags
• Read the specs • Accumulators
• Temp-storage fields for computations
• Read them again
• PROCEDURE DIVISION;
• Find a program that's similar in output to the program you must write
• Create all Paragraphs without any data
• Copy the code from that program • Just paragraph names and comments and DISPLAY statements
• Start modifying the new-program code by deleting areas within the program that are COBUCLG – just to find out where the syntax errors are
immaterial to your specs - Then begin your custom programming work
• Delete DATA DIVISION variables and PROCEDURE DIVISION paragraph details Back to the program - Add one scenario (large-grain function) at a time:

• IDENTIFICATION DIVISION; • FILE OPEN/READ/WRITE/CLOSE;


• PROGRAM-ID. • Including AT END
• Comment what your program is supposed to do • Including File Status (from Chapter 11)

• ENVIRONMENT DIVISION; COBUCLD to Debug your File handling


• Input Files - SELECT ASSIGN
Make modifications
• Output Files - SELECT ASSIGN
• Immediately go to your JCL and add - or check on the //DD cards (and files) needed for Iterate
your program
Next scenario
• DATA DIVISION;
• Files • Add the next piece of functionality, then COBUCLD
• FDs and FILE SECTION entries • Make modifications
• Input record layouts • Iterate
• Output record layouts - including Report heading lines
Keep adding functionality in an iterative but concise & contained fashion. This
• Test Data
way you maintain control over the programming/testing cycle - reducing
• Create the test records to match your input layouts
complexity -and lowering your level of frustration with small wins -
• Sketch out (at least mentally) the output report or record format which build up to big program jobs 10
Workshop 3.1a - Create new COBOL program
Create a new program in LEARN.COBOL named FAVS that is based on the COBOL code
in EMPPAY. FAVS should DISPLAY facts (real or imagined) about your favorite musical group.
Copy LEARN.COBOL(EMPPAY). Name the new program: FAVS
1. ZOD/IDz users see Module 2 for steps to create a new program
2. ISPF developers use ISPF 3.3 to Copy a PDS member into the same library

Edit Favs
1. Modify the PROGRAM-ID.
2. Modify the DATA DIVISION code - using new variable declarations shown on the next slide ➔
3. Modify the PROCEDURE DIVISION
• MOVE and DISPLAY new (and fictitious) values.
• Note the math (Compute statement) for CD-Cost: Cost = CD-Cost + (Sales Tax * Cost) + Shipping
4. When you're done and there are no syntax errors in the source file Save your work, and:
• Compile/Link/Run your code: LEARN.JCL(COBUCLG)
• Compile/Link/Debug your code: LEARN.JCL(COBUCLD)
10
Workshop 3.1b - Create new COBOL program
Potential record layout for FAVS. You will probably Musical Group Name: 30 bytes Alpha-Numeric
have to modify field definitions and/or add fields Number of musicians in the band: 2 digits
to FAV-REC to handle the program's requirements Musical genre - 12 bytes:
➔ CD cost - less than $1,000 - with two bytes to the right of the decimal place.
• Cost = CD + Shipping + Tax
TAX Calculation:
• If the CD-COST is > $40 the Tax is 6% of the CD-Cost
• Otherwise the Tax is 10% of the CD-Cost
Band is still together - 1 Byte: Valid values are: T/F 1 byte

Specifications for the report. The above non-COBOL requirements format


is similar to what you might get as part of a "spec package".

Before you begin the workshop:


• Read the Workshop slides carefully - Understand what you're being asked to do before you start coding
• Review the slides in this Module - especially the DATA DIVISION and PROCEDURE DIVISION slides
which contain details on the COBOL syntax used in the program
• Test the program with different values - checking for the correct computation & numeric PIC clauses
• ZOD/IDz users - refer to the slides in Module 2 for file editing and navigation
• ISPF users:
• Refer to video-learning links on using at the beginning of Module 2
• And you may need to get help on the Compile/Link/Go and Compile/Link/Debug JCL 102
Optional Workshop 3.2 - Program Analysis
Program Maintenance assignments are 60% reading, discovery,
understanding/analysis 10% coding and 30% testing.
Workshop Steps:
Open MORTGAGE and read the code starting from the
PROCEDURE DIVISION. Verify all DATA DIVISION fields
and their type/size.
(ZOD/IDz users) When a record or variable is referenced in
the PROCEDURE DIVISION:
1. Hover over the field
2. Open Declaration
3. Study the DATA DIVISION code

(ISPF & ZOD) After you've finished reading;


• From LEARN.JCL: Open COBUCLG
• Change MYPROG ➔ MORTGAGE and Submit the
Compile/Link/Go JCL
Even after many years of COBOL
• When the Job finishes view the SYSOUT file in JES - experience you will bump into
and reconcile the actual results with what you expected things you've never seen before.
to happen Learn to research. 103
Optional Slide - Deeper Dive into the MOVE Statement
• The COBOL MOVE statement copies a value to a variable
• The direction of MOVE is from left ➔ right
• The value can come from another variable or it can be defined as a COBOL Literal.
• If you are moving the contents of one variable to another, the sending variable remains
unchanged
• MOVE 'SMITH' TO LAST-NAME.
• Before the MOVE statement the content of LAST-NAME is undefined
• After the MOVE statement LAST-NAME contains: SMITH
• MOVE 89 TO AGE.
• Before the MOVE statement the content of AGE is undefined
• After the MOVE statement AGE contains: 89
• Note that AGE must be defined as a numeric (PIC 9) variable.

• MOVE LAST-NAME TO LAST-NAME-OUT.


• Before the MOVE statement the content of LAST-NAME-OUT is undefined
• After the MOVE statement LAST-NAME-OUT contains: SMITH

104
Optional Slide - Deeper Dive into the COMPUTE Statement
• THE COBOL COMPUTE statement The COMPUTE statement calculates the value of an
arithmetic expression and assigns the value to a numeric variable.
• The operation proceeds from right to left: Compute ResultVar = Var2 + Var3.
• All of the variables referenced in a COMPUTE statement must be declared in the DATA DIVISION as
numeric variable types: PIC 9 or some variation: PIC 9(03) PIC 9999 - etc.
• COMPUTE GROSS-PAY = 40 * 15.
• Before the COMPUTE statement the contents of GROSS-PAY is undefined
• After the COMPUTE statement GROSS-PAY contains: 600
• MOVE 65 TO HOURS-WORKED.
• MOVE 22 TO HOURLY-RATE.
• COMPUTE GROSS-PAY = HOURS-WORKED * HOURLY-RATE.
• Before the COMPUTE statement the contents of GROSS-PAY is undefined
• After the COMPUTE statement GROSS-PAY contains: 1320
• MOVE 60 TO WS-FAHRENHEIT.
• COMPUTE WS-CELSIUS = (WS-FAHRENHEIT - 32) * (0.5556).
• Before the COMPUTE statement the contents of WS-CELSIUS is undefined
• After the COMPUTE statement WS-CELSIUS contains: 15

• Note that COMPUTE statements can get pretty involved ➔


105
UNIT COBOL for z/OS - Module 4
DATA DIVISION and PROCEDURE DIVISION
- Next Level COBOL Statements
Review
Type
Size
01, 77
Structures
Group
Elementary
FILLER
VALUE
88-LEVEL
More complex performs
MOVE statements
Video Tutorial for this Module: Elementary
• https://www.youtube.com/watch?v=qhwOFuQl_pg Group
Numeric
String
Use Listing files to solve syntax problems 106
COBOL Program Big Picture - Topics in Module - 4
Identification Name the executable Program-ID. MILLARD.
Define connections to external data sets:
Environment Both Indexed and Sequential files

Declare data variables that contain values to 77 Standalone variable declaration


01 Data Hierarchy (Group) variable definitions
be processed (manipulated) in the
05
PROCEDURE DIVISION 10
Data
88 Named condition
FILLER
VALUE
Signed Numeric PIC
Code the executable statements that IF/ELSE
Procedure process the variable values in the DATA MOVE
DIVISION PIC X MOVE behavior
PIC 9 MOVE behavior
Literals: Numeric and Alphanumeric
DISPLAY
GOBACK
Code Paragraph
PERFORM Paragraph

107
ZOD
PAYROL0A - Sample Program Server

z/OS
I/O
Open <USERID>.LEARN.COBOL(PAYROL0A)

LEARN.COBOL

• MEMBER
• MEMBER
•…
• PAYROL0A
•…
• MEMBER
• MEMBER
•…

108
Review: Defining and Naming Variables
Variable definitions are declared in the DATA DIVISION. They follow COBOL language rules:
• Level Number - denotes an individual field (77) or a Group data hierarchy definition (next slide)
• Variable name - a unique name used to reference the variable within the PROCEDURE DIVISION
• Variable type/size definition - a picture of the size and type of value contained in the variable

Variable names follow COBOL language rules :


• Must not be a COBOL reserved word.
• See the end of this chapter for a link to a complete list of Enterprise COBOL reserved words
• Must not contain a space (blank) as a part of the name.
• Names can contain: Letters (A-Z), digits (0-9), underscores ( _ ) and hyphens ( - ).
• Maximum length of 30 characters.
• A hyphen cannot appear as the first or last character.
• An underscore cannot appear as the first character.
Variable names are case-insensitive: LAST-NAME ➔ last-name ➔ Last-Name 109
110
Review: Level Numbers
A variable level number is a one-digit or two-digit integer assigned to a variable.
Level numbers describe a "data hierarchy" and can be between 01 and 49 - or one of three special (reserved)
level numbers: 66, 77, or 88.
Group fields (which have no PIC clause) define a collection of subordinate variables.
They typically describe hierarchically related business data
A B
Area Area
77-level and 01-level data items must be
77 DATE-TODAY PIC X(10).
coded starting in the A Area.
01 FULL-NAME.
05 LAST-NAME PIC X(20).
05 MID-INITIAL PIC X(01).
05 FIRST-NAME PIC X(15).
01 STUDENT.
05 SOCIAL-SECURITY-NUMBER PIC X(20).
A Group variable includes all of the
05 CREDITS-TAKEN PIC 9(01). fields that follow it, until a level number
05 COURSE. less than or equal to the level number
10 COURSE-NAME PIC X(20). of that group variable is encountered.
10 COURSE-GRADE PIC 9(03).
05 FACULTY-ADVISOR.
10 ADVISOR-NAME PIC X(20).
10 ADVISOR-EXTENSION PIC X(04).
111
Review: PIC Clauses
PIC clause - Defines the size and type of the data contained in the variable.
• LAST-NAME PIC X(19).
• An alphanumeric variable which can contain, letters, numbers or special characters ( $, &, ^, +, @, %, etc.)
• The number of alphanumeric characters (bytes) that can be stored in this LAST-NAME is 19
• The (19) within parens is COBOL-shorthand for defining the number of digits in the PIC clause
PIC X(19) is the same as: PIC XXXXXXXXXXXXXXXXXXX. - but is far easier to type.

• TRIP-DURATION PIC 9(09).


• Numeric variable
• Max number of numeric digits is nine - and the largest algebraic value of TRIP-DURATION contain is: 999,999,999.
• Note that PIC 9(09) is the same as PIC 999999999.
77 DATE-TODAY PIC X(10). A 77-level data item is a single/standalone
01 ACCOUNT. variable. It must have a PIC clause.
05 ACOUNT-NUMBER PIC X(10).
05 ACCOUNT-ID PIC X(08). An 01-level data item is typically a group field -
05 ACCOUNT-PASSWORD PIC X(08). 01 fields must NOT have a PIC clause.
05 NUMBER-OF-WITHDRAWALS PIC 9(09).
05 ACCOUNT-BALANCE PIC S9(6)V99.

The "S" in the ACCOUNT-BALANCE PIC clause makes the field a signed numeric field, which can
contain values for both positive and negative numbers. The "V" in the PIC clause denotes an
implied decimal place - with 6 decimal digits to the left and 2 decimal digits to the right.
Cracking the Code: Additional Variable Definition Features
77 DATE-TODAY PIC X(10) VALUE SPACES.
01 ACCOUNT.
05 ACOUNT-NUMBER PIC X(10) VALUE ALL '1'.
05 ACCOUNT-ID PIC X(06) VALUE 'XXXXXX'.
05 FILLER PIC X(02) VALUE SPACES.
05 NUMBER-OF-WITHDRAWALS PIC 9(09) VALUE ZEROS.
05 ACCOUNT-BALANCE PIC S9(6)V99.
88 EMPTY-ACCOUNT VALUE ZEROS.
05 END-OF-FILE-SWITCH PIC X(01) VALUE 'N'.
88 END-OF-FILE VALUE 'Y'.

PROCEDURE DIVISION.
IF END-OF-FILE …

IF EMPTY-ACCOUNT …

1. FILLER - Defines a "byte placeholder" of a given PIC size inside a Group. Typically used for report formatting.
2. VALUE - A clause at the end of a variable definition that allows you to initialize the field to a given value before
the PROCEDURE DIVISION starts.
3. 88-Level - Defines a conditional test for a value defined within the variable's declaration. Used in
conjunction with IF statements in the PROCEDURE DIVISION - 88-levels can make code easier to read.
These three variable declaration features are available on elementary data items, for all variable
types, sizes and level numbers in the WORKING-STORAGE SECTION. 112
Cracking the Code: Paragraphs
Paragraphs are logical subsections of a
COBOL DIVISION or SECTION in your
program
Paragraphs contain sentences which in turn
contain COBOL statements.
Paragraph names (labels) are defined
starting in the "A Area"
Executable statements are coded inside of
paragraphs in the "B Area"
Paragraphs are used to organize procedural
logic along functional lines - making a
program readable and easier to follow.
113
Cracking the Code: PERFORM Statement
The PERFORM keyword transfers control ("branches")
to a named paragraph or SECTION

Statements within a performed paragraph will execute


sequentially - unless another branch statement is
encountered in the paragraph or until the next
COBOL paragraph or SECTION is executed

When the next paragraph or SECTION name is


executed, control is transferred back to the Next
Sequential Instruction following the original
PERFORM Paragraph statement.

To verify this "branching" behavior, debug PAYROL3A


114
Cracking the Code: Alphanumeric (PIC X) MOVE Statement Deep Dive
When your code moves the contents of one variable to another, think of: sending and receiving fields
• MOVE LAST-NAME TO LAST-NAME-TEMP.
Sending Receiving
Field Field
• The MOVE statement copies values according to the receiving field's data type:
• If the receiving field is defined as PIC X - bytes are copied from LEFT ➔ RIGHT starting at byte one of
the sending field
• If the sending field is shorter than the receiving field, the receiving field will be blank-filled to the remaining size of its
PIC clause.
• If the sending field is longer than the receiving field the sending field's bytes will be truncated to the size (PIC Clause)
of the receiving field.

• Consider the following:


• 05 LAST-NAME PIC X(10). b b b b b b b b b b

• MOVE 'SHERM' TO LAST-NAME. S H E R M b b b b b


• The MOVE statement copies the letters SHERM to LAST-NAME, from left to right starting at byte 1:

• 05 LAST-NAME PIC X(12). b b b b b b b b b b b b


• MOVE 'SHERMAN&PEABODY' TO LAST-NAME.
• After the MOVE statement LAST-NAME contains: S H E R M A N & P E A B 115
Cracking the Code: Numeric (PIC 9) MOVE Statement Deep Dive
When numeric values are moved to PIC 9 variables, there are also: sending and receiving fields
• MOVE GROSS-PAY-IN TO GROSS-PAY-OUT.
Sending Receiving
Field Field
• If the receiving field is numeric, COBOL performs an "algebraic move":
• COBOL aligns both fields at their implied decimal point - and then copies the sending field's digits to the left and to
the right of the decimal point.
• If the sending field's value is less than the receiving field's definition, the receiving field will be zero-filled on
the left and right of the decimal place - to the remaining size of its PIC clause - decimal aligned
• If the sending field's value is larger than the receiving field the sending field's bytes will be truncated to the PIC
Clause definition of the receiving field - this could include "significant digits"

• Consider the following:

Decimal
Implied
Point
05 GROSS-PAY PIC 9(4)V99 VALUE 0.
• …
MOVE 111.2 TO GROSS-PAY.
• After the MOVE statement GROSS-PAY contains: 0 1 1 1 2 0

Decimal
Implied
Point
05 GROSS-PAY PIC 9(4)V99 VALUE 0.
MOVE 123456.789 TO GROSS-PAY.
• After the MOVE statement GROSS-PAY contains: 3 4 5 6 7 8 116
Cracking the Code: Allowable MOVE Statements
Sending field PIC clause Receiving field PIC X Receiving field PIC 9 Receiving field Group field
PIC X - or "alpha literal" Y N Y
Group Data Field Y N Y
PIC 9 - or numeric literal ? Y Y ***

Considerations: Don't believe


PIC X ➔ to ➔ PIC X field moves are allowable - as are PIC 9 ➔ to ➔ PIC 9 moves this? Find out
- Group variables moves are treated as PIC X (Alphanumeric) moves.
See prior slides on numeric vs. Alphanumeric MOVE statements - truncation, overflow, etc.
for yourself.
DEBUG
For a MOVE statement where the receiving field is PIC 9: LEARN.COBOL(TRUNCATE)
_ Both the sending and receiving fields must contain valid numeric data

If you move a PIC 9 field to a PIC X field


_ The resulting value in the PIC field will contain blanks if the receiving field's definition is lager than the sending field
_ Blanks are not considered valid numeric data
Group Field MOVE
_ If you move one Group field to another Group field:
• The PIC X elementary fields will receive PIC X ➔ PIC X treatment
• The PIC 9 elementary fields within the group will receive PIC 9 (algebraic) treatment
***_ If you move an elementary field to a Group field, the move is considered a PIC X move
• The receiving field will be blank-filled, to the end of the variable definition 117
Working in COBOL at this Level
• In the real-world things all too often do not go as planned.
• For example…how would fields named the same, and from the same
business domain differ in PIC definition (lengths & types)?
• More than one person is making changes to the code
• This is a "COTS" system
• Corporate acquisitions and mergers of I/T applications
• The person who wrote the code didn't really know COBOL

• What to do?
• Debug the code - especially when things "go south" and looking at code + output is not sufficient
• Do not depend on DISPLAY statements
• Consult the course material
• Consult Dr. Google
• Slack your question - or find a COBOL Forum
• "Phone a friend"

The "Discovering COBOL Answers to Questions


Outside of Class-Time" Methodology
118
COBOL Language - Variable Names and Reserved Words
• Reserved Words in COBOL are language elements that are reserved for special use in the
COBOL language.

• As such - "reserved words" cannot be used as names for variables or paragraphs defined in
your program

• Keywords are a subset of Reserved Words. In general practice - they will mean the same thing
as reserved words: single words predefined as part of the COBOL language per se'
• Examples:
A table containing all of the Enterprise COBOL reserved words as of this writing:
• PROCEDURE
https://www.ibm.com/support/knowledgecenter/zh/SSZJPZ_9.1.0/com.ibm.swg.im.iis.ds.mfjob.dev.doc/topics/r_dmnjbre
• DIVISION f_COBOL_Reserved_Words.html

• ENVIRONMENT
• IDENTIFICATION
• MOVE
• DISPLAY
• GOBACK
• COMPUTE
• … 119
120

Workshop 4.0 - TESTCOB: A personal COBOL Learning/Testing Tool


As a means of learning new COBOL concepts, you can create a small program for testing aspects - or even just
one new facet of COBOL. See next slide for a reminder of how to create a new program from an existing one.
You'll have to define WORKING-STORAGE fields for any scenario you'd like to test - and of course code/test the
procedural logic.
Some use cases to try out using TESTCOB:
1. Complex conditional expressions
2. DATA DIVISION concepts
1. PIC 9 vs. PIC X and Group Field MOVE statements
2. 88-Level fields
3. Signed Numerics
4. PERFORM Paragraph testing

As you begin using TESTCOB - two final things:


1. You can comment out code in the PROCEDURE DIVISION that you don't need to run anymore, but want to keep
2. Embed COBOL comments in your scenarios - with easily identifiable search words for reuse

You can also use TESTCOB to experiment with COBOL language elements we haven't covered yet: i.e. Learn about
UPPER-CASE: https://www.ibm.com/support/knowledgecenter/en/SSQ2R2_14.2.0/com.ibm.ent.cbl.zos.doc/pg/tasks/tpstr19a.html
TESTCOB - A "Sandbox" Program for COBOL Keywords and Constructs
The best way to understand COBOL verbs/operations/etc. is to see it working under Debug.
Create a small COBOL test program that will allow you to quickly try out different aspects of the
language that you're learning… ZOD/IDz
Open HELLOW
File ➔ Save As... TESTCOB

ISPF
Open HELLOW
Block copy (CC…CC)
Command > create testcob 121
Module 4 - Summary
Module 4 covered several next-level COBOL language constructs:
• DATA DIVISION:
• Variable definitions:
• Level numbers
• Group field definitions
• VALUE clause

• PROCEDURE DIVISION:
• MOVE statement behavior for both PIC X and PIC 9 fields
• Paragraphs and PERFORM Paragraph logic Reminder: PERFORM statements return execution to the Next
• Allowable COBOL MOVE statements Sequential Instruction after the performed paragraph as soon as
another paragraph or section label is encountered

http://www.3480-3590-data-conversion.com/article-reading-cobol-layouts-1.html - record layout deep dive

http://www.3480-3590-data-conversion.com/article-reading-cobol-layouts-2.html - record layout examples 122


Workshop Questions - Defining Variables
Answer the following questions using the data definitions below
7890|123456789012345678901234567890123456789012345
-------------------------------------------------- • How many variables are declared in total?
• How many digits are to the left and right of the
01 HOSP-BED. implied decimal place in SPECIAL-CHARGES?
10 BED-ID PIC X(14) • Why is HOSP-BED declared in the A Margin?
10 ROOM-ID PIC X(8). • Why is MED-NAME declared in the B Margin?
10 COST PIC 9(6). • How many Group fields are declared
10 MEDICATION. • What is the data type of MED-PRICE?
20 MED-NUMBER PIC X(8). • What is the max algebraic value of COST?
• What is the total length of the MEDICATION
20 MED-NAME PIC X(40). group field?
20 MED-PRICE PIC S9(7)V999. • How many signed numeric fields are there in
10 WARD-ID PIC X(4). HOSP-BED?
10 SPECIAL-CHARGES PIC S9(7)V9(3). • How many bytes can REC-KTR contain?
• How many bytes can MED-NAME contain?
10 FILLER PIC X(30).
• What is the difference between the PIC clauses
77 REC-KTR PIC 99. of MED-PRICE and SPECIAL-CHARGES?

123
Review Questions - MOVE Statements
From LEARN.COBOL(MOVXMPLN)
From the screen capture ➔
Given the following WORKING-STORAGE definitions
• Analyze each MOVE statement in the
PROCEDURE DIVISION
• Determine what value ends up n the receiving field.
• Consider:
• PIC X left-to-right MOVE execution
• PIC 9 Algebraic assignment aligned on an
implied decimal point - if one exists in the field
definitions
• Truncation
• Loss of positive/negative sign in the receiving
field

• After you've finished your answers:


- COBUCLG MOVXPLN
Note that you will receive a 04 return
code…why - what does the compile
output say???
- From the Job's SYSOUT file verify your
expectations by using split-screen to both the
program code & results at the same time 124
COBOL Program Big Picture Review
Identification Name the executable Program-ID. MILLARD.
Define connections to external data sets:
Environment Both Indexed and Sequential files

Declare data variables that contain values to 77 Standalone variable declaration


01 Data Hierarchy (Group) variable definitions
be processed (manipulated) in the
05
PROCEDURE DIVISION 10
Data
88 Named condition
FILLER
VALUE
Signed Numeric PIC
Code the executable statements that IF/ELSE
Procedure process the variable values in the DATA MOVE
DIVISION PIC X MOVE behavior
PIC 9 MOVE behavior
Literals: Numeric and Alphanumeric
DISPLAY
GOBACK
Code Paragraph
PERFORM Paragraph

125
Maintenance Workshop 4.1
1. Open the COBOL program MILLARD and study the code - line by
line. Analyze and predict the output, then Compile/Link and Run
(COBOLCLG) MILLARD - and from the Job's SYSOUT file, review
the results and reconcile them with what you expected.
2. Add Paragraphs and PERFORM statements to MILLARD
• The only changes you need to make are in the PROCEDURE DIVISION
• NOTE - the code in the program version shown here will not work ➔
• When you run it, you'll get an ABEND (S0C7).
• Figure out why - and fix the problem so that it goes: EOJ

3. Again Compile/Link and Run MILLARD - and validate that the


output your new version produces with the new PERFORMs and
Paragraphs is the same as the previous version.
4. Fun Fact: Millard Fillmore had no vice president. So make his wife
(Abigail) the VP. Modify the code in the program as follows:
• Add a new 77-level variable named: VP
• Update the ASSIGNMENT-PARAGRAPH for Abigail the VP.
Add a new: MOVE statement and DISPLAY statement

• Compile/Link and Run or Debug to verify your work. 126


Optional - Production Support Workshop 4.2
There seems to be a logic bug in the FAHR2CEL program ➔
…which calculates Celsius temperatures based on Fahrenheit temperatures.
Open the program and study it for a few minutes to understand how it works.

Steps…
1. Compile, Link and Run the existing code
• Look for the results in your Job's SYSOUT. Looks OK, right?
• Now test the program by going to: https://www.mathsisfun.com/temperature-conversion.html
• Enter 60 in the Fahrenheit box and test. Our program is wrong…why?
• Numeric precision problems - that's why 

2. Change the code in FAHR2CEL to what is shown here ➔


• Then Compile/Link/Run FAHR2CEL
• View the Job's SYSOUT. Better?
• But are we really done?
• Test with 300 degrees Fahrenheit. Is the bug truly fixed?
• Any guesses as to why it's not (see the Truncation topic in Module 4 to find the answer)

Optional Workshop 4.2a - Using the internet, find the formula to convert Celsius to Fahrenheit.
Add new COBOL logic to convert a Celsius temperature to Fahrenheit. 127
Optional - Production Support Workshop 4.4
Compile, Link and Debug PAYROL0B ➔
• This program writes a single pay-stub.
• Note that, even though there are no syntax errors this
program has bugs.
• Find and fix as many bugs as possible
• Start by reading the code carefully - starting at
the PROCEDURE DIVISION and looking-up
(referencing) all variables
• Look for:
• Truncation problems in MOVE statements:
• Alphanumeric/Numeric
• Logic issues
• Arithmetic issues

• Along with Debugging, run the job using COBUCLG 128


Optional Workshop 4.5 - Maintenance Assignment
COBOL maintenance assignments are 90% reading, discovery,
understanding and less than 10% coding.
Open CBL0001*** and read the code starting
from the PROCEDURE DIVISION
When a record or variable is referenced in the
PROCEDURE DIVISION:
1. Hover over the field
2. Open Declaration
3. Study the DATA DIVISION code

After you've finished reading;


From LEARN.JCL(COBUCLD)
- Change the TEST statement to your USERID
- Debug and study the program, line by line
Even after several years of
- Check out the report the program produces COBOL production
experience you will bump
into things you've never
***The CBL000n programs are from an IBM team that
seen. Learn to research.
recently published a book on COBOL using VS Code/Zowe 12
Optional Workshop 4.6 - Remote Syntax Check
From within the Editor - using ZOD or IDz
Right-Click and select Remote Syntax Check … or Save and Syntax Check

A mainframe Compile results


Although no .exes are produced

See Syntax Errors in the


Remote Error List

Double-click a syntax error to


navigate to the line in question

Note you will need something


called a "Property Group"
130
ZOD/IDz Property Group
Property Groups are used to customize IDz & ZOD to a given mainframe environment, providing support for:
• COPYBOOK and INCLUDE file resolution - to remedy syntax errors
• Opening Called programs from Calling programs during an edit session
• Opening JCL PROCS from inline JCL

A Property Group can be created for each connection, From Property Group Manager:
1. Right-click on the connection and select New Property Group…
2. Specify the SYSLIB copy library search path
3. Save (Ctrl+S) and from MVS Files:
• Select Property Group → Associate Property Group…
• Click the Radio button for your Property Group

131
UNIT COBOL for z/OS - Module 5
Introduction to Sequential File Handling

Sequential Data Files and the COBOL


language constructs needed to process them
• OPEN/CLOSE/READ/WRITE,
• DATA DIVISION/FILE SECTION
• ENVIRONMENT DIVISION/INPUT-OUTPUT SECTION

Tutorial: https://www.youtube.com/watch?v=3EmmoUK4JIE

A mainframe disk drive - circa 1966


132
COBOL Program Big Picture - Topics in this module
Identification Name the executable Program-ID. CBL0006.

Define connections to external data sets: SELECT <internal file name> ASSIGN TO JCL-DDNAME
Environment Both Indexed and Sequential files
FILE SECTION
FD
Declare data variables that contain values to 77 Standalone variable declaration
be processed (manipulated) in the 01 Data Hierarchy variable definition
PROCEDURE DIVISION 05
Data 10
88 Named condition
FILLER
VALUE
Signed numeric PIC clause

Code the executable statements that IF/ELSE


Procedure MOVE
process the variable values in the DATA
PIC X MOVE behavior
DIVISION PIC 9 MOVE behavior
Literals: Numeric and Alphanumeric
DISPLAY
JCL: GOBACK
Code Paragraph
• JOB Statement PERFORM Paragraph
• EXEC Statement OPEN <Filename>
READ <Filename>
• //DD Statement WRITE <Recordname>
CLOSE <Filename>
ZOD
PAYROL01 - Sample Program Server

z/OS

Open <USERID>.LEARN.COBOL(PAYROL01) I/O

LEARN.COBOL

• MEMBER
• MEMBER
•…
• PAYROL01
•…
• MEMBER
• MEMBER
•…

134
Sequential File I/O
Since its inception COBOL's value proposition to the world of business was in the field of reports and
book-keeping, automating accounting systems, etc. In fact the language is optimized for back-office file
processing; Reading files… Processing file data… Writing files

z/OS Sequential Data File


COBOL PROGAM 113234$E£56§78{"#@/投JKJNN靠匚$£§{"erfghhj90-#@1/投IIK靠匚

File Records
113234$E£56§78{"#@/投JKJNN靠匚$£§{"erfghhj90-#@1/投IIK靠匚
Sequential File Processing Keywords

PROCEDURE DIVISION JCL 113234$E£56§78{"#@/投JKJNN靠匚$£§{"erfghhj90-#@1/投IIK靠匚

113234$E£56§78{"#@/投JKJNN靠匚$£§{"erfghhj90-#@1/投IIK靠匚

OPEN FILE Used 113234$E£56§78{"#@/投JKJNN靠匚$£§{"erfghhj90-#@1/投IIK靠匚

113234$E£56§78{"#@/投JKJNN靠匚$£§{"erfghhj90-#@1/投IIK靠匚

READ FILE To
COBOL

Process file data….. Invoke


The
WRITE RECORD
Program
CLOSE FILE SYSOUT
Report
135
136
Sequential Files - COBOL READ Statement
In a z/OS sequential data set, individual records are stored consecutively and
accessed by COBOL programs one-record-at-a-time, from the beginning to the
end of the file.
The READ operation copies data in successive records from the file to the
program's DATA DIVISION's FILE SECTION, each time a COBOL READ statement
is executed in the PROCEDURE DIVISION.

Record 1 READ FILE ……. Copy the data in Record 1 from the file to your program
Record 2 READ FILE ……. Copy the data in Record 2 from the file to your program
Record 3
READ FILE ……. Z/OS Copy the data in Record 3 from the file to your program
Record 4
Record 5 READ FILE ……. I/O Copy the data in Record 4 from the file to your program

Record 6 READ FILE ……. Subsystem Copy the data in Record 5 from the file to your program
Record 7
READ FILE ……. Copy the data in Record 6 from the file to your program
137
Sequential Files - COBOL WRITE Statement
COBOL WRITE statements reverse the process, copying records from program
variables in the DATA DIVISION's FILE SECTION to external/sequential files ➔
successively with each WRITE - which is coded in the PROCEDURE DIVISION

WRITE RECORD ……. Create a new record in the file from program data Record 1

WRITE RECORD ……. Create a new record in the file from program data Record 2
WRITE RECORD ……. Z/OS Create a new record in the file from program data Record 3

WRITE RECORD ……. I/O Create a new record in the file from program data Record 4

WRITE RECORD ……. Subsystem Create a new record in the file from program data Record 5

WRITE RECORD ……… Create a new record in the file from program data Record 6
z/OS Sequential Data Sets - Files and Records
Sequential Data Set ("Flat File"):
• A File that consists of a collection of records that contain business data
• Each record is a collection of fields
• Each field is made up of a number of characters (Bytes)

One RECORD SEQUENTIAL DATA SET

Five Note that few sequential data


sets are actually stored on
tape anymore 138
Describing Sequential Files to your Program
The ENVIRONMENT DIVISION:
• Specifies the JCL file's DDNAME which is associated with a file Data Set Name on the mainframe
• Creates an association between the JCL and program

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INTERNAL-FILE-NAME ASSIGN TO DDNAME.
SELECT INTERNAL-FILE-NAME ASSIGN TO DDNAME.

DSN= Identifies the


external file to z/OS

DSN=DDS0001.LEARN.DATA,

ASSIGN TO References //DDNAME - matches


JCL DDNAMEs in the JOB your program's
that runs your program ASSIGN TO DDNAME

INTERNAL-FILE-NAME. Select
specifies a File Descriptor (FD) in the
DATA DIVISION of your program. 139
Cracking the Code: COBOL Sequential File Processing Statements
COBOL statements used for sequential file handling involve additional
language constructs for the following areas of your program:
• ENVIRONMENT DIVISION. Describes the external files
• SELECT clauses your program will access
• ASSIGN clauses
• DATA DIVISION. Defines the data variables for
records in the external files
• FD statements
• PROCEDURE DIVISION. Processes (accesses) file data
1. OPEN statements using four new COBOL keywords
2. READ statement
3. WRITE statement
4. CLOSE statements 140
Cracking the Code: DATA DIVISION … FILE SECTION

The FILE SECTION defines a "buffer" in your program - for file data that is read from
and written to external files.

SELECT/ASSIGN clauses in the ENVIRONMENT DIVISION point to


File Descriptors (FDs) in the FILE SECTION.
File Descriptors (FDs) detail the external file I/O and are coded in the
FILE SECTION
BLOCK CONTAINS 0 RECORDS - should be the only clause you ever see
or use in the FD. BLOCK CONTAINS 0 RECORDS instructs z/OS to select
the most efficient "blocking factor" for record-I/O.

 DATA RECORD is the unit of data transfer from the file to your
program's buffer. The elementary data item PIC clauses define the data
in the file - they must add up to the length of a single record in a file.

141
Cracking the Code:
PROCEDURE DIVISION - File I/O Verbs DDS0001.LEARN.PAYROLL

The ENVIRONMENT DIVISION SELECT


ASSIGN statements create the connections
between your I/O Verbs and external data files

PAYCHECK data written to SYSOUT

1.

2. The PROCEDURE DIVISION is where you:


3.
1. OPEN a file - for INPUT or OUTPUT
2. READ a file - from an input data set
3. WRITE a record to an output data set
4. CLOSE files
4.
142
The JCL DD Statement //DDNAME DD DSN=ABCD

//STEPNM EXEC PGM=S…

//JOBNM JOB 504,SMIIH

Data definition (DD) statements define the data sets that a program
or procedure uses when it runs.
• You must code one DD statement for each data set (file) that is referenced by a program
• The order of DD statements within a job step is not usually significant.

//PAY DD DSN=DDS0001.PAYDS,DISP=SHR
The DD field contains a one-through eight-character name that identifies the JCL file entry - as
a data definition. After DD we have (minimally) two keyword parameters:
• DSN, which identifies the z/OS name of a data set.
• DISP, which specifies if the file is to be created
• DISP=NEW
Or if the file already exists:
• DISP=OLD - My JOB requires an "exclusive lock" on the file
• DISP=SHR - My JOB can share with other users

To write program output to a job's spool file, code:


143 //DDname DD SYSOUT=* (write all of the file data to SYSOUT)
//DDNAME DD DSN=ABCD

The JCL EXEC Statement //STEPNM EXEC PGM=S…

//JOBNM JOB 504,SMIIH


• The EXEC statement marks the beginning of a step within a job, and specifies the name of a
compiled program or cataloged JCL PROC to be run.
• PROCS are named collections of partial JCL. They contain one or more EXEC statements and data definition (DD)
statements, that perform frequently used functions such as Compile/Link, Sort/Merge, etc.
• Programs and cataloged procedures are stored in library data sets,
• Successfully Compiled and Link-Edited programs are stored in a LOADLIB - a library that contains "Load Modules"
• PROCs are stored in a PROCLIB
//JOBNUM1 JOB 504,SMITH PAYROLL
//STEP1 EXEC PGM=PROGRAM1
//STEPLIB DD DSN=HLQ.LOAD.LIB,DISP=SHR
//* STEPLIB = The Library name where z/OS can find the load module
//DD1 DD DSN=HLQ.INPUT
• In the above EXEC statement:
• The name field contains the EXEC step name "STEP1".
• A step name is a 1 ➔ 8 character name that identifies the job step so that other JCL statements or the
operating system can refer to it.
• A parameter (PARM=) field can pass variable data into a program

Job Control Language: JCL - an excellent online tutorial into this critical topic
144
• https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zjcl/zjclc_basicjclconcepts.htm
Some Common Mistakes
Running Programs
S013 - You didn't change EXEC PGM= or
misspelled the program name in the
COBUCLD or COBUCLG JCL
B14 - you are out of directory space in a
Library (PDS)
S0C7 - a math statement or MOVE was
attempted on a numeric variable that
didn't have valid numeric data in it.
S806 (Module Not Found) - See S013 We'll keep a running tab of these during class..
above for possible reason why
File Status 35 (U4038) - Did not define
Input or Output file correctly in JCL DD
statement
JCL Error - Misspelling of Filename - or Note that during Week 5 we will delve into
Dataset referenced by DSN= is missing the common causes and for ABENDs in
COBOL application work. 145
Review - COBOL Program Big Picture
Identification Name the executable Program-ID. CBL0006.

Define connections to external data sets: SELECT <internal file name> ASSIGN TO JCL-DDNAME
Environment Both Indexed and Sequential files
FILE SECTION
FD
Declare data variables that contain values to 77 Standalone variable declaration
be processed (manipulated) in the 01 Data Hierarchy variable definition
PROCEDURE DIVISION 05
Data 10
88 Named condition
FILLER
VALUE
Signed numeric PIC clause
Code the executable statements that
process the variable values in the DATA IF/ELSE
Procedure DIVISION MOVE
PIC X MOVE behavior
PIC 9 MOVE behavior
//DDNAME DD DSN= is the link Literals: Numeric and Alphanumeric
between your program's DISPLAY
GOBACK
SELECT/ASSIGN and the physical file Code Paragraph
PERFORM Paragraph
residing on a z/OS disk pack OPEN <Filename>
READ <Filename>
"You need a DD name in the JCL for everything to the right of WRITE <Recordname>
an ASSIGN TO statement in your program". D. Riley CLOSE <Filename> 146
Sequential File Handling - Module 5 Syntax Review
Refer to FD to
Open files
READ a file (FD)

Write a record
Matches File Section Matches JCL //DDNAME
FD statements

Refer to FD to close files

147
 Nothing to hand in ZOD
Server
Workshop 5.1 Debug CBL0006
Workshop Steps:
1.
2.
Open <USERID>.LEARN.COBOL(CBL0006)
Review the COBOL code - starting from the top of the
z/OS
PROCEDURE DIVISION.
CBL0006.

1. What does CBL0006 do (what's the output)? I/O


2. How does it work (can you follow the code pattern)?
3. Pay particular attention to the READ-NEXT-RECORD paragraph.
Compile/Link/Run CBL0006
4. View GO:RUN:PRTLINE in JES and verify your understanding of
how the code operates LEARN.COBOL
Optional Workshop:
5. Compile/Link/Debug CBL0006 • MEMBER
6. Pay close attention to the paragraph execution flow • MEMBER
•…
• CBL0006
•…
• MEMBER
• MEMBER
•…
148
 Nothing to hand in

Optional Workshop 5.2


Open PAYROL01 and analyze
the code:
• Pay particular attention to:
• The record layouts for PAYROLL
and PAYCHECK
• Variable Definitions
• COBOL Syntax
• The PROCEDURE DIVISION flow -
Performs and Paragraphs

Compile/Link and Debug


PAYROL01: Note that you will use PAYROL01 as the template or example-
code to create your own sequential file processing program -
• Monitor the values in the PAYROLL
and PAYCHECK records see next slide for details …
• Note the data mapping, record
layouts and data values from the
external file
149
Create a new program named FAVRPT that is based
on the design & coding in PAYROL01. FAVRPT should
Workshop 5.3.1 - FAVRPT display facts about your favorite musical band:

Record Layout:
From <USERID>.LEARN.COBOL make a copy of FAVS
• Name of band: 30 bytes Alpha-Numeric
and paste it onto <USERID>.LEARN.COBOL
• Number of musicians in the band: 2 digits
• Name your new module: FAVRPT • Musical genre - 12 bytes:
Make the following changes to the code in FAVRPT: • Cost - Must be less than $100.00 and include:
• CD Cost: PIC 999V99
• Change the PROGRAM-ID to FAVRPT1 • Sales tax from your state: PIC 99V99
• In the ENVIRONMENT DIVISION add an FD (File Section) • Shipping cost PIC 99V99
and the external file names to: FAVIN and FAVOUT • Band is still together - 1 Byte:

• Define the (DATA DIVISION) variables as described here


• Modify the PROCEDURE DIVISION to process three FAVIN records:
• OPEN both FD file names
• READ the FAVIN file
• Process the data: Note that you can use PAYROL01 as a "model" for
• MOVE input field data to the output record the design of FAVRPT. This is not cheating…it's
• Compute COST how COBOL programmers manage their workload.
• Write the FAVOUT record
• CLOSE both files

• Create test data in a new FAVIN data file - based on the record layout shown above - see next slide. 150
Workshop 5.3.2 - Create FAVIN Test Data Records

Input Values
Create three data records for the FAVRPT program, based
on the record layout shown below
1. Edit LEARN.FAVIN and delete all of the existing content.
2. Add three records - carefully matching the field definitions in the
record layout to the bytes in the file DDS0001.LEARN.FAVIN

• Line up the DATA DIVISION variables with the LEARN.FAVIN data


record data Byte-for-Byte ➔ File data/values line up with the record layout PIC clauses

• The use of split screen editing will make this easier


3. When you're sure that your test data works with FAVRPT,
Save the file, Compile/Link-Edit and Debug your program.
4. Email the program source file.
5. Your job output should look like this
Input data that is read into numeric fields must NOT contain decimal
places. The "implied" decimal place will line the values up automatically.
• 05 CD-COST PIC 9(3)V99.
• Data from the file: 11111
111.11
Internal result after READ..
151
151 Usable for computations
Optional Workshop 5.3.2 - Creating Professional COBOL Reports
Professional COBOL reports contain headers, footers, page#s, record counters, etc. They are not at all difficult to
create ☺ They are however time-consuming  And if you're planning on a COBOL career, you'll need to be able to
both develop and maintain them ➔

Study CBL0009 for example code and design concepts:


• COBUCLG and COBUCLD the program
• Copy the Header and Print record layouts (it's not cheating - it's called "meeting my deadline")
• Copy the code to obtain the current date
• Feel free to use your own (international) date format

• Do not worry about numeric (money) output formatting. That's covered in Module 7
• Do not worry about the PERFORM <paragraph> verb iterating thru the input file. That's covered in Module 6
152
UNIT COBOL for z/OS - Module 6
Introduction to Structured COBOL - and
Iterative Sequential File Handling

• Sequence/Selection/Iteration
• Introduction to Structured COBOL Programming
• Paragraphs & Iteration
• Read input file until EOF
• DISPLAY Statements used for Debugging
• Desk-Checking Code

Article on the COBOL PERFORM operation


https://condor.depaul.edu/jpetlick/COBOL05.html 153
COBOL Program Big Picture - Topics in this module
Identification Name the executable Program-ID. MILLARD.

Statements that connect the program to SELECT <internal file name> ASSIGN TO JCL-DDNAME
Environment Indexed and Sequential data sets.
FILE SECTION
FD
Variable declarations - Fields that contain 77 Standalone variable declaration
values to be processed in the program's 01 Data Hierarchy variable definition
05
PROCEDURE DIVISION 10
Data
88 Named Conditions
FILLER
VALUE
Signed Numeric PIC

Executable statements that process the IF/ELSE


Procedure variable values in the DATA DIVISION MOVE
PIC X MOVE behavior
PIC 9 MOVE behavior
Compute
DISPLAY
GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>
READ <Filename> AT END
COBOL WRITE <Recordname>
CLOSE <Filename>
Divisions INITIALIZE 154
155

Scalability & Legibility


Two problems with PAYROL01 and FAVRPT
1. Scalability:
• The program only processes three records
• Given the coding pattern how long would the PROCEDURE
DIVISION be if you needed to process 1K records? 10K? 1M?
2. Legibility:
• The output report is not production worthy - it's just unformatted data
• We will deal with report/output formatting in the next Module
• WRT modifying the code, PAYROL01 and FAVRPT's PROCEDURE
DIVISION is a long run-on sentence, hard to understand and change

• We need a structured solution based on an iterative COBOL coding pattern


155
PAYROL02 - Sequential File Pattern to Process All Records in a File

Keep performing 100-Main until there are


Open LEARN.COBOL(PAYROL02)
no more records in the Payroll file

156
Sequence, Selection and Iteration - Logic Patterns
DO
Loop
Sequence of instructions
Statement 1 Statement 2 Statement 3

…then… …then…
Iteration Statement

All COBOL procedural


Statement code is built from one Statement Statement

of these three patterns:


1. Sequence
2. Selection
Selection 3. Iteration Statement Statement
IF
False path True path

Branch Branch Process All Records

Conditional Statement Branching 157


The Iterative Sequential File Processing Pattern
• While there are different ways to design sequential
file handling program, one approach that is used
throughout the industry follows this pattern:
1. Initialize the program's WORKING-STORAGE data items
2. Open the files
3. Read a record
4. Process all records
until the end-of-file data set marker is detected
5. Close the files

Let's see how PAYROL02 fits this model… 158


Sequential File Design Pattern -
4.
COBOL Implementation
PERFORM <paragraph-name> 1.
UNTIL condition (conditional iteration)

("Priming Read")

Process the record - WRITE output


Read the next record - check for EOF
2.

READ <filename> 3.
AT END conditional check & imperative statement

5. 159
Sequential File Logic Pattern - Structured Design using PERFORM:Paragraph
From the beginning of the PROCEDURE DIVISION, PERFORM "next-level" paragraphs:
• Housekeeping-para (1 X)
• Perform open files paragraph
• OPEN FILES
• Perform "priming read"
• READ Input File(s) - AT END set END-of-FILE Flag
• Perform WORKING-STORAGE field initialization
• INITIALIZE …or… MOVE statements

• Main Business Logic-para (UNTIL End-of-File) Level 0


PROCEDURE
• Perform para… DIVISION
• Perform para…
• Perform Read-Next Level 1
Housekeeping "Main" Wrap-Up
• Wrap-up-para (1 X)
• Perform Close Files
• Perform final counts
Audit Level 2
• Perform Displays Open File Priming Read Business Logic Read Next
Run Totals
Close Files

• GOBACK 160
PAYROL02 - Sample Structured
Sequential File Pattern
The structure of PAYROL02

PERFORM statements "chain" together


business logic contained in paragraphs

Questions on PERFORM:Paragraph as the


industry-standard approach to structuring
large complex processing designs? 161
Initializing WORKING-STORAGE Variables
• Recall from an earlier module that:
• Your Load Module is copied from its Load Library into an "Address Space"
• The Address Space's storage is not pre-initialized. Your DATA DIVISION variable pick up whatever "garbage" values
leftover in the Address Space at load time
• Until a value is moved to a variable - the data in that variable's storage is "unknown"

Your Load Module


PROGRAM-ID……………………………
Address ………………………………………........
Space DATA DIVISION (Data)………………..
…………………………………………….
PROCEDURE DIVISION (Instructions)
……………………………………………..
…also remember…
• If you attempt to do math using numeric data that does not contain valid numbers you will have a problem … either a
mainframe ABEND will occur, or incorrect computational will result

• Solution: Initialize WORKING-STORAGE numeric fields at the beginning of the PROCEDURE DIVISION.
• Three options:
1. VALUE clause - part of a field definition in the DATA DIVISION
2. MOVE statement - coded in the PROCEDURE DIVISION
3. INITIALIZE statement - coded in the PROCEDURE DIVISION 162
Cracking the Code: INITIALIZE
INITIALIZE is coded in the PROCEDURE DIVISION.
It is functionally equivalent to one or more MOVE statements
and is a convenient way to set the variables you're going to
work with to either blanks or zeros:
• PIC X variables ➔ blanks
• PIC 9 variables ➔ zeros

Field PIC Field value before INITIALIZE Field value after INITIALIZE

9(5) 12345 00000

X(5) AB123 bbbbb

Notes:
• INITIALIZE is usually executed at the beginning of a program
• INITIALIZE can reference either elementary and group variables
• There are a large number of more sophisticated use cases with INITIALIZE
163
Cracking the Code: End of Data Set Marker
• The z/OS I/O subsystem maintains an "End of Data Set Marker" into the file act
after the last record in the file.

• The COBOL READ operation has an "AT END" clause which is invoked when the End of Data Set Marker is
encountered.

• Allowing you to take procedural action…usually by doing


something setting a WORKING STORAGE variable to "Y"

In this pattern:
• The program performs 100-Main UNTIL PAYMENT-EOF = 'Y'
• 100-Main does business logic…………………………………………
• The last statement in the paragraph performs another 400-Read-Payroll
• 400-Read-Payroll reads records. When the End of Data Set Marker
is reached the AT END clause of the READ statement moves "Y" to
PAYMENT-EOF

164
Cracking the code: DATA DIVISION 88-Level Variables
• 88-Level data items - Are sometimes called "Conditional Names"
• They are used to make programs more readable
and understandable

• They are defined without a PIC clause


• But must have a VALUE clause that will be
referenced as a conditional test in the
PROCEDURE DIVISION

- Define an 88-level variable:

- Test for the 88-level condition:

- Set the variable value to be tested:

165
Desk-Checking Code
Desk-Checking = "proof-reading your code". Basically, like proof-reading a document, Desk-Checking is a
widely-used means of catching logic errors early - and relatively inexpensively. While the Debugger is our secret
weapon to detect and analyze logic errors and discrepancies between what we intended to code and what the
COBOL compiler generated, the Debugger does not know "what" the program's specs are. Proof-Reading code
and COBOL Comments - is the only means of discovering that.

• ISPF Users:
Be able to follow the PROCEDURE DIVISION Logic

166
Review - COBOL Program Big Picture
Identification Name the executable Program-ID. CBL0006.

Statements that connect the program to SELECT <internal file name> ASSIGN TO JCL-DDNAME
Environment Indexed and Sequential data sets.
FILE SECTION
FD
77 Standalone variable declaration
Variable declarations - Fields that contain 01 Data Hierarchy variable definition
values to be processed in the program's 05
10
Data PROCEDURE DIVISION 88 Named Conditions
FILLER
VALUE
Signed Numeric PIC

IF/ELSE
Procedure Executable statements that process the MOVE
variable values in the DATA DIVISION PIC X MOVE behavior
PIC 9 MOVE behavior
Compute
DISPLAY
GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>
Additional details on end-of-file logic: READ <Filename> AT END
COBOL • https://www.techopedia.com/definition/7051/end-of-file-eof WRITE <Recordname>
• CLOSE <Filename>
Divisions https://en.wikipedia.org/wiki/End-of-file
INITIALIZE 167
 Nothing to hand in

Workshop 6.1a - Desk-Check WARDRPT


Open WARDRPT and take 5 minutes to Desk-Check the business
logic in the PROCEDURE DIVISION.

Make sure you understand "HOW" the program operates … not


WHAT it's doing.

(ZOD/IDz users)
• Whenever a variable is referenced, hover over it to pick
off its WORKING-STORAGE declaration
• With the code opened in the editor, right-click and select:
Show In ➔ Program Control Flow
(see next slide…)

168 168
 Nothing to hand in

Workshop 6.1b - Desk-Checking: TRTMNT

If you are using ZOD or IDz…


1. Right-Click in the diagram and
select: Hide EXIT Nodes
With the code opened in the editor, right-click and select:
2. What kind of logic model design
Show In ➔ Program Control Flow is TRTMNT?

Desk-Check PAYROL02
Be able to follow the
PROCEDURE DIVISION Full-screen view of the
Logic Program Control Flow diagram 169
 Nothing to hand in

Optional Workshop 6.2 - Debug PAYROL02


• Debug (COBUCLD) PAYROL02
• Step thru the code
• What happened
• Why did it happen?

• Fix the problem


Order of operations:
1. OPEN a file - for INPUT or OUTPUT
2. READ a file - from an input data set
• What does AT END do - and how is it used in the
PROCEDURE DIVISION?
3. WRITE a record to an output data set
4. CLOSE files
• Compile/Link/Debug
• Better
170
Symbol Value

Negative Numbers in an External File { -0


J -1
• In Module 9 you will learn about the USAGE clause, numeric values and data
representation. Until then - if you wish to pass a negative value to your program K -2
using a sequential file and a Display (Zoned) Decimal variable you must change L -3
the last digit in the number to the appropriate signed-negative number symbol ➔ M -4
N -5
Test Code O -6
P -7
Q -8
Optional Workshop R -9
• Change PAYROL02 to accept a negative number
• Add a negative number to your copy of DDS0001.LEARN.PAYROLL
• Debug the program and validate your work

Negative values 171


Workshop 6.3 - Enhancements to FAVRPT
Modify FAVRPT so that it writes a single line of output text for each of the input (FAVIN)
records read:
1. Create 3 new FAVIN records in <TSOID>.LEARN.FAVIN
2. Edit FAVRPT and use the sequential file processing logic in PAYROL02 as a design pattern in
FAVRPT in order to:
• PERFORM paragraphs UNTIL <end-of-file>
• READ … AT END
• MOVE the individual FAV fields from input to output. Compute the CD Cost for each FAVIN record
3. Test your program - and when complete, email your code

Optional Testing Workshops


• Test your code with an empty input file
• Copy LEARN.FAVIN to your TSO-ID. Edit the file and change the numeric values to all 9's
• Check for Truncation and overflow 172
Optional Workshop 6.3a - Reporting Enhancements to FAVRPT
Date: yyyy/mm/dd Favorite Artists Report

Artist Number of Musical CD SHIP TAX TOTAL

Name Musicians Genre Cost Cost Cost

==================== ========= ========= ======== ======== ======== ==========

XXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXX nnnnnnnn nnnnnnnn nnnnnnnn nnnnnnnnn

XXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXX nnnnnnnn nnnnnnnn nnnnnnnn nnnnnnnnn

XXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXX nnnnnnnn nnnnnnnn nnnnnnnn nnnnnnnnn

Number of Artists in this Report: nn

You will need:


• Multiple Output "print" lines in WORKING-STORAGE to write from
• A record "accumulator" variable - that you add to
• A "Current Date" code pattern - check out Workshop 13.3 173
Optional Workshop 6.4 - Coding Enhancements to FILECALC
Modify FILECALC so that it provides square-root calculations:
1. From: https://www.ibm.com/support/knowledgecenter/SSQ2R2_9.5.1/com.ibm.ent.cbl.zos.doc/PGandLR/tasks/tpbeg18.html -

find the sample/code that produces a square root result ➔


2. Create a small program to test out the square root formula
2. There are two options in this program - choose one or the other
2. An algebraic statement that raises to the power of .5
3. A COBOL "Intrinsic Function" - Sqrt(y)

3. Compile/Link/Debug your test program

4. When you're satisfied that the test program works, modify FILECALC and add the SQRT function:
2. Change 100-Main - Add an ELSE IF for a Square Root operation
3. Add a 750-Square-Root paragraph for the statement you chose
4. Open <YOURID>.LEARN.JCL(DEBUGCAL).
5. Add a few records to the //INVALS DD instream data for your square root calculation
6. Compile/Link the new version of FILECALC - then run: DEBUGCAL - and verify your results
7. Replace the "OPERATION = "…" clauses in 100-Main so that they use 88-level variables:
174
 Nothing to hand in
PERFORM 400-Read
Optional Workshop 6.5 - Priming Read Statements
In PAYROL02 we're performing the read operation both
before the loop and at the end of the loop… why?
To find out why the "priming read" is an important
aspect of the sequential file processing pattern:
1. Edit PAYROL3A.cbl
• In 100-Initialize, comment out the PERFORM 400-Read statement
2. Edit COBUCLD
• Remove (delete) the data records from the //PAYROLL DD *
• Making it an empty input file.
3. Compile and Link/Edit the program
4. Re-run COBUCLDH
5. When the job completes have a look at the PAYCHECK
SYSOUT in the JES spool.
PERFORM 600-Close Files.
GOBACK
175
Optional Topic - What other COBOL Logic Patterns and Models are there?
Many………. To name just a few:
• Systemic:
• Structure the code tightly, based on the application business process
Rarely seen - but the best & easiest code to maintain

• Three tier:
1. UI Processing
2. Business Logic Processing
3. Database and File read/write Processing
This was once the "prime directive" of modern application development

• Online:
1. Retrieve user input
2. Process
3. Return display output to users
Online application design is based upon the requirement of fastest-possible-response-time. This brings
with it an entirely different problem/design space 176
UNIT COBOL for z/OS - Module 7
COBOL Arithmetic and Output Report Formatting

• Numeric Edited Fields


• Deeper dive into COBOL Data Assignments
• Arithmetic Statements
• ADD
• SUBTRACT
• MULTIPLY
• DIVIDE
Article on COBOL arithmetic instructions
https://condor.depaul.edu/jpetlick/COBOL04.html
177
COBOL Program Big Picture - Topics in this module
Identification Name the executable Program-ID. MILLARD.

SELECT <internal file name> ASSIGN TO JCL-DDNAME


Statements that connect the program to
Environment Indexed and Sequential data sets. FILE SECTION
FD
77 Standalone variable declaration
Variable declarations - Fields that contain 01 Data Hierarchy variable definition
05
values to be processed in the program's 10
PROCEDURE DIVISION 88 Named condition
Data Signed Numeric PIC
USAGE IS COMP…USAGE IS COMP-3
FILLER/VALUE
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point
BLANK WHEN ZERO, JUSTIFIED RIGHT

Executable statements that process the IF/ELSE


MOVE
Procedure variable values in the DATA DIVISION PIC X MOVE behavior
PIC 9 MOVE behavior
Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
DISPLAY
GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>
READ <Filename> AT END

COBOL WRITE <Recordname>


CLOSE <Filename>

Divisions INITIALIZE
178
Not Ready for Prime Time
There are still problems with our Payroll program
1. Legibility and Accuracy
• The output report is not production worthy:
• Things do not line up well
• The output numeric values need a lot of work:
• The high-order zeroes need to be suppressed
• Positive/Negative signs may be needed
• $$ signs are standard - and missing
2. There are many different kinds and nuances for math computations - based
on business calculations.
3. In the real world there are far more complex evaluative conditions you will be
expected to code, especially for data editing programs. you will need to know:
• Compound ("nested") IF statements
• And how best to structure code to handle complex conditional expressions

We'll cover conditional expressions in Module 8 179


Introducing Numeric Edited Fields for Report-Output
Standard Numeric Field definitions:
• PIC 9(6)V99 6 digits to the left of the implied decimal place and 2 digits to the right
• PIC V99 2 decimal digits
• PIC 9(7)V9(2) 7 digits to the left of the implied decimal place and 2 digits to the right
• PIC S99V999 2 digits and 3 decimal digits, the sign is maintained internally
• PIC S999 3 digits, the sign is maintained internally

Production-quality "Numeric Edited" values - consist of: zero-suppressed fields, Fixed


and Floating $, commas, periods, and other "insertion characters".
WORKING-STORAGE SECTION.

77 PRICE PIC 9(5)v99.

77 EDITED-PRICE PIC $zz,zz9.99.

PROCEDURE DIVISION.

MOVE 12345.6 TO PRICE.


Notes: $12,345.60
• Dollar sign
MOVE PRICE TO EDITED-PRICE.
• Comma
DISPLAY EDITED-PRICE. • Decimal place period 180
Cracking the Code - Numeric Edited PIC Clauses
Some of the common numeric
editing characters include:
Z Suppresses leading zeros - by turning
them into blanks (spaces).

. Displays the decimal point in the number as


a period

, Displays a comma in the number


$ Displays a "fixed-position" $ in the field
$$ Replaces 'leading zeroes' with a "floating"
$ in the field - that will align with numeric data

* Suppresses leading zeroes replacing them


with asterisks

+- Will add a positive (plus sign) OR minus


sign indicator either to the left or right side of
the output data 181
Cracking the Code - Numeric Edited PIC Clauses
There are a number of rules for the use of
numeric edited PIC clauses, including but SYSOUT
not limited to: DISPLAY
• Can't mix Suppression Characters: Results
$$,ZZZ9.99
Z,**9.99
• Can't use $ suppression to the right of
the decimal place
• Etc.

Read the formal rules from the IBM page


(link below) then try several them out with
your TESTCOB program & COBUCLG

IBM InfoCenter page for COBOL


Numeric Edited fields
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlddezsr.htm 182
Cracking the Code - Mismatched Numeric Edited PIC Clauses
Review - Numeric Variable Moves:

When numeric move operations are combined with numeric edited PIC Clauses
math & assignments, the results must be watched carefully for loss of significant digits
183
Mismatched Numeric Editing Examples - Demonstration
Input Value Working-Storage PIC Numeric Edited PIC Output Value
234567 Moved to ➔ 9(5)V9 Moved to ➔ Z,ZZZ.99 4,567.00
-1234 Moved to ➔ 9999 Moved to ➔ -Z,ZZ9 b1,234
000178 Moved to ➔ 9(6) Moved to ➔ ***,*** ****178
-1234.99 ➔ S9999 ➔ -ZZZ,ZZ9 -bb1,234
000078 Moved to ➔ 9(6) Moved to ➔ 999,999 000,078
002178 Moved to ➔ 9(6) Moved to ➔ ***,*** **2,178
120117 Moved to ➔ 9(6) Moved to ➔ 99/99/99 12/01/17
20034.5 Moved to ➔ 9(3)V9 Moved to ➔ $$9.99 $34.50
123456 Moved to ➔ 9(6) Moved to ➔ 999,999 123,456
-754 Moved to ➔ S9999 Moved to ➔ Z,ZZ9 bbb754
20034 Moved to ➔ 9(4) Moved to ➔ $*,***.99 $***34.00
76543 Moved to ➔ 999V99 Moved to ➔ ZZ,ZZ9 bb543
12345.6 ➔ 9(5)V99 ➔ $ZZ,ZZ9.99 $12,345.60
0000 Moved to ➔ S9(5)V99 Moved to ➔ $9,999.99 BLANK WHEN ZERO. bbbbbbbbb
1002.34 Moved to ➔ 9(4)V99 Moved to ➔ ZZ9.99 bb2.34
Given the Input Values, Working-Storage Picture clauses and based on the COBOL rules for
Numeric Editing symbols - explain the Output Values shown above.
184
185
COBOL Reports: Field Justification
• The default field justification for output alphanumeric data is Left
• To justify PIC X data Right by using the JUSTIFIED … or … JUST (abbreviation)
clause in your elementary field definition

Example:
77 COMPANY-NAME-L PIC X(60). *> Left Justify is the COBOL default
77 COMPANY-NAME-R PIC X(60) JUSTIFIED RIGHT.

PROCEDURE DIVISION.
MOVE 'CORPNAME-JUST-LEFT' TO COMPANY-NAME-L.
DISPLAY CORPORATION-L.
*
MOVE 'CORPNAME-JUST-RIGHT' TO COMPANY-NAME-R.
DISPLAY COMPANY-NAME-R.
Cracking the Code: Additional COBOL Arithmetic Keywords
COBOL's arithmetic verbs: ADD, SUBTRACT, MULTIPLY, DIVIDE, COMPUTE
ADD - adds the first number to the second.

• ADD VAR1 TO VAR2 ➔ (VAR1 + VAR2) - the total is stored in VAR2

• GIVING can be specified: ADD VAR1 TO VAR2 GIVING VAR3 - the total is stored in VAR3

SUBTRACT - subtracts the first number FROM the second.

• SUBTRACT VAR1 FROM VAR2 ➔ (VAR2 - VAR1) - the difference is stored in VAR2

• GIVING can be specified: SUBTRACT VAR1 FROM VAR2 GIVING VAR3 - the difference is stored in VAR3

MULTIPLY - totals the first number times the second.

• MULTIPLY VAR1 BY VAR2 ➔ (VAR1 * VAR2) - the product is stored in VAR2 Arithmetic truncation and
rounding errors can occur
• GIVING can be specified: MULTIPLY VAR1 BY VAR2 GIVING VAR3 - the product is stored in VAR3
on any of these
DIVIDE - calculates the first number divided by the second - the first number is the divisor operations if the result
• DIVIDE VAR1 INTO VAR2 ➔ (VAR2 / VAR1) - the quotient is stored in VAR2
fields are defined with too
little numeric precision.
• GIVING can be specified: DIVIDE VAR2 INTO VAR1 GIVING VAR3 - the quotient is stored in VAR3

COMPUTE - provides a way for you to express arithmetic algebraically

• COMPUTE VAR3 = VAR1 * VAR2

• COMPUTE VAR3 = VAR1 + ( (VAR2 * VAR3) / VAR3 )


186
• COMPUTE VAR2 = VAR1**2 - VAR1 "squared" (Exponentiation)
Cracking the Code: ROUNDED and ON SIZE ERROR
ON SIZE ERROR is used to specify COBOL logic that takes place when a size error occurs for a numeric data item used to
store the results of an arithmetic expression. A numeric size error condition occurs in the following common situations:
• The result of the arithmetic operation is larger than the fixed-point field that is to hold it
• Division by zero
0

TESTCOB!
Code the ON SIZE ERROR clause after the math portion of the statement

ROUNDED After decimal point alignment, the number of places in the fraction of the result of an arithmetic operation is
compared with the number of places provided for the fraction of the resultant identifier. When the size of the fractional result
exceeds the number of places provided for its storage, truncation occurs unless ROUNDED is specified. When ROUNDED is
specified, the least significant digit of the resultant identifier is increased by 1 whenever the most significant digit of the excess is
greater than or equal to 5.

Code the ROUNDED clause immediately following the variable name (result)

Further study:
• ROUNDED: https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlpdsrou.htm

• SIZE ERROR: https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlpdssiz.htm


187
Cracking the Code: Order of Evaluation - COMPUTE
Default Sequence of Operations for COBOL COMPUTE statements:
1. Exponentiation
2. Multiply … Divide
Example. Multiple orders of both: ITEM1 & ITEM2
3. Add … Subtract
COMPUTE ITEM-TOTAL = (ITEM1 + ITEM2) * QTY
Will be executed as follows: ITEM1 + (ITEM2 * QTY)
What happens when the operations are mixed? What is wrong with this (if you're the seller) ?
?

As in Algebra equations, the order in which the COMPUTE statement operations are
performed will affect output/results. COBOL Programmers routinely force the operation
order using parenthesis:
COMPUTE TOT-PRICE = (PRICE * DISCOUNT) + TAX
…vs…
COMPUTE TOT-PRICE = PRICE * (DISCOUNT + TAX)

Take-away: Always use parenthesis. Make your equations obvious to


the next programmer who maintains the code 188
Module 7 Review
COBOL Arithmetic and Output Report Formatting
• Create simple COBOL "TESTCOB" program that illustrates
"cause and effect" for language features
• Numeric Edited Fields:
**
$$
ZZ
• Matched assignment results
• Mismatched PIC Clause issues ("idiosyncrasies")
• Arithmetic Statements - all COBOL options
• ON SIZE ERROR
• ROUNDED
• COBOL hierarchy of arithmetic expression/evaluation
18
COBOL Program Big Picture - Topics in this module
Identification Name the executable Program-ID. MILLARD.

SELECT <internal file name> ASSIGN TO JCL-DDNAME


Define connections to external data sets:
Environment Both Indexed and Sequential files FILE SECTION
FD
77 Standalone variable declaration
Declare data variables that contain values to 01 Data Hierarchy variable definition
05
be processed (manipulated) in the 10
PROCEDURE DIVISION 88 Named condition
Data Signed Numeric PIC
FILLER
VALUE
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point
BLANK WHEN ZERO, JUSTIFIED RIGHT

Code the executable statements that IF/ELSE


MOVE
Procedure process the variable values in the DATA PIC X MOVE behavior
DIVISION PIC 9 MOVE behavior
Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
DISPLAY
GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>
READ <Filename> AT END
WRITE <Recordname>
CLOSE <Filename>
INITIALIZE
 Nothing to hand in

Workshop 7.0 - TESTCOB and Numeric Edited PIC Clauses


Create TESTCOB - and prove out at least
five or six of the COBOL language
syntax rules for numeric edited fields.
Try out:
• Right Justification of PIC data
• Try mixing suppression characters:
$$,ZZZ9.99
*,**9.99

Read the formal rules in the link below,


then try several them out with your
TESTCOB program.

IBM InfoCenter page for COBOL


Numeric Edited fields
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlddezsr.htm
191
 Nothing to hand in 192
Mismatched Numeric Editing Results - Optional Workshop 7.1
Input Value Working-Storage PIC Numeric Edited PIC Output Value
234567 9(5)V9 Z,ZZZ.99 4,567.00
-1234 9999 -Z,ZZ9 b1,234
000178 9(6) ***,*** ****178
-1234.99 S9999 -ZZZ,ZZ9 -bb1,234
000078 9(6) 999,999 000,078
002178 9(6) ***,*** **2,178
120117 9(6) 99/99/99 12/01/17
20034.5 9(3)V9 $$9.99 $34.50
123456 9(6) 999,999 123,456
-754 S9999 Z,ZZ9 bb543
20034 9(4) $*,***.99 $***34.00
76543 999V99 ZZ,ZZ9 bbb765
12345.6 9(5)V99 $ZZ,ZZ9.99 $12,345.60
0000 S9(5)V99 $9,999.99 BLANK WHEN ZERO. bbbbbbbbb
1002.34 9(4)V99 ZZ9.99 bb2.34

Use TESTCOB to copy/paste/run and verify several of the above


mismatched variable assignment/truncation COBOL idiosyncrasies.
Workshop 7.2 - Enhancements to FAVRPT - Report Statistics

Modify FAVRPT as follows:


1. Add a WORKING-STORAGE SECTION with fields like the above - to support a few simple report statistics:
1. A count of the number of records written; 2. A grand total of all CD sales; 3. The average CD sale.
• Utilize Numeric Edited Variable declarations. Your choice: $, Zero Suppression, Commas, etc.
2. Add the following code to the PROCEDURE DIVISION, after each FAVRPT-REC WRITE statement
1. Add +1 to REC-KTR-OUT
2. Add the calculated COST-CD to COST-TOTAL
3. At the end of the program (after all the input records have been read) display the following statistics:
1. Number of records
2. Gross Revenue (COST-TOTAL-OUT)
3. Average CD Sale COST-TOTAL / Number of records

Optional/Challenge Exercise: Add code to find and calculate the Highest & Lowest CD cost. Print
them out (DISPLAY them) at the end of the program with an appropriate message.
193
 Nothing to hand in

Workshop 7.3 - Program Testing


Part 1.
The SMPLCALC program contains a couple of bugs. Try and spot them
by reading the code shown here. Then Compile, Link-Edit and Debug
the code. Fix the problems.

Part 2.
Enhance SMPLCALC. Add an exponentiation function, then add a
square root function.

Part 3.
Add 88-level variables to THE-FUNCTION:
• 88 ADD-OP VALUE "A".
• SUBTRACT-OP
• DIVIDE-OP
• MULTIPLY-OP
• … <TSOID>.LEARN.COBOL(SMPLCALC)
Change the COMPUTE-AND-DISPLAY paragraph. Utilize the 88-Level
condition names in the IF conditions:
• IF ADD-OPERATION….
• IF SUBTRACT-OPERATION…
194
• …
 Nothing to hand in

Workshop 7.4 - Mortgage Calculation

1. Open the program: MORTGAGE and analyze the


algebraic COMPUTE statements
2. Compile/Link and Debug the program.
1. Step (Click F5) to debug the code
2. Monitor Expression: FACTORS-WS
3. Note the change in variable values that happens
with each Step (F5)
4. What was the final MONTHLY-PAYMENT:
• When Computed algebraically
• And when using the COBOL "ANNUITY" Function?

195
 Nothing to hand in

Workshop 7.5 - Mortgage Calculation

Dial: 1 (800) Google


• Using the Internet, research the COBOL
Intrinsic Function: ANNUITY
https://www.ibm.com/support/knowledgecenter/SSQ2R2_9.
5.1/com.ibm.ent.cbl.zos.doc/PGandLR/ref/rlinfann.html

• Which code would be easier to write,


test & maintain?

196
 Nothing to hand in

Optional Workshop 7.6 - Arithmetic Precision


Open the MORTGAGE source file, and find the COMPUTE statement below.
• What might happen to MONTHLY-PAYMENT if INT-RATE was defined with a lower precision?
(Don't guess - let's find out):
• Compile/Link and Debug MORTGAGE
• Jot down the value of MONTHLY-PAYMENT.
• Duplicate INT-RATE in Working-Storage
• Define your new field as: PIC V9999.
• Comment out the correct INT-RATE definition then Compile/Link and Debug MORTGAGE again.
• What happened? Why?
• Finally, change INT-RATE's definition to: PIC V99 and repeat the above. What happened now? Why?

197
 Nothing to hand in

Optional Workshop 7.7 - MATH Examples


MATHXMP2 and MATHXMPL are
programs that exercise many of
the COBOL arithmetic functions
and expose concerns like;
• TRUNCATION
• ROUNDING
• ON SIZE ERROR

Part 1.
Compile/Link/Debug
MATHXMP2. Set a Monitor on:
ELEMENTARY-MATH-FIELDS
Examine the cause & effect of the
various math statements on the Part 2. When you are satisfied that you understand the arithmetic
WORKING-STORAGE variable problems MATHXMP2 is pointing out - repeat this process with:
definitions.
MATHXMPL.
Look for the above problems;
Truncation, On Size Error, etc. This program has much more interesting computations. It exposes the kinds
errors that happen when COBOL's specific rules are broken. 198
 Nothing to hand in

Optional Workshop 7.8 - Numeric Edited Fields


Part 1. Open the program: MOVXMPLN. Split the screen and study the WORKING-STORAGE field definitions side-
by-side with the PROCEDURE DIVISION MOVE and DISPLAY statements. Predict what the output will look like.

Part 2.
Compile/Link & Run
the program ➔
From
GO:RUN:SYSOUT, GO:RUN:SYSOUT
compare the results
against your
Desk-Checked
expectations ➔

199
Optional Workshop 7.9 - Internal Arithmetic Precision
77 ACCT-VAL-A PIC S9(15)V9(02) COMP-3.
Create a new 77 ACCT-VAL-B-01 PIC S9(16)V9(02) VALUE 0.
77 ACCT-VAL-B-02 PIC S9(13)V9(05) VALUE 0.
version of 77 ACCT-VAL-C PIC S9(16)V9(02) VALUE 0.
TESTCOB with the 77 ACCT-RESULT PIC S9(15)V9(02) VALUE 0.
……………
following code ➔ ……………
MOVE 2500.87 TO ACCT-VAL-A.
MOVE 12285 TO ACCT-VAL-B-01.
MOVE 12285 TO ACCT-VAL-B-02.
Run or Debug the MOVE 4387.5 TO ACCT-VAL-C.
COMPUTE ACCT-RESULT ROUNDED =
program and note (ACCT-VAL-A / ( ACCT-VAL-B-01 + ACCT-VAL-C) * 100 ).
the differences in DISPLAY ACCT-RESULT.
results. COMPUTE ACCT-RESULT ROUNDED =
(ACCT-VAL-A / ( ACCT-VAL-B-02 + ACCT-VAL-C) * 100 ).
DISPLAY ACCT-RESULT.

eMail your instructor the reason for these precision issues 200
UNIT COBOL for z/OS - Module 8

Deep-Dive into COBOL Conditional


Statements
• IF THEN ELSE statements
• Relational operators (< > etc.).
• Boolean operators: AND OR
• New fields in the FAVRPT file
• Category
• Division
• Bonus

If/Then/Else Tutorial:
https://www.youtube.com/watch?v=uO9UIdotFQo 201
COBOL Program Big Picture - Topics in Module 8
Identification Name the executable Program-ID. FAVRFP.

SELECT <internal file name> ASSIGN TO JCL-DDNAME


Environment Statements that connect the program to
Indexed and Sequential data sets. FILE SECTION
FD
77 Standalone variable declaration
Variable declarations - Fields that 01 Data Hierarchy variable definition
05
contain values to be processed in the 10
Data program's PROCEDURE DIVISION 88 Named condition
Signed Numeric PIC
FILLER
VALUE
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point
BLANK WHEN ZERO

Procedure Executable statements that process the IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields
variable values in the DATA DIVISION Compound IF, Nested IF
EVALUATE
Signed Conditions, Class Conditions
MOVE
PIC X MOVE behavior
PIC 9 MOVE behavior
Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
DISPLAY
GOBACK
COBOL Code Paragraph
PERFORM Paragraph UNTIL <condition>
Divisions OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
INITIALIZE
Counters, Accumulators, Flags
COBOL Conditional Statements
Six types of Conditional Expressions in COBOL
1. Relation condition: IF VAR-X = VAR-Y … IF VAR-X >= VAR-Z
2. Sign condition: IF NUMVAR-X IS POSITIVE … IF NUMVAR-Y IS ZERO
3. Class condition: IF ALPHA-VAR-X IS NUMERIC
4. Condition-name 88-Level Data Item: IF 88-LEVEL-CONDITION
5. Compound/Nested conditions: IF VAR-X = VAR-Y OR VAR-Z
6. EVALUATE (Case Structure): EVALUATE VAR-X, WHEN LITERAL-VALUE
IBM Knowledge Center: https://www.ibm.com/support/knowledgecenter/SSUFAU_1.0.0/com.ibm.debugtool.doc/rmdita/rcmdico.html
TechAgilist.com: https://www.techagilist.com/mainframe/cobol/conditional-expressions-use-in-cobol/
203
False
Cracking the Code: Basic IF Condition VAR1 =
VAR2
True

IF [condition] THEN [statement(s)] ELSE [statements] END-IF.


SUBTRACT
If the condition tests true, all COBOL statements up to the ELSE are executed. ADD +1 TO
1 FROM
VAR-EQUAL
If there is no ELSE all statements up to the END-IF or period are executed. VAR-EQUAL

If the condition does not test true, all statements after the ELSE clause are IF VAR1 = VAR2
executed to the END-IF or period. THEN
ADD +1 TO VAR-EQUAL
MOVE VAR2 TO PRINT-REC
• THEN and END-IF are optional ELSE
• But END-IF is recommended for readability SUBTRACT 1 FROM VAR-EQUAL
• Indenting also highly-recommended for readability MOVE VAR1 TO PRINT-REC
• If END-IF is not used, the period becomes the scope-terminator END-IF

• NEXT SENTENCE or CONTINUE can be used There is a difference between NEXT SENTENCE
and CONTINUE
• To avoid performing any operation if a condition exists This is covered in Module 11
• To execute instructions only when the ELSE condition is met

• Numeric operands are compared algebraically


• Alphanumeric comparisons are cAse SEnsiTIvE
• Alphanumeric operands are compared byte for byte, from LEFT ➔ RIGHT 204
Relational Comparison Operators
Cracking the Code: Relational Comparison Operators >
<
COBOL provides eight relational operators ➔ =
You can use math/comp-sci symbols or English vocab: NOT =
>=
• = … NOT =
<=
• IS EQUAL TO … IS NOT EQUAL TO
NOT <
• < … > NOT >
• IS LESS THAN … IS GREATER THAN
• <= … >=
• IS LESS THAN OR EQUAL TO … IS GREATER THAN OR EQUAL TO
• IS NOT EQUAL TO … IS NOT LESS THAN … IS NOT GREATER THAN, etc.
English syntax: Math syntax:
IF VAR1 IS EQUAL TO VAR2 IF VAR1 = VAR2
IF VAR1 IS NOT EQUAL TO VAR2 IF VAR1 NOT = TO VAR2
IF VAR1 IS LESS THAN VAR2 IF VAR1 < VAR2
IF VAR1 IS LESS THAN OR EQUAL TO VAR2 IF VAR1 <= VAR2
IF VAR1 IS GREATER THAN VAR2 IF VAR1 > VAR2
IF VAR1 IS GREATER THAN OR EQUAL TO VAR2 IF VAR1 >= VAR2
Cracking the Code: How IF Conditions are Evaluated - PIC X
IF FLD1 > FLD2 …
• PIC X fields or literals are compared byte for byte - proceeding from LEFT ➔ RIGHT
• The comparison will stop at the first byte that satisfies the condition
• If the operands are of different sizes, the shorter operand is moved into a temporary field the size of the
longer operand before the byte for byte comparison starts
• Group data items are treated as Alphanumeric compares
• On System z (mainframes) the EBCDIC collating system will affect range ( < … > )comparisons

77 FLD1 PIC X(6) A B C D E F b b

77 FLD2 PIC X(8) A B C D E F 1 b


MOVE 'ABCDEF1' TO FLD1, FLD2


IF FLD1 > FLD2 206
Cracking the Code: How IF Conditions are Evaluated - PIC 9
IF FLD1 = FLD2 …
• PIC 9 fields and numeric literals are compared algebraically:
• Their numerical value - not the PIC clause determines the outcome of the comparison
• Decimal points are aligned by COBOL
• The length of the operands is not significant
• Unsigned numeric items are considered positive
77 FLD1 PIC 9(4)v999. 0 1 4 3 2 1 0
77 FLD2 PIC S9(5)v99.

0 0 1 4 3 2 1
MOVE 143.21 TO FLD1, FLD2
Implied Decimal Point
IF FLD1 = FLD2 …

Mixed PIC X and PIC 9 comparisons


The PIC 9 field is treated as if it were an alphanumeric field and the IF test is evaluated as an alphanumeric
compare. Note that mixing PIC 9 and PIC X data in IF tests is not recommended 207
Field Comparisons - Checkpoint
MOVE 'ABC' TO FLD1, FLD2. 01 GROUP-FLD.
IF FLD1 < FLD2 ??? 05 FLD1 PIC X(4).
MOVE 'ABCDE' TO FLD1, FLD2. 05 FLD2 PIC X(6).
IF FLD1 = FLD2 ??? 77 ALPHA-FLD PIC X(8).
77 NUM-FLD1 PIC 9(4).
MOVE 'ABCDEF' TO GROUP-FLD, ALPHA-FLD.
77 NUM-FLD2 PIC S9(3)V99.
IF GROUP-FLD = ALPHA-FLD???
IF ALPHA-FLD = FLD2??? Consider the following W-S Definitions

MOVE ZEROES TO NUM-FLD1, NUM-FLD2 Which path (THEN/ELSE) will each of


IF NUM-FLD1 = NUM-FLD2???  these IF statements take?

MOVE 7.1 TO NUM-FLD1, NUM-FLD2


IF NUM-FLD1 = NUM-FLD2???
MOVE -6 TO NUM-FLD1, NUM-FLD2
IF NUM-FLD1 = NUM-FLD2??? 208
Condition-Name (88-Level) Tests - Review
IF tests in the PROCEDURE DIVISION can reference condition-name (88-Level) variables - to test
for the existence of a value that equals the WORKING-STORAGE VALUE clause definition.
01 Transaction-Input-Rec.
05 Transaction-Type Pic X.
88 Valid-Transaction Value "A" "C" "D".
88 Add-Transaction Value "A".
88-Level Condition Names
88 Change-Transaction Value "C".
(Definition)
88 Delete-Transaction Value "D".
88 Invalid-Transaction Value "E" THRU "Z".
PROCEDURE DIVISION.
IF Valid-Transaction 88-Level Condition Names
If Add-Transaction (Referenced in IF Test)
Perform Add-Master-Record-Paragraph
Else IF Change-Transaction
Perform Update-Existing-Record-Paragraph
Else IF Delete-Transaction
Perform Delete-Master-Record-Paragraph
END-IF
END-IF. 209
Cracking the Code: Additional 88-Level Condition Name Options
• 88-Level variable definitions are sometimes called "Condition Names"
• They test T/F against a specific value, set or range of values in an elementary field of the DATA DIVISION
• In the PROCEDURE DIVISION you write statements that reference the 88-level variable names
• 88-Level Condition Names must:
• Be defined as a unique 88 level entry in the DATA DIVISION
• Refer to the elementary variable immediately preceding the 88-level
• Specify a VALUE clause - consistent with the PIC clause of the variable immediately preceding the 88-level
• NOT specify a PIC clause

• Elementary variables can have as many 88-Level Condition Names as necessary


• And the 88-level definition can contain multiple values:
05 COLOR-DEF PIC X(10).
88 VALID-COLOR VALUES ARE "ORANGE" "GREEN" "BLUE" "BROWN".
05 ITEM-SIZE-VALUE PIC 9(3).
88 VALID-ITEM-SIZE VALUES 12 THRU 30.
05 TRAN-DESCRIPTION PIC X(40).
88 INVALID-DESCRIPTION VALUE ALL SPACES.
05 TRAN-DESCRIPTION PIC X(8).
88 HIGH-RISK-INV VALUES ARE "JUNK" "GOLD" "MOODYSB" THRU "MOODYSF".
210
01 GROUP-FLD.
05 FLD1 PIC X(4).
Cracking the Code: COBOL "Sign" and "Class" Tests 05 FLD2 PIC X(6).
77 ELEM-FLD PIC X(8).
77 NUM-FIELD PIC S9(4).
• Class conditions - test whether a PIC X variable:
• IS NUMERIC MOVE '1234' TO FLD1, FLD2.

• IS ALPHABETIC Consider the above W-S Definition IF FLD1 IS NUMERIC???


IF FLD2 IS NOT NUMERIC???
Which path (true/false) will each of ➔
these IF statements take? MOVE 'ABCDEF' TO GROUP-FLD.
IF GROUP-FLD ALPHABETIC
MOVE '987654' TO FLD2, ELEM-FLD.
IF FLD2 IS NUMERIC???
IF ELEM-FLD IS NUMERIC???
• Sign conditions - test whether a (PIC 9) variable: IF ELEM-FLD IS ALPHABETIC???
• IS POSITIVE
• IS NEGATIVE Again consider the above W-S Definition. MOVE 0.0 TO NUM-FIELD
• IS ZERO SUBTRACT 1 FROM NUM-FIELD
Is NUM-FIELD positive, zero or negative
after each of the following statements ➔ ADD +1 TO NUM-FIELD
211 MOVE .1 TO NUM-FIELD
212

Cracking the Code: Nested IF Conditions


A nested IF is a statement in which an IF statement contains additional IF clauses on the True or False path
IF (AIRLINE1-FARE < AIRLINE2-FARE) THEN
IF (AIRLINE1-FARE < AIRLINE3-FARE) THEN
DISPLAY "AIRLINE1 " AIRLINE1-FARE " IS CHEAPEST"
ELSE
DISPLAY "AIRLINE2 " AIRLINE3-FARE " IS CHEAPEST"
END-IF
ELSE
IF (AIRLINE2-FARE < AIRLINE3-FARE) THEN
DISPLAY "AIRLINE2 " AIRLINE2-FARE "IS CHEAPEST"
ELSE
DISPLAY "AIRLINE3 " AIRLINE3-FARE " IS CHEAPEST"
END-IF
END-IF

Nested IFs can get obscenely complicated in production business applications.


You can utilize END-IF to make complex statements easier to read, easier to understand and easier to maintain.
Cracking the Code: Compound IF Conditions
A compound IF statement is two or more conditions connected by OR/AND/NOT
IF STATE = 'CA' OR 'WA' OR 'HI' OR 'OR' If two or more conditions in a compound conditional contain
the same operand, then the operand only needs to be coded
PERFORM WEST-COAST-SHIPPING-COSTS. in the first conditional

• A compound IF / OR will be true if any single condition tests true.


• Note that, as soon as a condition tests true the test stops and takes that path - i.e. code the most
likely condition first.

• A compound IF / AND will be true only when all of the conditions are true. The left➔right test stops
as soon as one of the conditions tests false
IF EMPLOYEE = 'FULL-TIME' AND JOB = 'MGR'
COMPUTE MONTHLY-BONUS = .4.
• Be careful about directly translating English language requirements into COBOL. Example (business
specification) - "Our discount customers live in NJ, NY and NC." What is wrong with the following:
IF BUYERS-STATE = 'NJ' AND 'NC' AND 'NY'
COMPUTE DISCOUNT-AMT = 100. 213
Cracking the Code: Compound IF - Evaluation precedence
The operational hierarchy rules for compound conditionals are as follows:
1. Conditions surrounding the word AND are evaluated first.
2. Conditions surrounding the word OR are evaluated last.

When there are several AND - OR connectors,


1. The AND conditions are evaluated first, as they appear in the statement, from left to right.
2. Then the OR conditions are evaluated, also from left
IF STATE-CD = 'NY' AND AGE > 65
to right.
OR STATE-CD = 'NJ' AND AGE > 64
OR AGE > 70
AND NOT SINGLE-PAYER-COVERAGE
THEN
MOVE 'Y' TO MEDICARE-ELIGIBLE-SW.
Parentheses override all other hierarchy rules: What is the order of evaluation?
• All conditions within parentheses are evaluated first.
• The evaluation starts with the inner parentheses first …
then continues outwards until the contents of all parentheses have been examined and acted upon
• Note that there must be a one-to-one correspondence between left and right parentheses,
with each left parenthesis to the left of its corresponding right parenthesis. 214
EVALUATE - COBOL's "CASE" Logic
The EVALUATE verb provides a shorthand notation for a series of nested IF
statements. There are several different options:
EVALUATE <variable> Format 1.
• EVALUATE (Examine) the contents of a variable
WHEN <literal/named-condition> statement(s) • WHEN <literal> <imperative statement>

END-EVALUATE.
Format 2.
EVALUATE TRUE • Evaluate TRUE/FALSE
• Note that 88-Level fields must use EVALUATE TRUE
WHEN <condition> statement • Execute the statement after the first WHEN condition that tests true
• WHEN OTHER = "If none of the above test true" -- note that all of
WHEN OTHER statement(s) the EVALUATE options support "OTHER"
END-EVALUATE.

Format 3.
EVALUATE <variable> ALSO <variable> • Inspect the contents of <variable1> & <variable2>
• If <literal-value> or if 88-level, AND <literal-value2>
WHEN <condition> ALSO <condition> statement(s) execute statement
END-EVALUATE. 215
EVALUATE can be easier to understand from examples
EVALUATE WS-EMPLOYEE-STATUS
WHEN "F" MOVE "FULL-TIME" TO EMP-TYPE-PR
EVALUATE RECORD-TYPE-VALUE
WHEN "U" PERFORM UPDATE-PARA WHEN "P" MOVE "PART-TIME" TO EMP-TYPE-PR
WHEN "D" PERFORM DELETE-PARA
WHEN "T" MOVE "TEMP" TO EMP-TYPE-PR
WHEN "I" PERFORM INSERT-PARA
WHEN OTHER PERFORM INVALID-VALUE WHEN OTHER MOVE "BAD STATES" TO WS-EMP-STAUS-OUT
END-EVALUATE.
END-EVALUATE.

EVALUATE CUSTOMER-TYPE ALSO SHIP-REQUEST


WHEN "PREMIER" ALSO "OVERNIGHT" PERFORM OVERNIGHT-PARA
WHEN "PREMIER" ALSO "SECOND-DAY" PERFORM EXPEDITED-PARA EVALUATE TRUE
WHEN "PREMIER" ALSO "THIRTY-DAY" PERFORM 30-DAY-PARA WHEN VALID-STOCK-SCAN
WHEN "GENERAL" ALSO "OVERNIGHT" PERFORM OVERNIGHT-PARA MOVE 0 TO LINE-ITM-COUNT
WHEN "GENERAL" ALSO "SECOND-DAY" PERFORM EXPEDITED-PARA PERFORM INVENTORY-SETUP-RTN
WHEN "GENERAL" ALSO "THIRTY-DAY" PERFORM 30-DAY-PARA WHEN STOCK-LOW
WHEN OTHER PERFORM BAD-SHIPPING-PARA PERFORM INVENTORY-LOW-RTN
END-EVALUATE. WHEN STOCK-ADEQUATE
PERFORM INVENTORY-OK-RTN
END-EVALUATE.
216
EVALUATE - And the IF statement equivalent
EVALUATE The Equivalent IF Statement;
EVALUATE menu-input IF (menu-input = "0") THEN
WHEN "0" PERFORM init-proc
ELSE
PERFORM init-proc IF (menu-input >= "1") AND (menu-input <= "9")
WHEN "1" THRU "9" THEN
PERFORM process-proc
PERFORM process-proc ELSE
WHEN "R" IF (menu-input = "R") THEN
PERFORM read-parms
PERFORM read-parms ELSE
WHEN "X" IF (menu-input = "X") THEN
PERFORM cleanup-proc
PERFORM cleanup-proc ELSE
WHEN OTHER PERFORM error-proc
END-IF;
PERFORM error-proc END-IF; Note that a semicolon is treated like a comma -
END-EVALUATE. END-IF; basically a non-operational word separator
217
END-IF;
COBOL Program Big Picture - Topics in this Module
Identification Name the executable Program-ID. PAYROL03.

SELECT <internal file name> ASSIGN TO JCL-DDNAME


Environment Statements that connect the program to
Indexed and Sequential data sets. FILE SECTION
FD
77 Standalone variable declaration
Variable declarations - Fields that 01 Data Hierarchy variable definition
05
contain values to be processed in the 10
Data program's PROCEDURE DIVISION 88 Named condition
Signed Numeric PIC
FILLER
VALUE
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point
BLANK WHEN ZERO

Procedure Executable statements that process the IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields
variable values in the DATA DIVISION Compound IF, Nested IF
EVALUATE
Signed Conditions, Class Conditions
MOVE
PIC X MOVE behavior
PIC 9 MOVE behavior
Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
DISPLAY
GOBACK
COBOL Code Paragraph
PERFORM Paragraph UNTIL <condition>
Divisions OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
INITIALIZE
Counters, Accumulators, Flags
Module 8 Review
• Complete the slide reviews/checkpoints in this Module - answer questions on the slides:
• Field Comparisons
• COBOL - Sign and Class tests
• Use TESTCOB as a sandbox-tool to validate your answers by copy/pasting in the DATA DIVISION and
PROCEDURE DIVISION statements, then doing a COBUCLD and following the Debugger
• What is the operational difference between PIC X and PIC comparisons?
• What are the benefits of consistently utilizing parentheses in complex IF statements?
• Under what circumstances would you utilize the EVALUATE statement
• Which of these relational operators is NOT a valid
comparison operator ➔ <>
<
!=
NOT=
=>
<<=
NOT <
NOT >=
219
 Nothing to hand in

Workshop 8.0 - Use TESTCOB to try out these Field Comparison Variations
MOVE 'ABC' TO FLD1, FLD2. 01 GROUP-FLD.
IF FLD1 < FLD2 ??? 05 FLD1 PIC X(4).
MOVE 'ABCDE' TO FLD1, FLD2. 05 FLD2 PIC X(6).
IF FLD1 = FLD2 ??? 77 ALPHA-FLD PIC X(8).
77 NUM-FLD1 PIC 9(4).
MOVE 'ABCDEF' TO GROUP-FLD, ALPHA-FLD.
77 NUM-FLD2 PIC S9(3)V99.
IF GROUP-FLD = ALPHA-FLD???
Copy the field definitions (above) and the
IF ALPHA-FLD = FLD2???
 procedural statements into TESTCOB.

MOVE ZEROES TO NUM-FLD1, NUM-FLD2


Complete the IF/Test with a valid DISPLAY
IF NUM-FLD1 = NUM-FLD2???
statement
MOVE 7.1 TO NUM-FLD1, NUM-FLD2
Try out as many of the statements as time
IF NUM-FLD1 = NUM-FLD2??? permits - to lock down your understanding
MOVE -6 TO NUM-FLD1, NUM-FLD2 of COBOL IF tests and
IF NUM-FLD1 = NUM-FLD2??? assignment/truncation idiosyncrasies. 220
 Nothing to hand in 01 GROUP-FLD2.
05 FLD3 PIC X(4).
Workshop 8.0 continued - Class and Sign conditions 05 FLD4 PIC X(6).
77 ELEM-FLD PIC X(8).
Class conditions - test whether a PIC X variable: 77 NUM-FIELD PIC S9(4).
• IS NUMERIC
Consider the above W-S Definition MOVE '1234' TO FLD3, FLD4.
• IS ALPHABETIC
IF FLD3 IS NUMERIC???
Which path (true/false) will each of ➔ IF FLD4 IS NOT NUMERIC???
these IF statements take?
MOVE 'ABCDEF' TO GROUP-FLD2.
Copy the field definitions and statements IF GROUP-FLD2 IS ALPHABETIC???
into TESTCOB MOVE '987654' TO FLD4, ELEM-FLD.

Try out as many of the statements as time IF FLD4 IS NUMERIC???

permits - to lock down your understanding IF ELEM-FLD IS NUMERIC???


of COBOL Class and Sign IF tests IF ELEM-FLD IS ALPHABETIC???

Sign conditions - test whether a PIC 9 variable: MOVE 0.0 TO NUM-FIELD


• IS POSITIVE
Again consider the above W-S Definition. SUBTRACT 1 FROM NUM-FIELD
• IS NEGATIVE
• IS ZERO Is NUM-FIELD positive, zero or negative ADD +1 TO NUM-FIELD
221 after each of the following statements ➔ MOVE .1 TO NUM-FIELD
ACME Corp.
Valued Customer Sign-on:
Optional Workshop - Conditional Login Pattern
You've been asked to re-write the logic for the IMS TM Enter User ID: ________
(online) applications sign-on screen.
Enter Password: _____
Create record layouts that will display these lines xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Create procedural logic as follows:
• If the User ID is wrong send back the message: "Wrong ID".
• If the User ID is right and the Password is wrong, the message is "Bad Password"
• If both are right, message = "Welcome to COBOL"

When your logic works, add one more test - that allows users only three chances to enter
the correct ID/PWD combination

Because we do not have online screen functionality to "converse" with users and store
values temporarily as part of the send/receive conversation, simply utilize MOVE statements
and PERFORMED paragraphs to simulate the send/receive functionality

222
Workshop 8.1a - New COBOL Development
You own a musical instrument shop which sells rock
band gear. You've been asked to respond to an RFP
(request for proposal) to outfit all the musicians in your
favorite rock band with instruments, amps, mics…"gear"
The costs for the various instruments are categorized by
instrument type and within type, instrument quality
Here is a record-layout you can use for RFP input file ➔

Create a report program (FAVRFP) - that responds to the RFP input.


The report should consist of one detailed-line per valid input record:
• One/per RFP/Musician - showing the calculated costs with all commercial factors applied
(Instrument base-price, New/Used, Tax, Shipping, etc.).
• You can layout the output (report detailed-lines) as you see fit.
On the next slide are additional programming specifications, as well as a sample output record.
223
Workshop 8.1b - New COBOL Development
1. The output report should use Numeric Edited fields

Output File Record Layout


2. TAX is a flat 8% on the COST-PER-INSTRUMENT
3. Shipping cost is as follows:
1. IN-COUNTRY: 10% of the calculated Cost-per-Instrument (see below)
2. OUT-OF-COUNTRY: 20% of the Cost-per-Instrument

4. Prices - per instrument:


1. Keyboards: $3,017.89
2. Vocals (mics, auto-tuner, etc.): $599.05 PIC X(01).
3. Guitar Rig (guitar + amp): $2,648.99
4. Bass Rig (bass + amp): $1,876.10
5. Drum Kit: 3,087,22
6. Percussion: $799.99

5. Prices - Instrument-Quality Adjustment:


1. Used - 20% off the standard price
2. New - standard price
3. Premium - 20% more than the standard price

Calculated COST-PER-INSTRUMENT = Price + Instrument-Quality Uplift + Tax + Shipping Cost 224


225

Workshop 8.1c - Create the Test Data Input File

Input Data File


Input File <TSOID>.LEARN.FAVRFP
 Record Layout

1. Make a copy of <TSOID>.LEARN.FAVIN - name it <TSOID>.LEARN.FAVRFP


2. Split screen - and edit the program - and the Data file - so that you can line up the fields with the data; byte for byte
3. It might help you to see the byte positions in the file (|||||||||1|||||||||2|||||||||3…) - Remove the line before testing

Edit your Testing JCL. Add the following DD cards at the end of the file……………………………
The DDNames must be the same as your SELECT/ASSIGN clause in the program
Optional Workshop 8.1d - Enhancements to FAVRFP - Tighter Edit Checks
The Testing Team has decided that the one or two error-checks done by FAVRFP are not nearly enough.
So you are to modify the program logic as follows:
• Artist-Account-Number ➔ All numerics
• Artist-Musical-Genre - Must be: ROCK, JAZZ, FUSION, FOLK, CLASSICAL, COUNTRY
• Artist Musician last and first names ➔ Must not be blank
• Musician-Instrument-Type ➔ Must be DRUMS, GUITAR, BASS, VOCALS, KEYBOARD, PERCUSSION
• Musician-Instrument-Type ➔ Must be USED, NEW, or PREMIUM
• Max-Musician-Budget ➔ Must be between $1,000 and $9,999.99
• Ship-To ➔ Must be: IN or OUT
Speaking of Shipping-Cost, someone complained about our calculation for shipping cost - stating that
shipping cost should be based on the instrument cost - only. Please fix that calculation.
Note that you will need specific test data records, in order to verify your results. You will also need a way
to associate each record with the type of error caught.

 Optional values to start you off


226
Optional Workshop 8.1e - Enhancements to FAVRFP - Management Quality Reports
Beside the above, add a couple of new output record types, to capture:
• A header record - A simple report title (Left-Justified)
• Break out the detail line into Labelled Fields:
• Add the necessary FILLER to space out the report fields neatly
• Add a grand total line for the entire program:
• Number of input records total
• Number of good input records
• Number of bad input records
• Grand total of calculated instruments costs

Finally add a new output file to be populated by all bad (invalid) records. You will need new:
• FILE/CONTROL → SELECT/ASSIGN
• JCL DDName for the bad output record Data Set tied to the new SELECT/ASSIGN
• FD in the Data Division
• OPEN and CLOSE file names
• WRITE file paragraph
• PERFORM (s) of the Write File paragraph:
• Note: No need to format the bad/records being written out. 227
Just move the record. At the 01-level
 Nothing to hand in

Workshop 8.2 - Production Support


You've been asked to take over the work on PAYROL03 which is
currently being tested. Unfortunately, the test team has identified
more than a few logic bugs:
• Truncation
• Field transposition
• Missing fields

1. Study the code, in split-screen, juxtaposing the DATA


DIVISION variables with the PROCEDURE DIVISION
business logic
2. Fix the problems, then Compile/Link/Run PAYROL03
3. From the Job SYSOUT - verify your expectations
4. If you're not satisfied with the output alignment and quality
of your report, repeat steps 1 ➔ 4
5. Add a record-counter to WORKING-STORAGE. Count the
number of records both read & written
6. Implement a Payroll-Total - by defining a WORKING-
STORAGE field, accumulating each of the Paycheck
amounts into the field, and printing Numeric Edited output. 228
Optional Topic: IF statements and the importance of indentation
IF (PHARMACY-COST IN INPATIENT-TREATMENT-REC > 990)
IF (MEDICATION-COST > 9900.0
OR MEDICATION-COST < 1.01)
MOVE "*** INVALID MEDICATION COST" TO
ERR-MSG IN INPATIENT-TREATMENT-REC-ERR.
MOVE "Y" TO ERROR-FOUND-SW
PERFORM 710-WRITE-TRMTERR THRU 710-EXIT
GO TO 400-EXIT
IF (PHARMACY-COST IN INPATIENT-TREATMENT-REC > 880)
IF (ANCILLARY-CHARGE > 900 AND ERROR-FOUND-SW = 'N')
IF LAB-TEST-ID(ROW-SUB) AND NOT VALID-CATEGORY(ROW-SUB)
OR PHARMACY-COST IN INPATIENT-TREATMENT-REC < .88
MOVE "*** INVALID PHARMACY COSTS" TO
ERR-MSG IN INPATIENT-TREATMENT-REC-ERR.
IF (ANCILLARY-CHARGE > 100)
NEXT SENTENCE ELSE
IF (ANCILLARY-CHARGE > 1000
OR ANCILLARY-CHARGE < 1.01)
MOVE "Y" TO ERROR-FOUND-SW
GO TO 400-EXIT.
IF VALID-RECORD
PERFORM 450-CROSS-FIELD-EDITS THRU 450-EXIT. 229
Optional Topic: Procedural Patterns for Conditional Code
In the context of large programming work - IF statements allow you to:
• Edit Data
• Make a procedural decision -- perform this vs that procedure

• Your options to design/code a solution include all six conditional expressions


• And your process needs to factor in:
• Correct-ness
• Test-ability
• Maintain-ability

For a series of IF / OR tests you have the following three options:


1. Nested IF
2. CASE (evaluate a series of OR conditions)
3. IF (simple test) … GO TO EXIT
• Something you will doubtless run into at some point in your career
• See next slide

230
Optional Topic: Multiple IF <condition> Tests -
COBOL Programming Pattern
• As a data centric programming language - you
will find that many of the logic requirements you
code to will involve testing for valid values -
dozens and dozens of data edits.

• PERFORM EDIT-PARA THRU EDIT-PARA-EXIT


- and in the EDIT-PARA … for each invalid
condition found, you would:
• Take programmatic action:
• Set a "flag"
• Document the error condition
• GO TO the PARA-EXIT ➔
Wil the 80's ever die?
231
UNIT COBOL for z/OS - Module 9
COBOL Internal Data Types and Corporate
Business Data
• EBCDIC Hexadecimal Data Representation
• COBOL Internal Data Types and binary fields
• COMP
• COMP-3

Note that the material on Hex data representation, COMP and COMP-3
data storage requires an understanding of Base 2 and Base 16
232
COBOL Program Big Picture - Topics in Module 9
Identification Name the executable Program-ID. PAYROL03.

SELECT <internal file name> ASSIGN TO JCL-DDNAME


Statements that connect the
Environment program to Indexed and
FILE SECTION
FD
Sequential data sets. 77 Standalone variable declaration
01 Data Hierarchy variable definition
05
Variable declarations - Fields 10
that contain values to be Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
Data processed in the program's REDEFINES
88 Named condition
PROCEDURE DIVISION
Signed Numeric PIC
FILLER
VALUE
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

Executable statements that IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields
Procedure process the variable values in
Compound IF, Nested IF
EVALUATE
the DATA DIVISION Signed Conditions, Class Conditions
MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
DISPLAY
GOBACK
Code Paragraph
COBOL PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
Divisions INITIALIZE
Counters, Accumulators, Flags

233
What's Really Happening - 1 of 3
When you execute COBUCLD/COBUCLG -
and if there are no syntax errors - your z/OS
program in Load Module format is copied
from your USERID.LOAD library into a z/OS
Address Space.

An Address Space provides 16 Exabytes of


z/OS z/OS z/OS z/OS
storage for your program. In this COBOL Address Address Address Address

class you will use a lot less., Space Space Space Space

Net: Your program/Load Module is loaded


into an z/OS Address Space and assigned
memory locations that your code and data Seriously… "Exabytes"?
has available for use.
234
What's Really Happening - 2 of 3
Here your program has started to execute under Debug
You've "monitored" ACCT-FIELDS. The Memory View CBL0001
shows the Hex values and storage addresses Load
Module
Debug
Before the READ operation

At the beginning of the PROCEDURE DIVISION variables declared without a VALUE clause
pick up whatever values remain in the Address Space from the previous program 235
3 of 3
The READ
operation
completes, and READ operation complete
an ACCT.DATA
record is read
into your
program's buffer

The FD in the Note that the Memory view is like an


File Section. MRI of your code

Hexadecimal values and their


addresses in your Load Module 236
237

Corporate Business Data


• Mainframe data files - the data used to transact business - are:
• Huge: Gigabyte sized files are common…Terabyte-sized files are not uncommon
• Varied: Fixed Records, Variable-length Records, Indexed Files, Databases, etc.
• Full of "binary data fields" - data that can not be read with text editors
• We will need to understand more about the COBOL variable "USAGE IS" clause to
work with Business Data files. And we'll need to understand the EBCDIC Code Page

• A data file with two COMP-3


(packed decimal) fields
• Note the "special characters"
that appear when viewing
binary data using text editors
• You will learn to use special
data file editing tools such as
IBM's File Manager to view
and edit binary data files
Binary Data - EBCDIC Mainframe Values (Base 16)
First Digit
Capital Letters:
• C1 ➔ C9
• D1 ➔ D9
• E2 ➔ E9

Second Digit
Numbers:
• F0 ➔ F9

Special Values:
• Low-Values: '00'
• High-values: 'FF'
Display values ➔
• Spaces: '40'
DBCS values ➔
ASCII (UTF8) values ➔
EBCDIC (CP037)values ➔ 238
Understanding Hex Data
• To understand the binary or Hex data
you need:
• An understanding of the previous slides
• The data
• The record layout for the file/PIC clauses
The red vertical lines
represent individual
fields in the record layout

239
How to view and edit "binary" data - ISPF "Hex On"
There are three options for browsing & editing files that contain binary data
- depending on which client software you are using:
• ISPF ➔ HEX ON The Record Layout - including COMP & COMP-3 Fields
• Edit file directly in HEX

• IDz ➔ z Systems Data Editor


• Also edit file directly in HEX

• ZOD ➔ Debugger
• ZOD does not come with a binary data file editor
• So you will Compile/Link-Edit and Debug
• During Debug - you can:

Binary Data
• Change variable representations (to HEX)
• Modify values
• Write records
• End the program when you're ready
Most shops have one ore more tools that
map record layouts directly on to files 240
ISPF "Hex On" Binary Data
From =1 (Browse) type the name of
the file: LEARN.PAYCHECK.DATA

When the file opens, you will have to


type RES (reset) on the command
line

Type HEX ON BROWSE

Press <Enter>

Note that the WRITEFLE


record layout for
PAYROLL-WS on the
previous slide defines the
data values 241
IDz - z Systems Data Editor - Binary Data
For IDz:
• Right-click on <USERID>.LEARN.PAYCHECK.DATA and open the file with
the z Systems Data Editor
• Click the Hex button - to go into Hex Mode. View/Edit the values in Hex

Use the WRITEFLE record layout for PAYROLL-WS on


the previous slide to visualize the data value fields 242
ZOD Binary Data Editing
Using the COBOL Editor - 1 of 2

For ZOD users:


1. Right-click on the Data Set you want to edit
• Follow these instructions ➔

2. Then follow these instructions…


ZOD Binary Data Editing
1. Right-click on the file and select Properties
2. From Properties > Mapping make the Extension: cbl

3. Open the file and click the Toggle Hex Editing icon on the
toolbar

Note that - to turn Hex Editing off click the Icon on the toolbar (again)

And we see the Hex characters


 for the 'current line'
Using the ZOD Debugger to Access/Display Binary Data - 1 of 2
Another option for ZOD users is to
Compile/Link-Edit/Debug a program that
accesses the file and Monitor binary field
values in Hex - allowing you to see and change
Hex values

• COBUCLD WRITEFLE
• Step 12 ➔ 13 times
• Monitor Expression: PAYROLL-WS
• Right-click and Show Type Names
• Change and view few variables'
representations (to Hex) - specifically
numeric fields that are:
• COMP, CMP3, DISP
• Change the numeric field
representations back to Decimal
• Modify some values - then switch to
Hex and see the values in EBCDIC
• Write records
• End the debug session when you're
ready by changing the value of
PAYROLL-EOF to "Y" 245
Using the ZOD Debugger to Access/Display Binary Data - 2 of 2
• Monitoring and changing field
values in Text/Decimal
• Notes:
• Show Type Names - toggles the USAGE
on off for all fields
• Change representation - presents the
value of an individual field in Hex … or
Display

• It will be easier for you to modify test


data in Display USAGE - but to fully-
understand Binary Data use Change
representation

246
Data Storage and Numeric Values – DISPLAY, COMP and COMP-3 Variables
The Data Division numeric variables we've declared so far have used PIC 9 and PIC S9 to
declarations. They've also used the default COBOL internal numeric data USAGE: DISPLAY - also
referred to as "External Decimal" or "Zoned Decimal"
• In USAGE DISPLAY fields, the System z stores each digit as a single byte (8 bits) of hex data;
i.e. The number 5 is stored as: 1111 0101
Bits: 1234 5678 Most often you'll see Base 16 instead of Base 2 values:
Base 16: F 5 This is also called: Hex or Hexadecimal
"F" is the Zone

• There are other internal common numeric data "USAGE" types - including:
• COMP-3 ➔ "packed" or "packed-decimal"
COMP-3 fields pack multiple digits into 1 byte of storage by replacing the “Zone” with a value
The rightmost byte contains only one digit and the sign. COMP-3 fields
• Save space on disk storage
• Significantly speed the: Disk ➔ Program ➔ Disk I/O operations
• COMP ➔ "binary"
Binary field values are stored as pure Hex (Base 16) values:
247
• Decimal value: 111 ➔ Hex value: 6F
248

Defining COMP and COMP-3 Fields


• USAGE DISPLAY:
• Is the default COBOL definition for a PIC 9 field
• The phrase: USAGE IS is optional
• Internal (Hex) storage of numeric values:
MOVE 1234.56 TO DISPLAY-VAR
The internal storage is: F1F2F3F4F5F6

• COMP-3 fields are defined as COMP-3 …or… • COMP fields are defined as COMP …or…
PACKED-DECIMAL: BINARY:
• They consume almost half of the space needed to store
DISPLAY variables • They are defined as follows:
• The ending 4 bits are reserved for a sign: COMP PIC 9(1) ➔ PIC 9(4) … Two bytes of storage
• C or F (positive value) COMP PIC 9(5) ➔ PIC 9(8) … Four bytes of storage
• D (negative value) COMP PIC 9(9) ➔ PIC 9(18) …Eight bytes of storage
• Internal (Hex) storage of numeric values: • Internal (Hex) storage of numeric values:
• MOVE 1234.56 TO COMP-3-VAR • MOVE 1234.56 TO COMP-VAR-HALF-WORD
• The internal storage is: 01 23 4.5 6F • The internal storage is: 04D2
• MOVE -1234.56 TO COMP-3-VAR-SIGNED • MOVE 1234.56 TO COMP-VAR-WORD
• The internal storage is: 01 23 45 6D • The internal storage is: 0001E240
COBOL Internal Data Representation of Numeric Values - Summary
Internal There are additional PIC
Numeric type Variable PIC, USAGE and SIGN clause Value representation Clauses and Usages
you may bump into;
External Decimal PIC S9999 DISPLAY + 1234 F1 F2 F3 C4 • Floating Point:
…aka… - 1234 F1 F2 F3 D4 • COMP-1,
1234 F1 F2 F3 C4 • COMP-2,
Zoned Decimal • National Data - for
PIC 9999 DISPLAY 1234 F1 F2 F3 F4 preparing output to go
+ 1234 C1 F2 F3 F4 to countries with
PIC S9999 DISPLAY DBCS code pages
SIGN LEADING - 1234 D1 F2 F3 F4
PIC S9999 SIGN LEADING SEPARATE + 1234 4E F1 F2 F3 F4  Note: 5 Bytes total

PIC S9999 SIGN TRAILING SEPARATE 1234- F1 F2 F3 F4 60


Binary PIC S9999 BINARY or PIC S9999 + 1234 04 D2
…aka… COMP The hyperlink on the
Comp PIC 9999 BINARY or PIC 9999 COMP 1234 04 D2 Slide Header launches a
page which describes all
Internal Decimal PIC S9999 PACKED-DECIMAL or + 1234 01 23 4C Enterprise COBOL types
…aka… PIC S9999 COMP-3 - 1234 01 23 4D
Packed Decimal PIC 9999 PACKED-DECIMAL COMP-3 1234 01 23 4F 249
COMP (Binary) Numeric Field Definition - Deeper Dive
There are three different PIC clause size variations for COMP fields

1.
2.
3.
1.
2.
3.

• The amount of storage - and the max numeric value - occupied by a comp
field depends on the number of digits defined in its PICTURE clause.

BINARY, COMPUTATIONAL, and COMPUTATIONAL-4 data items can be affected by the TRUNC compiler option.
For information about the effect of this compiler option, see TRUNC in the Enterprise COBOL Programming Guide. 25
COBOL Program Big Picture - Topics in Module 9
Identification Name the executable Program-ID. PAYROL03.

SELECT <internal file name> ASSIGN TO JCL-DDNAME


Statements that connect the
Environment program to Indexed and
FILE SECTION
FD
Sequential data sets. 77 Standalone variable declaration
01 Data Hierarchy variable definition
05
Variable declarations - Fields 10
that contain values to be Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
Data processed in the program's REDEFINES
88 Named condition
PROCEDURE DIVISION
Signed Numeric PIC
FILLER
VALUE
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

Executable statements that IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields
Procedure process the variable values in
Compound IF, Nested IF
EVALUATE
the DATA DIVISION Signed Conditions, Class Conditions
MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
DISPLAY
GOBACK
Code Paragraph
COBOL PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
Divisions INITIALIZE
Counters, Accumulators, Flags
Reference Modification
Figurative Constants
 Nothing to hand in

Review Questions - What will happen if I click "Step Into(F5)" ???

1. If you're not sure what


will happen:
• COBUCLD the program: S0C7
• Monitor: S0C7-TEST-VARIABLES
• From the Variables view, Right-Click
on SUB and change its
Representation to Hexadecimal

2. Why did this happen?

3. Change SUB from


COMP-3 to COMP. Again,
COBUCLD What happened
this time and why?
252
 Nothing to hand in

Optional Workshop 9.0


1. Translate your name into EBCDIC
Hex values
*** Use your development IDE to check your work

2. Translate the following into English

3. Based on the record layout in CUST-REC (previous slide), what are the values of the following
variables:
• CUST-ACCOUNT-BALANCE
• CUST-ORDERS-YTD Think of this like "Where's Waldo" for Hex data

3. Hint - have a look at: http://www.longpelaexpertise.com/toolsCode.php While this site will not help with numeric COMP-3 and
COMP data, it may expedite EBCDIC translation, including finishing the above workshops.

4. Whatever you don't finish during class can be done as homework for this chapter. 253
 Nothing to hand in

Workshop 9.1 - Use the Debugger to Display & Manipulate Binary Data
Compile/Link-Edit/Debug: WRITEFIL
During your Debug session:
• Monitor PAYROLL-WS
• Select PAYROLL-WS
• Right-click and select: Monitor Expression

• Show Type Names


• Change a few variables' representations
(to HEX)
• View some field values in HEX -
• COMP
• COMP-3
• DISPLAY

• Change the numeric field representations


back to Decimal
• Modify some values - and view the results:
• In HEX - and In DISPLAY

• Write a few records and end the debug


session when you're ready, by changing
254
the value of PAYROLL-EOF to "Y"
 Nothing to hand in

Optional Workshop 9.2 - COMP and COMP-3 Fields "Under the Microscope"
1. Use TESTCOB
- or create
another program
that acts as a
Sandbox/COBOL
language tester.
Create this
collection of
variable/ type
definitions ➔

Use Copy/Paste
to speed up your
development
cycles. 2. COBUCLD (Compile/Link/Debug) the program
• After you • During Debug:
define the • Monitor VARIABLES-WS
variables copy
the variable
• Expand the 01 to reveal all of the elementary fields
names into the • Show Type Names
PROCEDURE • For selected fields, Change the representation to
DIVISION ➔ Hexadecimal
• Check out the positive and negative values
255
COBOL Internal Data Representation - Additional Links to Augment Your Learning

• https://www.ibm.com/support/knowledgecenter/SSEPEK_12.0.0/intro/src/tpc/db2z_charsets
andcodepages.html - EBCDIC Code Pages
• https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/con
cepts/cpari20e.htm - COBOL Numeric Data and Internal Representation
• http://www.3480-3590-data-conversion.com/article-packed-fields.html -- Treatise on COMP-3
• http://www.3480-3590-data-conversion.com/article-reading-cobol-layouts-3.html - Redefined Fields
• http://www.3480-3590-data-conversion.com/article-reading-cobol-layouts-4.html - Internal Numeric Data

Note that these site links are not


IBM endorsements - they are
simply lists of internet resources 256
UNIT COBOL for z/OS - Module 10

"It's almost a given and an unavoidable fact of


ABEND Resolution
life that there is some amount of invalid data
floating around in production files and data
• Terms and Concepts
bases." z/OS Architect, 2020 • Types of ABENDs
• Defensive Programming
• Specific ABENDs
• ABEND on purpose

Sources for MVS Completion Codes (related to ABENDs) that you can find on the web:
http://www.jaymoseley.com/hercules/sabends.htm
http://ibmmainframes.com/references/a29.html
http://ibmmainframes.com/topic-42-0-250.html 257
COBOL Program Big Picture - Topics in Module 10
Identification Name the executable Program-ID. PAYROL03.

SELECT <internal file name> ASSIGN TO JCL-DDNAME


Statements that connect the
Environment program to Indexed and
FILE SECTION
FD
Sequential data sets. 77 Standalone variable declaration
01 Data Hierarchy variable definition
05
Variable declarations - Fields 10
that contain values to be Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
Data processed in the program's REDEFINES
88 Named condition
PROCEDURE DIVISION
Signed Numeric PIC
FILLER
VALUE
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

Executable statements that IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields
Procedure process the variable values in
Compound IF, Nested IF
EVALUATE
the DATA DIVISION Signed Conditions, Class Conditions
MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
DISPLAY
z/OS ABENDS GOBACK

• Understanding
Code Paragraph
PERFORM Paragraph UNTIL <condition>

• Safeguarding
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>

COBOL
INITIALIZE

• Resolving
Counters, Accumulators, Flags

Divisions
Reference Modification
Figurative Constants
z/OS ABEND (ABnormal END of Task)
• Production business application software errors are costly:
• While they are nowhere near as expensive as mistakes on an operating table
• They’re more expensive than mixing up the 1% vs. 2% milk in the dairy
aisle…or hitting Reply All when you actually meant to hit Reply

• There are ~dozen categories of common COBOL errors which produce ABENDS.
These include but are not limited to:
• Incorrect data typing of field definitions
An ABEND is a mainframe
• Incorrect subprogram parameter passing order business application
• Invalid data within files "Blue Screen"
• Values out of range
• Specific bad values … missing values
• Incorrect record-layout offset definitions
• Programmer/Analyst/Developer errors
• Misunderstanding of the specs – Typically the biggest & most expensive single issue
• Incomplete testing – Second biggest issue
• Misunderstanding of the COBOL language - Third biggest issue 259
Why ABENDs - Deeper Dive
System z architecture is built on an "instruction set" known as the Principles of Operation (POP)
• The POP describes every legitimate instruction that your program can execute - at the
machine-code level (what on earth does that mean?)
Process Produces Stored in
1.Code COBOL program - using your IDE (dev product) COBOL Source File Source Library (PDS) or SCM
you produce COBOL statements to solve business product
application requirements
2.Compile COBOL program - from COBOL ➔ machine Object/Machine code with calls (links) to Compiled Object Library
code unresolved executables (other programs) (PDS) - or simply deleted
written by you, your company or IBM
3.Link-Edit Object Code; Validate all calls to external Load Module - Machine code version of your Load Library (PDS) or SCM
executables program, with all external calls resolved product

4. GO/EXEC PGM= Business Application processing and outputs: Runs in an Address Space on
Copies your Load Module to an Address Space on • Files System z
System z and attempts to run instructions in your Load • Database updates
Module. • Reports
• Edited data
If System z encounters an instruction that is not
allowable as per the POP? ABEND 260
How do ABENDs occur?
Typical COBOL ABEND causes for sequential batch applications:
• Alphanumeric Data: • Programmatic "fall-thru"
• Truncation • COBOL statements execute downwards
• Incorrect PIC clause alignment in the record layout sequentially - irrespective of paragraph boundaries

• Numeric data: • Unchecked PERFORM UNTIL (Iteration):


• Reference to numeric field that contains non-numeric data • Infinite Loops
• Decimal place precision and rounding - esp. with internal
variables • Index issues:
• Typically "index out of range" - attempt to access a
• File Problems: table row with an invalid subscript: STATE-TBL(0)
• Read past end of file • File Handling:
• Reference to file before OPEN or after CLOSE • Invalid ASSIGN clause
• Write loop fills up an output file
• JCL:
• IF Conditions • Incorrect module name
• Incorrect specification of True/False logic • Invalid DD Name
• References to numeric fields that contain non-numeric data • Invalid DSN

• Invalid CALL • DISP = not correct with READ/WRITE

• Attempt to execute code in a different Address Space - or • Application Version Control Issues
reference to invalid
261
Frequent COBOL Business Application ABEND Types
There are more ABEND types and situations that you'll see as a COBOL coder. But understanding
the nine common ABENDS in this list will get you started
Also - sometimes z/OS will mask or return different system ABEND codes than those listed below
depending on whether the ABENDS occur in a layer of System Software

• S001 - Record Length/Block Size Discrepancy


• S013 - Empty File/Record Length/Block Size Discrepancy
• S0C1 - Invalid Instruction
• S0C4 - Storage Protection Exception
• S0C7 - Data Exception
• S0CB - Divide by Zero
• S222/S322 - Time out/Job Cancelled - Infinite Loop
• S806 - Module Not Found
• B37/E37 - Out of space (output file)
262
S001: Record Length/Block Size - Discrepancy
Reason(s)

S001-0: Conflict between record length specifications (program vs. JCL vs. dataset label)

S001-2: Damaged storage media or hardware error

S001-3: Fatal QSAM error

S001-4: Conflict between Block specifications (program vs. JCL)

S001-5: Attempt to read past end-of-file

Instructions: OPEN, CLOSE, READ, WRITE

Frequent Coding Causes:

S001-0: Typos in FD or JCL

S001-2: Corrupt disk or tape dataset

S001-3: Internal z/OS problem

S001-4: Forgot to code BLOCK CONTAINS 0 RECORDS in FD (default Block is 1)

S001-5: Logic error (either forgot to close file, or end-of-file-switch not set, overwritten or ignored)

Defensive Programming:

1. Split-Screen COBOL ➔ JCL

2. From JCL: Right-Click on DSN … Open Declaration

3. Select File and verify LRECL from the Properties View 263
S001: Record Length/Block Size - Discrepancy
Defensive Programming:

1. Split-Screen COBOL ➔ JCL ➔ File Properties

2. From JCL: Right-Click on DSN … Open Declaration

3. Select File and verify LRECL from the Properties View

2.

5.
4. 1.
3.

264
S013: Conflicting DCB Parameters

Reason(s) Instructions: OPEN, CLOSE, READ, WRITE


S013-10: Dummy data set needs buffer space; specify BLKSIZE in JCL

S013-14: DD statement must specify a PDS Frequent Coding Causes:


S013-18: PDS member not found Most of these ABENDs occur running under z/OS (some may not
even occur under z/OS, although older modules running on older
S013-1C: I/O error search PDS directory operating systems (OSVS or VS COBOL II code) that have not been
recompiled can produce them). And most are due JCL/COBOL➔
S013-20: Block size is not a multiple of the LRECL
FD inconsistencies.
S013-34: LRECL is incorrect

S013-50: Tried to open a printer for Input of I/O


Tools to debug – Static Analysis: S013-18: Same
technique as S001
S013-60: Block size not equal to LRECL for unblocked file

S013-64: Attempted to Dummy out indexed or relative file

S013-68: Block size > 32K

S013-A4: SYSIN or SYSOUT not QSAM file Workshop:


S013-A8: Invalid RECFM for SYSIN/SYSOUT • COBUCLG: S013
S013-D0: Attempted to define PDS with RECFM FBS or FS
• COBUCLG: S0001
S013-E4: Attempted to concatenate > 16 PDSs

265
S013: Block Size - Discrepancy
Defensive Programming:

1. Delete the BLOCK CONTAINS 0 RECORDS line as shown below

2. Save and COBUCLG

3. Open the IDIREPORT

266
SOC1: Invalid Instruction
Reason(s)
Frequent Coding Causes:
- SYSOUT DD statement missing
- Incorrect logic in setting AFTER ADVANCING variable (or failure
- The value in an AFTER ADVANCING clause is < 0 or > 99 to understand 0-99 limits)
- And Index or Subscript is out of range - Incorrect logic in table handling code, or number of table entries
has overflowed the PIC of variable e.g. PIC 99 (two digits, max) -
- An I/O verb was issued against an unopened dataset but there are 100 entries in the table
- Can also happen of CALL/ENTRY subroutine LINKAGE
does not match the calling programs record definition
Tools to debug:
Instructions: Static

OPEN, CLOSE, READ, WRITE, Table handling routines SYSOUT problem: Open multiple windows on AD Batch Job
• Note also that during Debug SYSOUT-DISPLAYs Diagram and program Environment Division - SELECT
are written to the "console" ASSIGN.
Logic problem: Select File. Use Occurrences in Compilation
to isolate statements
Dynamic:

Set Watch Breakpoint and Monitor on table index or AFTER


ADVANCING variable.

Set conditional advanced break point on subscript (i.e. SUB<100). 267


S0C4: Protection Exception

Reason(s): Tools to debug:


The program is attempting to access a Static
memory address that is not within the - DD statement problem: Open multiple windows on AD Batch Job Diagram
applications z/OS "Address Space" and program Environment Division - SELECT ASSIGN

- Incorrect linkage problem:

Frequent Coding Causes: - Open multiple windows on CALLing and CALLed programs - verify linkage
declarations.
- JCL DD statement is missing or incorrectly coded:
File Status: 47 upon READ Instruction Dynamic

- Incorrect logic in table handling code (referencing a The problem with S0C4 ABENDS, is that once they happen - there's nothing
table subscript < 1 or > max-table-size) left to capture and assist with Debugging.

- INITIALIZE used against a Buffer (file FD) that hasn't An "Address Space" is a block of virtual memory your Load Module is
been opened. assigned and runs in, when executing on z/OS. If your program attempts to
reference memory beyond the Address Space assigned, z/OS ABENDS
- Number of table entries has outgrown PIC of variable your program with an S0C4
(i.e. PIC 99, but 100 entries).

Important Note: Compile parameters influence what statements will and won't S0C4 268
S0C7: Data Exception
Reason:
Tools to debug:
Machine instruction expecting numeric data Static
found invalid data
Occurrences in Compilation Unit on numeric fields
Instructions:
Isolate all PIC 9 Fields
Arithmetic, IF MOVE (if receiving field is numeric) and PERFORM
VARYING statements Dynamic
Your application can S0C7 if the sending field is numeric and Set Watch points and Monitor on field.
contains non-numeric data (MOVE pic9field TO picXfield).
Record the Debug session - Run through to S0C7 and Playback
Frequent Coding Causes: from the ABEND
- Incorrectly initialized, or uninitialized variable Locate the field definition - and use client data analysis tools
- Missing or incorrect data edit
Solutions:
- 01 to 01 level MOVE if sending field is shorter than receiving field
Add edit checks for valid data in all numeric fields
- Move of Zeros to Group-level numeric fields
Define all numeric data that does do participate in arithmetic
- MOVE CORRESPONDING incorrect as PIC X
- MOVE field1 to field2 incorrect assignment statements.

Important Note: Compile parameters influence what statements will and won't S0C7 269
S0CB: Divide by Zero

Reason: Tools to debug:


Static
CPU attempted to divide a number by 0. Search for all DIVIDE and COMPUTE instructions – or
using IDz double-click on these verbs and select Filter
from the Context Menu
Instructions: Dynamic
Run through to the S0CB
DIVIDE, COMPUTE with / operation Locate to field definitions of the offending fields
Solution:
Add edit to check for zero divide:
Frequent Coding Causes:
IF divisor > ZERO
- Incorrectly initialized, or un-initialized variable THEN
COMPUTE ...
- Missing or incorrect data edits (i.e. failed to check ELSE
divisor for zero value) PERFORM error-processing routine

Add ON SIZE ERROR to all arithmetic verbs.

270
S222/S322: Timeout … Endless Loop
Reason: Dynamic tools.
Debug to Loop
Timeout due to program logic caught in "loop" Query and Monitor on subscript
through instruction set with no exit. Set an Advanced Break Point - Conditional on count
• S322 = Timeout
• S222 = Job Cancelled Solution:
For S322 - you may need to increase the TIME=(,n) value in
Frequent Coding Causes: the JCL Job Card
For S222 - you will need to read the code carefully to find one
- Invalid logic or fall-through logic
of the Frequent Coding Causes
- Invalid end-of-file logic

- End-of-file switch overlaid

- Subscript not large enough

- Perform Thru wrong Exit

- PERFORM UNTIL "End-Of-File", but not performing


"READ" routine to reach EOF condition

Tools to debug:

Static
Note: You will need to
Perform Hierarchy/Program Control Flow on logic in
Cancel the job to stop
PERFORM chain the Endless Loop ➔
271
Desk-Checking for other loop possibilities
S806: Module Not Found
Reason: Tools to debug:
CALL made to program which could not be located Static
along normal search path - which is: Build (Link) Map
Do Remote Systems search on module name –
//STEPLIB in the Load Libraries
//JOBLIB Dynamic
Set Program Advanced Break Point (Entry) to set program break
LINKPACK before entry to system.

Solution:
Instructions: Spell name correctly
Check for 4 or 8 return code from Link Edit (Build step)
Fix the program CALL keyword or the JCL EXEC
PGM=XXXX

Frequent Coding Causes: Change &COBPGM. ➔ XXXX


- Module deleted from library, or never compiled to
library

- Module name spelled incorrectly

- STEPLIB does not contain load library with module Note: If the initial EXEC PGM=XXXX
- I/O error occurred while z/OS searched the directory is incorrect and causes the S806 -
of the library the Debugger will not start 272
B37/D37/E37: Dataset or PDS Index Space Exceeded

ABENDS - B37/D37/E37 (RTS-028) Tools to debug:


B37: Disk volume out of space. Static – Fault Analyzer will show the DSNs of the out-of-
space dataset. As will the JES Output messages
D37: Primary space exceeded, no secondary extents defined.

E37: Primary and secondary extents full. In TSO, PDS directory On the host the JCL will show the DDNAME and z/OS filespec
needs compress. of the dataset in question
E37-04: Disk volume table of contents (VTOC) is full. Dynamic
Reason: Set an advanced conditional break point to break on a certain
number on iterations
MVS could not find space for output WRITE to disk
See S222/S322 reasons and solutions
Instructions: Also, set break point on file WRITE statements
WRITE

Frequent Coding Causes:

- Not enough space initially allocated to output file(s).

- (more likely) Logic error - program in (infinite) loop writing output file(s)
- see S222/S322 reasons.

273
ABEND or Invalid Data - Which is worse???
• It is a widely held axiom that invalid production data is far
costlier than MVS ABENDs:
• When something ABENDS it ABENDS
• Execution stops
• z/OS tells you precisely what failed - when & where it failed (the why & how are part of your job)
• Backout routines can be called automatically
• CHECKPOINT routines can be used to provide point-in-time recovery
• When applications "go EOJ":
• Results may (or may not) be correct
• Often only business users can verify this
• If results are not correct:
• What's wrong - was it the data or the code?
• If it's the code, where in heck do you start?
• Backtrack - or start from the beginning
• If this was production, invalid values will negatively impact the corporation - not just you or your team
• Sometimes programs contain their own "self-balancing" defensive-programming:
• Record in/Record out counters
274
• Amounts in/Amounts out as well "trial balances"
Avoiding ABENDS
• Data: • Program "fall-thru":
• Truncation: Understand the COBOL statement/operations • Paragraph Fall Thru: Debug with "Conditional Watch
• Incorrect PIC clause alignment in the record layout: Align the Monitors and/or code a DISPLAY statement at the top of
actual data file to the record layout the paragraph - which names the paragraph.
• IF/Conditional Fall /thru: Ditto
• Numeric data:
• Reference to numeric field that contains non-numeric data: • Iteration:
Liberal use of IF … NOT NUMERIC tests • Infinite Loops: Check for numeric truncation in loop
• Decimal place precision and rounding - esp. with internal counters
variables: Understand the underlying accounting - and
use ROUND • File Handling
• Invalid ASSIGN clause: Vertical split screen, view JCL &
• File Problems: Program ENVIRONMENT DIVISION
• Read past end of file: Debugging, Desk-Checking and Peer
Reviews • JCL
• Reference to file before OPEN or after CLOSE: Ditto • Incorrect module name: Typically easy (JCL Error)
• Write loop fills up the output file: Understand the record • Invalid DD Name - View ENVIRONMENT DIVISION and
capacity and file Space Allocation. Debug for Infinite batch JCL side-by-side
Loop
• Invalid DSN: JCL Error
• IF Conditions • File not the correct DCB: Debug with "Conditional Watch
Monitors.
• Incorrect specification of True/False logic: Debug with
"Jump To" function, Flow Charting, Clear understanding • DISP= not correct with READ/WRITE: ABEND upon OPEN
of the COBOL semantics and business spec. <file>. In general: OPEN INPUT assumes that the file contains
data (DISP=SHR) and OPEN OUTPOUT assumes that the file
is empty (DISP=NEW). OPEN OUTPUT will over-write the
content of a file. 275
Avoiding ABENDS and COBOL Logic Errors - Coding Best Practices
Defensive Programming COBOL language error trapping clauses
• INITIALIZE fields at the beginning of a routine
• Pay particular attention to flags and accumulators

• I/O Statements:
• Use a FILE STATUS variable, and always check it
• Always check for Empty Input files and other possible I/O exceptions

• Numeric Fields:
• Never trust a numeric field that you're doing math on (never assume the data is good)
• Understand the use of ROUNDED
• Always include ON OVERFLOW and ON SIZE ERROR
• If a numeric data item is NOT being used in a calculation, declare it as PIC X

• Format your code


• Consistent use of Scope Terminators: END-IF, END-COMPUTE, END-PERFORM, etc.
• Run your code thru Software Analysis (Code Review) scanners
• Desk Check and peer-review - i.e. find programmatic & business logic errors
• Testing - Methodical, comprehensive Quality Assurance measures are the best defense against ABENDs276
Avoiding ABENDs and Software Logic Errors - ABEND Routines
ABEND on Purpose
• Data Integrity is ultimately the responsible of your COBOL program. And even if a system
ABEND does not occur, there are typically many situations or data results that are unexpected
or unacceptable, and you will be expected to call an "ABEND Routine"
• Values outside allowable ranges i.e. ON OVERFLOW
• Database/IO calls that detect an error-condition
• Empty input file
• Specific record(s) not found
• Negative return-code from a call

• ABEND routines are typically supplied by corporations - including directions on how to "call"
them, when anything that warrants ending your program happens.
• The logic would look something like this:
• IF ABEND-Condition
• PERFORM ABEND-ROUTINE
• ABEND-ROUTINE
• Set error-message and displays
• Take steps to end the program
277
ABENDING in Production vs. Test and Development
• ABENDs during Development & Test are expected
• Not welcome - but expected
• ABENDs in Production are expensive - and unacceptable
• They negatively impact corporation financials, market reputation, etc.

ABENDs during
Production ABENDs Development/Test
Unacceptable Inconvenient
Loss of business revenue Expected
Denial of service to customers

278
COBOL Program Big Picture - Topics in Module 10
Identification Name the executable Program-ID. PAYROL03.

SELECT <internal file name> ASSIGN TO JCL-DDNAME


Statements that connect the
Environment program to Indexed and
FILE SECTION
FD
Sequential data sets. 77 Standalone variable declaration
01 Data Hierarchy variable definition
05
Variable declarations - Fields 10
that contain values to be Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
Data processed in the program's REDEFINES
88 Named condition
PROCEDURE DIVISION
Signed Numeric PIC
FILLER
VALUE
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

Executable statements that IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields
Procedure process the variable values in
Compound IF, Nested IF
EVALUATE
the DATA DIVISION Signed Conditions, Class Conditions
MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
DISPLAY
z/OS ABENDS GOBACK

• Understanding
Code Paragraph
PERFORM Paragraph UNTIL <condition>

• Safeguarding
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>

COBOL
INITIALIZE

• Resolving
Counters, Accumulators, Flags

Divisions
Reference Modification
Figurative Constants
 Nothing to hand in

Workshop 10 - Using the Debugger to Experience the Common ABENDs


1. Run COBUCLD on the following LEARN.COBOL(Sxxx) programs. Each program will produce
the ABEND condition associated with its name.
ABEND Code Description Programs that will ABEND
S001 Record Length/Block Size Discrepancy S001
S013 Record Length/Block Size Discrepancy S013
S0C1 Invalid Instruction S0C1
S0C4 Storage Protection Exception S0C4 - There are multiple scenarios in the program comments
S0C7 Numeric Data Exception S0C7 - There are multiple scenarios in the program comments
S0CB Divide by Zero S0CB
S222/S322 Time out/Job Cancelled N/A
S806 Module Not Found Mistype the name of: PGM=xxxx in the JCL
B37/E37 Out of space (output file) B37
2. If you're using zserveros, run these ABEND programs again using COBUCLG. From JES, open
the file: GO:RUN:IDIREPRT. Read the first page of SYSOUT and validate the report with the
errant program logic.
3. Using defensive programming techniques - add COBOL code into each of the Sxxx programs
so that they do not ABEND 280
Online sources for MVS ABEND Code research
Online sources for MVS ABEND Code research - the other sites will have to be referenced via URL

• http://www.jsayles.com/tech/cobol/ABEND.htm

• http://ibmmainframes.com/references/a29.html

• http://faculty.madisoncollege.edu/schmidt/mainframe/abendcodes.html

Wikipedia DB2/SQLCODES Site: http://en.wikipedia.org/wiki/DB2_SQL_return_codes


IBM SQLCODE and SQLSTATE Analysis:
• http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzala%2Frzalaco.htm
• http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2z10.doc.codes%2Fsrc%2Ftpc%2Fdb2z_sqlcodes.htm

Miscellaneous site: http://theamericanprogrammer.com/programming/sqlcodes.shtml


MS ABEND Code Sites:
• http://mainframe230.blogspot.com/2011/04/ims-dbdc-return-codes.html
• http://www.felgall.com/ims1.htm
• http://theamericanprogrammer.com/programming/abend-codes.shtml

Note that these site links are not


IBM endorsements - they are
simply lists of internet resources 281
UNIT COBOL for z/OS - Module 11

Coding Standards and Best Practices -


COBOL Quality Measures:
• Capitalization
• Naming conventions
• Coding Style
• Sentences, End-if, Use of Periods
• Input/Output FILE-STATUS Checking
• Grouping W-S functionally
• COBOL Comments

Article on structuring your COBOL PROCEDURE DIVISION


https://condor.depaul.edu/jpetlick/COBOL03.html 282
283
COBOL Program Big Picture - Topics in Module 11
Identification Name the executable Program-ID. PAYROL03.

SELECT <internal file name> ASSIGN TO JCL-DDNAME

Environment Statements that connect the FILE SECTION


program to Indexed and FD COBOL Coding Standards
Sequential data sets. 77 Standalone variable declaration
01 Data Hierarchy variable definition
05
• Quality
• Consistency
10
Variable declarations - Fields COMP, COMP-3, DISPLAY EBCDIC values
Data that contain values to be REDEFINES
processed in the program's
PROCEDURE DIVISION
88 Named condition
Signed Numeric PIC
FILLER, VALUE
• Compliance
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Executable statements that Compound IF, Nested IF
Procedure process the variable values in EVALUATE
the DATA DIVISION Signed Conditions, Class Conditions
MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
DISPLAY
GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
INITIALIZE
z/OS ABENDS
COBOL Counters, Accumulators, Flags
Reference Modification • Understanding
Divisions Figurative Constants • Safeguards
• Resolutions
COBOL Coding - Styles and Standards
• Software programming - and this is especially true of COBOL whose language design was
codified in the late 1950's - is more "art" than "engineering"

• A fundamental mechanism used by corporations to build application portfolios that


run their business reliably and efficiently are "Coding Standards"

• What are Coding Standards?


• Coding Standards are programming policies, guidelines and best practices
• Different software languages and different application domains have different types of
Coding Standards and different levels of required compliance.

• Every shop has its own set of Coding Standards

• For COBOL Business Applications - there are two primary benefits:


1. Code Quality … 2. Code Consistency
284
Code Quality
• During this course you will write/test programs measured in the dozens to
(low) hundreds of lines
• In the real-world of production business AppDev, you will find no such programs.
Real-world COBOL programs are measured in the thousands to tens-of-thousands
of lines.**
• To code/test efficiently and effectively, you should learn and adhere to your shop's
Code Quality rules.

• NET: The next generation of COBOL programmers assigned to maintain and


support your code will need to be able to 1; Understand the details of your
program design and 2; Be able to make changes to your programs with confidence.

** We have actually seen single Business Application programs in excess of 200,000


lines. Coding programs this large is not considered a "Best Practice".
285
Code Consistency
Code Consistency means creating uniform COBOL routines that developers recognize and can;
Fix when broken, Maintain efficiently over time and Upgrade with confidence that unforeseen
errors will be minimized. Note that COBOL Comments are a major part of what makes
programs easy to maintain…………..or not.
Some of the categories of Coding Standards for Quality and Consistency:
1. Capitalization
2. Naming Conventions
3. Scope terminators
4. Sentences vs. Statement code-authoring style
5. File-Status
6. Grouping variable types in WORKING-STORAGE
7. READ INTO/WRITE FROM
8. Use of GO TO and other COBOL language features
9. Reusable code libraries
10. Structured COBOL Coding 286
Capitalization
There are several approaches to capitalizing code, and six COBOL language categories to consider:
Language Categories UPPER CASE InitCap (Mixed Case) lower case
IF, MOVE, PERFORM, If, Move, Perform, Write, Read if, move, perform
Reserved Words WRITE, READ, SECTION Procedure Division procedure division.

WS-LINE-COUNTER, Ws-Line-Counter, Last-Name, ws-line-counter, last-name


Variable Names LAST-NAME, EMP-SALARY Emp-Salary emp-salary

400-READ-FILE 400-Read-File 400-read-file


Paragraph and Section Names 100-HOUSEKEEPING 100-Housekeeping 100-housekeeping
999-ABEND-ROUTINE 999-Abend-Routine 999-abend-routine

THIS IS A COMMENT This Is A Comment this is a comment


Comments
UPPER-CASE Upper-Case upper-case
Intrinsic Functions SQRT Sqrt sqrt

TODAY'S DATE IS: Today's Date Is: today's date is


Literals / VALUE Clause

Note that you can mix & match the above options and language categories
i.e. Reserved Words and Paragraph Names will be Upper-Case, Comments and Value
Clauses should be Mixed Case. 287
Capitalization - Examples

288
Variable and Paragraph Naming Conventions
• There are dozens of approaches/standards for COBOL program naming conventions
• The goal for all naming standards is "meaningful" - as in, the paragraph or variable name should
be easily understood and descriptive of its business content or purpose
WS-LAST-NAME
• Besides labels, shops often use COBOL-DIVISION standards such as: WS-ERROR-REC-KTR
WS-GRAND-TOTAL
• WORKING-STORAGE variable names start (or end) with WS- …
• LINKAGE SECTION variable names start (or end) with LS- LS-ACCOUNT-NBR
LS-GROSS-PAY
• Paragraph names begin with a 3-digit prefix LS-RETURN-CODE
• Commonly-required paragraphs should have prescribed names:
• MAIN, READ, OPEN, CLOSE, ABEND, etc.
100-HOUSEKEEPING
300-MAIN
• Additionally, you will find common field abbreviations in COBOL programs: 400-READ
• Counter ➔ KTR, CTR 500-WRITE
• Total ➔ TOT, ACCUM 900-ERROR-
PROCESSING
• NUMBER ➔ NBR, NO, NM

• Last name/First name ➔ LNAME, FNAME, LAST-NM, FIRST-NM
• Date ➔ DT, DTE, DAT, CC, YR, MN, MNTH, DY, 289
Prefix Variable Naming - Examples

+ Can see at-a-glance where the field is declared


- Makes the PROCEDURE DIVISION code bigger

290
Code Authoring Style - Sentences vs. Statements
• From Module 3
• Paragraphs consist of one to many sentences
• Sentences consist of one to many statements
• Statements consist of one to many keywords
and variables

• You can end statements with a period


…or…

• End sentences with a period


• In which case, you will use explicit scope-terminators in
PROCEDURE DIVISION statements

• Pluses to using sentence-based coding style:


• Less possibility of PROCEDURE DIVISION "fall-thru"
• More of a modern COBOL coding approach
• The more complex the code, the more beneficial sentence-
based coding becomes
https://www.ibm.com/support/knowledgecenter/en/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/concepts/cppgm42.htm 291
Explicit Scope Terminators
• A scope terminator marks the end of certain PROCEDURE DIVISION
statements.
• Explicit Scope Terminators are used in place of periods as a means of
documenting the end-scope of COBOL keywords:
• IF … … END-IF
• PERFORM … END-PERFORM
• COMPUTE (and other math statements) COMPUTE … … END-COMPUTE
• READ/WRITE - READ … … END-READ WRITE … … END-WRITE
• SEARCH … END-SEARCH
• STRING/UNSTRING - UNSTRING … … END-UNSTRING

• They are considered a "Best Practice" for COBOL coding - as they explicitly
define the extent of the keyword operation.

Links to additional scope terminator documentation and learning content:


• http://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlpdsste.htm
• http://www.naspa.net/magazine/1999/January/T9901012.PDF
292
Scope Terminator Examples

.
COBOL Statement (period) Coding Style
293
Scope Terminators - CONTINUE vs. NEXT SENTENCE
Both NEXT SENTENCE and CONTINUE can be used in an IF statement as a "no-op" - basically a do-nothing IF branch
The distinction between NEXT SENTENCE vs. CONTINUE is critical - particularly if Scope Terminators are a shop standard.
• NEXT SENTENCE will execute the COBOL verb following the next period (.)
• CONTINUE will execute the next verb after the explicit scope terminator (END-IF)
If you are you are using Scope Terminators, it's safer to use CONTINUE rather than NEXT SENTENCE.
MOVE 5 TO AMT-1.
MOVE 9 TO AMT-2.

IF AMT-1 IS LESS THAN AMT-2 If AMT-1 IS LESS THAN AMT-2 NEXT SENTENCE will DISPLAY only AMT-3.
NEXT SENTENCE
DISPLAY 'AMT-1: ' AMT-1 Challenge Question - Why does NEXT SENTENCE work this way?
DISPLAY 'AMT-2: ' AMT-2.
DISPLAY 'AMT-3: ' AMT-3.

IF AMT-1 IS LESS THAN AMT-2


CONTINUE
END-IF If AMT-1 IS LESS THAN AMT-2 CONTINUE will DISPLAY AMT-1, AMT-2 and AMT-3.
DISPLAY 'AMT-1: ' AMT-1
DISPLAY 'AMT-2: ' AMT-2.
DISPLAY 'AMT-3: ' AMT-3. 294
I/O File Status Checking
As a Best Practice, always define and verify
every I/O operation in your program:
• QSAM and VSAM files
• FILE STATUS field - defined in WORKING-
STORAGE

• IMS 'CBLTDLI' Calls


• DL/I Status Code - defined in the LINKAGE SECTION QSAM/VSAM File-Status Checking Pattern:
• SQL queries 1. Define a 2-byte PIC X field for each file in WORKING-
• SQLCODE - part of an SQLCA WORKING-STORAGE
STORAGE
record structure 2. Reference the field with a FILE STATUS IS… statement in the
ENVIRONMENT DIVISION
3. Test the file status variable after each I/O operation in the
Follow these rules for each file: PROCEDURE DIVISION
• Define a different file status key for each file.
• Check the file status key after each input or output request.
• If the file status key contains a value other than 0, your program can issue an error message or can take action based on that value.

• You do not have to reset the file status key code, because it is set after each input or output attempt.
• Comprehensive web-page for File Status code: http://ibmmainframes.com/references/a27.html 295
File Status - Examples

Working-Storage Definitions
Procedure Division
File OPEN

Procedure Division
ENVIRONMENT DIVISION File READ

296
Formatting - "Pretty Printing"
Line up DATA DIVISION variables based on Level numbers
01 - column 8
05 - column 12
10 - column 16
• VALUE clauses and 88-levels line up
• Indent conditional logic
• "Spacer lines" between statements.

Line up PROCEDURE DIVISION "TO" statements:


Unformatted Formatted

297
298

Formatting - Visual-alignment of procedural flow-dependencies

Indent/Outdent conditional and iterative/UNTIL logic


Unformatted
Coding Styles -
Group Related Fields
• Group related Working-Storage
fields:
• File-Status variables
• Flags and Switches
• Counters-and-Accumulators
• Variables of a given domain
• ABEND variables
• What paragraph did the ABEND
occur in
• Any other salient information that
can be dynamically carried
throughout the code
• …
299
Use of GO TO and other COBOL Language Options
Most COBOL shops have an extensive
IDz & ZOD Code Review
list of COBOL language do's and don'ts:
• Do use Scope Terminators
• Do use Sentence Structure
• Do not use a number of COBOL
verbs:
• ALTER
• GO TO
• ACCEPT
• PERFORM THRU
• OCCURS DEPENDING ON
• …

Compliance with shop rules is enforced by; Peer Reviews, REXX/CLIST scripts or IDE-based Tools 300
COBOL Comments
The semantics of a COBOL program are captured in the code**. And before
1.
changing one sentence, it's your responsibility to understand the semantics
of the code. Comments are the only mechanism by which you document
WHAT a program does as well as HOW a program works.
Typically you will see comments in three places:
1. At the top of the program
• A general description of the entire program. And other specifics such as a
maintenance log, change dates, reasons, names, files, etc.

2. At the top of each paragraph:


• Describing the key functionality in the paragraph - along with any useful 2.
business-level doc, and a maintenance log, etc.

3. Inline with the code


• The Compiler will ignore whatever is to the right of *>
• So developers can craft annotations, reminders, etc. embedded in the code
itself
** Program semantics are not only defined by
variables in the DATA DIVISION, they are buried in
the procedural structure of the performed
301 3. paragraphs that process the data
Approaches to Coding Standards Compliance
• Tools-based approach:
• There are a number of tools on the market from different software vendors
• Application Discovery - An Enterprise-wide COBOL application analysis product
• IDz and ZOD Code Review - A collection of coding rules and Best Practices packaged with IDz or ZOD
• Sonarsource: https://www.sonarsource.com/cobol/

• Manual Desk-Checking/Peer Reviews:


• Many shops have created a formal list of coding standards in MS-Excel, MS-Word, etc.
• COBOL code is compared to, or reviewed against standards, line-by-line
• In-house developed "Applets":
• There are two z/OS "command languages" - REXX and CLIST language that are used to parse
application programs
• The parsing typically based on the coding standard documents
• The REXX or CLIST Applets compare COBOL code electronically
302
Reusable Code Libraries
• IDz and ZOD provide a collection of sample statement templates ➔
• The templates can be Ctrl+Spacebar inserted into your COBOL program. The code in
the templates follows current Best Practices standards - including Scope Terminators.
You can modify the provided Templates - creating your own library of reusable
statements based on your shops Code Review Standards

• You're also encouraged to create your own reusable code library


consisting of tested COBOL routines/examples:
• Numeric calculation
• Nested IF/Evaluate
• Date & Time handling snippets
• Sequential File Handling examples
• ABEND routines

• Shops using TSO/ISPF often implement the same "Reusable Code Library" principle - by creating PDS (Libraries) that
contain:
• Program skeletons for different kinds of projects
• "Copybook" and "Include" libraries that contain:
• Predefined WORKING-STORAGE record definitions
• PROCEDURE DIVISION code for common routines (I/O, ABEND handling, Complex computations, etc.)

• The COBOL content in these resources can be either copied in on-demand, using ISPF Command Line "Copy"
- or using the COBOL: COPY keyword - which we'll learn about later in this course 303
COBOL Program Big Picture - Topics in Module 11
Identification Name the executable Program-ID. PAYROL03.

SELECT <internal file name> ASSIGN TO JCL-DDNAME

Environment Statements that connect the FILE SECTION


program to Indexed and FD
Sequential data sets. 77 Standalone variable declaration
01 Data Hierarchy variable definition
05
10
Variable declarations - Fields Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
Data that contain values to be REDEFINES
processed in the program's 88 Named condition
PROCEDURE DIVISION Signed Numeric PIC
FILLER
VALUE
Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

Executable statements that IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields
Procedure process the variable values in Compound IF, Nested IF
the DATA DIVISION EVALUATE
Signed Conditions, Class Conditions
z/OS ABENDS MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
• Understanding Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
• Safeguards DISPLAY
• Resolutions GOBACK
Code Paragraph
COBOL Coding Standards PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
• Quality
COBOL
INITIALIZE
• Consistency Counters, Accumulators, Flags

Divisions
Reference Modification
• Compliance Figurative Constants 304
 Nothing to hand in
Workshop 11.1
Steps - only for ZOD/IDz users:
1. Set your own custom Formatter options for;
• Capitalization Styles
• Procedure Division

2. Open LEARN.COBOL(FORMATER) and


browse around inside the source file
• From the Context Menu, right-click and select:
• Source ➔ Format ➔ Yes
• Browse again throughout the file, and note the
differences
• Repeat this exercise with CBL0009

3. Open PAYROL3A.
• Add Scope Terminators to paragraphs 300, 600 and 700
• Re-write the PROCEDURE DIVISION, turning all of the
COBOL statements ending with periods into Sentence
structure code. 305
Optional Workshop 11.2 - Multiple Input Record Types
It's end-of-year, you've finished your project, but have another week left
on your contract. Your manager walks over to your desk and she says
"Hey <your-name> ... There's this program your predecessor wrote that
was "finished" (air quotes) - but we've never been confident that it works The Current Report Output
(see report)

Multiple 01-record layouts for the same file


You glance over and think "Yep - this is one defective piece of COBOL".
Duplicate names for the 1st & 2nd output records … Total students: 1
Your boss looks at you and says, "So - you can pack up early, or you
can spend another week fixing this" (a no-brainer…)
I'll do it!!! You say with all the enthusiasm that goes along with three
exclamation marks. And so it begins with you obtaining the source and
reading it line-by-line
Early in your analysis you realize that the dang thing uses an input file:
LEARN.STUDENT that actually sports multiple record layouts - which
(you realize) is not something you learned in class, making a mental
note to write an accusatory eMail to Jon .cc to his IBM boss.

Anyway - if you're up for this challenge, grab the program code,


DDS0001.LEARN.COBOL(STUDENT) the file records and fix this dilapidated
program - with appreciation for the fact that You're billing for this.
306
 Nothing to hand in

Optional Workshop - Review COBOL Source Code Standards Online


https://www.ibm.com/support/knowledgecenter/SSUFAU_1.0.0/com.ibm.rsar.analysis.codereview.cobol.doc/topics/cac_anconfig_describerul
es.html - Comprehensive Coding Standards documentation

http://mainframe-tips-and-tricks.blogspot.com/2012/11/sample-cobol-coding-standard.html - Naming Conventions and Coding Practices

https://www.unf.edu/~broggio/cop3531/standard.html - coding standards broken out by COBOL Divisions

https://www.tonymarston.net/cobol/cobolstandards.html - the COBOL language per se

https://www.csus.edu/indiv/c/christenson/DL_Files/CobolStandards.pdf - Business COBOL coding standards. Unsparing details

https://ags.hawaii.gov/wp-content/uploads/2012/09/ITS_1110.pdf - Business COBOL coding standards. Unsparing details


https://www.cusys.edu/pubs/1cobol.html - COBOL Programming Language break-down of coding standards
http://ibmmainframes.com/references/a7.html - Detailed (COBOL statement-level) collection of practical coding "Do's & Don'ts"
http://www.mainframes360.com/2009/08/cobol-tutorial-compiling-linking-and.html - Common COBOL coding errors

You should also know about SONAR technology for COBOL

Note that these site links are not


IBM endorsements - they are
simply lists of internet resources 307
 Nothing to hand in

Coding Styles -
Tools
• IDz and ZOD provide
automated code
formatting
capabilities:
• Source ➔ Format

• The rules can be


customized from:
• Window ➔
• Preferences

• Note that these


coding styles can be
enforced upon SAVE 308
Compile JCL … Run JCL
• The EXEC statement marks the beginning of a step within a job, and specifies the name of a
compiled program or cataloged JCL PROC to be run.
• PROCS are named collections of partial JCL. They contain one or more EXEC statements and data definition (DD)
statements, that perform frequently used functions such as Compile/Link, Sort/Merge, etc.
• Programs and cataloged procedures are stored in library data sets,
• Successfully Compiled and Link-Edited programs are stored in a LOADLIB - a library that contains "Load Modules"
• PROCs are stored in a PROCLIB
//JOBNUM1 JOB 504,SMITH PAYROLL
//STEP1 EXEC PGM=PROGRAM1
//STEPLIB DD DSN=HLQ.LOAD.LIB,DISP=SHR
//* STEPLIB = The Library name where z/OS can find the program
//DD1 DD DSN=HLQ.INPUT
• In the above EXEC statement:
• The name field contains the EXEC step name "STEP1".
• A step name is a 1 ➔ 8 character name that identifies the job step so that other JCL statements or the
operating system can refer to it.
• A parameter (PARM=) field can pass variable data into a program

Job Control Language: JCL - an excellent online tutorial into this critical topic
309
• https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zjcl/zjclc_basicjclconcepts.htm
Creating Output Files and Libraries
• The EXEC statement marks the beginning of a step within a job, and specifies the name of a compiled program or cataloged
JCL PROC to be run.
• PROCS are named collections of partial JCL. They contain one or more EXEC statements and data definition (DD)
statements, that perform frequently used functions such as Compile/Link, Sort/Merge, etc.
• Programs and cataloged procedures are stored in library data sets,
• Successfully Compiled and Link-Edited programs are stored in a LOADLIB - a library that contains "Load Modules"
• PROCs are stored in a PROCLIB
//JOBNUM1 JOB 504,SMITH PAYROLL
//STEP1 EXEC PGM=PROGRAM1
//STEPLIB DD DSN=HLQ.LOAD.LIB,DISP=SHR
//* STEPLIB = The Library name where z/OS can find the program
//DD1 DD DSN=HLQ.OUTPUT,DISP=(NEW,DELETE,KEEP),
// DCB=(LRECL=100,

310
UNIT COBOL for z/OS - Module 12

Mid-Term Project and Miscellaneous Topics:


• FigCons
• REDEFINES
• RefMods
• Counters/Accumulators and Flags
• Mid-Term Program
• Specifications
• Data
• Output
• Top-down testing 311
Cracking the Code: Figurative Constants
• A Figurative Constant ("FigCon") is a COBOL reserved word that
defines a "constant value". The value is similar to a literal - except that
Figurative Constants consist only one given value.
• HIGH-VALUES/HIGH-VALUE - An alphanumeric constant consisting of binary X'FF' values
• LOW-VALUES/LOW-VALUE - An alphanumeric constant consisting of binary X'00' values
• SPACES/SPACE - An alphanumeric constant consisting of blanks - X'40' values
• ZEROES/ZERO - An alpha - or - numeric constant consisting of binary X'F0' values
• ALL - An alphanumeric constant consisting of the one-character-literal follows the word ALL
• MOVE ALL '9' TO TRANSACTION-FINIS - a field defined as PIC X
• MOVE ALL 9 TO END-OF-FILE-KEY - a field defined as PIC 9 (either DISPLAY, COMP or COMP-3)

• IF statements sometimes reference FigCons in conditional expressions:


• IF END-OF-FILE-KEY = HIGH-VALUES
• IF KEY-CHARS = LOW-VALUES
• IF LAST-NAME = SPACES
• IF RECORD-ID = ALL '9' 312
Cracking the Code: REDEFINES
• The REDEFINES clause allows you to use different data description names and PIC Clauses to describe
the same DATA DIVISION byte storage
• Typically REDEFINES is done for one of three reasons:
• To save disk space
• To store different domain data within the same bytes in a record  Note: Excellent REDEFINES examples in this web page
• To use data manipulation techniques on fields with the wrong USAGE (i.e. Alpha vs. Numeric)

05 FLDA PIC X(6). *> Six total bytes of storage


05 FLDB REDEFINES FLDA.
10 FLDB-1 PIC X(2). *> Two total bytes of storage
10 FLDB-2 PIC 9(4). *> Four total bytes of storage
05 ...

• When specified, REDEFINES must be the first keyword after the field name and followed by the to-be-
redefined field
• The REDEFINES variable must contain the same number of bytes as the field being redefined - and the
data item Level Number must be the same. 313
05 WITHDRAWALREDEFINES-DATE PIC 9(08).
05 WITHDRAWAL-DATE-RDF WITHDRAWAL-DATE.
REDEFINES Examples 10 WITHDRAWAL-YEAR PIC 9(04).
10 WITHDRAWAL-CCYY REDEFINES WITHDRAWAL-YEAR.
15 WITHDRAWAL-CC PIC 9(02).
15 WITHDRAWAL-YY PIC 9(02).
10 WITHDRAWAL-MONTH PIC 9(02).
10 WITHDRAWAL-DAY PIC 9(02).

05 CUSTOMER-NAME PIC X(30). In the same 30-bytes of storage, your


05 CUSTOMER-BUSINESS-NAME-RDF REDEFINES CUSTOMER-NAME. program can refer to:
• CUSTOMER-NAME
10 COMPANY NAME PIC X(30).
• COMPANY-NAME
10 CUSTOMER-OWNER-NAME REDEFINES COMPANY-NAME • CUSTOMER-OWNER-NAME
15 FIRST-NAME PIC X(15). • FIRST-NAME
15 LAST-NAME PIC X(15). • LAST-NAME

• When you redefine a 01 field/record with another 01 field/record, the redefining record's PIC clause(s) can add up to
more, less or the same number of bytes.
• But when you redefine a non-01 field by another non-01 field-2 - the two total definitions of both fields should
match - but minimally, the redefined record must be as large as the redefining record. 314
Cracking the Code: Reference Modification (COBOL "SubString")
• Not all data definitions can be handled with REDEFINES - and not all meaningful data can be defined using
Level numbers and fields. Because of the extreme variety of data formats COBOL programs have to deal
with, the language provides a string manipulation feature known as Reference Modification (RefMod).
• RefMods allow you to sub-string (to access one or more contiguous characters) of a PIC X or PIC 9 (DISPLAY)
variable as if it were an array of bytes. A RefMod requires; Variable-Name, StartByte, EndByte - in this format:

Examples: KEYFLD(3:6)
01 KEYFLD PIC X(8).
… <Variable-Name>(START_BYTE:LENGTH)
01 DATE-FLD PIC X(10).
* COMMENT - CCYY/MM/DD FORMAT
… • Variable-Name
MOVE DATE-FLD(1:4) TO CCYY-OUT. • Start-Position
MOVE DATE-FLD(6:2) TO MM-OUT. • Length (# of bytes referenced)
MOVE DATE-FLD(9:2) TO DD-OUT.

IF KEYFLD(3:6) = 'ACC1' … Note: While you can use RefMod sub-stringing with PIC 9 fields,
ELSE IF KEYFLD(4:8) = 'BDLE0' … you cannot use RefMods in a math statement. This is because
ELSE IF KEYFLD(2:3) = 'XX' … COBOL considers a RefMod to be an Alphanumeric operation. 315
Cracking the Code: Counters, Accumulators and Flags
• Because COBOL is a data-file-I/O-centric language, many of the programs that you'll run into will:
• Read a file - and add +1 to a Record-Counter for each record-read.
• At the end of the file a value will be moved to the end-of-file "flag".
• Process the data - and keep a running total of numeric fields in "accumulators"
• If the program edits fields in the data, often a flag will be used to specify if the data is "good" or "bad"
• Write an output record - and typically add +1 to a Page or to File-Record-Counter for each record written

05 SWITCH-EOF PIC X(1) VALUE 'N'.  Note that "flags" are often referred to as "switches"
88 END-OF-FILE VALUE 'Y'.
05 WS-IN-RECORD-KTR PIC S9(7) COMP-3 VALUE ZERO.
05 WS-OUT-RECORD-KTR PIC S9(7) COMP-3 VALUE ZERO.
05 WS-SALARY-ACCUM PIC S9(8)V99 COMP-3 VALUE ZERO.

READ INFILE AT END MOVE 'Y' TO SWITCH-EOF ** Note that
IF NOT END-OF-FILE ADD +1 TO WS-IN-RECORD-KTR.

ADD COMPUTED-SALARY TO WS-SALARY-ACCUM
… The use of flags, counters
WRITE OUT-RECORD and accumulators involves
IF FILE-STATUS = '00' ADD +1 TO WS-OUT-RECORD-KTR. conditional expressions. 316
 Nothing to hand in

Workshop 12.1 - REDEFINES and RefMods


Edit WRITEFIL.
Add statements in the PROCEDURE DIVISION to:
1. Move your name to NAME.
2. Move a company name to CORPORATION
• Include either the LLC or DOT-COM suffix
3. Experiment with RefMods
• Select a substring portion of your name and DISPLAY it
• Choose a few other PIC X fields to substring with RefMods

Test your code using the Debugger


• When you're finished with the above, add the following
WORKING-STORAGE and PROCEDURE DIVISION code
to the program ➔
05 CUSTOMER-ACCT-BAL PIC S9(7)V99.
05 CUSTOMER-ACCT-BAL-X REDEFINES CUSTOMER-ACCT-BAL PIC X(9).

• Compile/Link/Debug MOVE '12345678' TO CUSTOMER-ACC-BAL-X.
IF CUSTOMER-ACCT-BAL-X IS NOT NUMERIC DISPLAY "NOT NUMERIC". 317
Mid-Term Exam - Specification 1 of 5

COBOL Record Layout


Create a report that writes records for all medical claims that are in-policy.
Use the record layout shown here ➔
Glossary of Terms:
• Policy-Number: Unique identifying number for each policy sold
• Policy-Type: Type of insurance in-force
• Policy-Benefit-Date: The date the policy was written
• Policy-Amount: The amount currently left on the policy
• Policy-Deductible: The amount paid for covered services before insurance kicks in
• Policy-Coinsurance: The % costs of a covered health service paid by the insured
• Claim-Amount: The amount of the medical charges
• Claim-Amount-Paid: The amount the company will cover of a claim
• Max-Coverage-Amount: The max claim amount for a policy of this type: $999,999.99

Sample
Data
318
Mid-Term Exam Spec: 2 of 5 - Business Logic

IF CLAIM-AMOUNT < ALLOWED-AMT


Calculate Deductible:
The Deductible is the Policy-Amount times the company's deductible (copay) % which is a constant .02
 Policy-Deductible-Paid is the amount the Insured has already paid towards their deductible and is carried
in the data.

Process the claim:


• If the Deductible has been met the Claim-Paid will be:
Claim-Amount minus the (Policy-Coinsurance * Claim-Amount)
• If the Deductible has not been met the Claim-Paid will be the
Claim-Amount - Deductible - (Policy-Coinsurance * Claim-Amount)
• Finally, subtract the Claim-Paid from the Policy-Amount (which is whatever is left
for this insured). If the result is > zero pay the claim (print the record) otherwise
deny the claim (don't print the record on the report)
319
Mid-Term Exam Spec: 3 of 5 - COBOL Copybooks
A copybook is a file of reusable source code. In most cases the Copybook will be a data record that maps exactly to
the fields in a file (i.e. the record layout). Copybooks are stored in Copy Libraries. Most production mainframe
applications make heavy use of Copybooks.
Here's your first one…Note that you should see this in your <TSOID>.COBOL.COPYLIB

The COBOL statement


used to access a
Copybook - from which
the program can
reference the fields in the
record layout it contains -
you code:
COPY <copybookname>.
…..in the B margin
320
Mid-Term Exam Spec: 4 of 5 - Output Report
• Below is a sample output from the report produced by an example-program from a
student in a previous class.
• You are to recreate this output using the:
• Record Layout
• Insurance Claims Logic
• Copybook

• Note that you're encouraged to make up your own data (MidTerm Slide 1 of 5) - so
that you lock down the FileData ➔ Copybook layout field & byte positions

DEDUC

321
Mid-Term Exam Spec: 5 of 5 - Attacking this kind of programming challenge
Level 1 Development - Understand the problem and design the solution "from a 1,000 foot view"
• Create the test data - first. By doing this you'll familiarize yourself with the program's "problem space"
• Study the claims processing business functionality When you understand exactly "what" is required, break the whole into parts … down to
what COBOL paragraphs will be required - and what will be in the paragraphs.
• Create a new program from an existing program - one that reads a file and writes a report so that you can inherit the ENVIRONMENT
DIVISION and other COBOL boilerplate. Substitute the USERID.LEARN.INSCLAIM file (ENVIRONMENT DIVISION) for the existing input file
and use the CLAIMREC Copybook file. Liberal use of Find/Replace All.
• Code the PROCEDURE DIVISION logic to PERFORM each paragraph. If using ZOD/IDz use the Program Control Flow to visualize your work.
• Comment each of the paragraphs with a "Flower Box" above the para-name, describing the logic in the paragraph
• STUB OUT the lower-level COBOL paragraphs that calc the deductible and process claims
• STUB OUT means to code the paragraph names, but don't add anything except a DISPLAY statement: DISPLAY 'PARA ' <paragraph-name>.

Level 1 Testing - COBUCLG - or COBUCLD the program, and view the logic flow for accuracy
Level 2 Development: Divide and conquer - Create the rest of the rest of the program. Code the PROCEDURE DIVISION logic to open the file.
And read and write each record.
• For MOVE & COMPUTE statements, copy the input record (CLAIMREC) into your processing routine - just for the sake of editing speed.
Consistent naming conventions are crucial throughout the code.
• Name Working-Storage fields for the same domain the same as the input/output fields - but use a WS- prefix or suffix

Level 2 Testing - Test/Verify then move on → one primary function at a time. 322
Split and Full-Screen development: Highly recommended
Report Line Records PROCEDURE DIVISION - references to CLAIM-RECORD Layout
WORKING-STORAGE SECTION variables WORKING-STORAGE SECTION

Copy/Paste - or - Read/Understand your data and


procedural programming work at-a-glance

Bookmarks (ISPF Labels) also come in handy 323


UNIT COBOL for z/OS - Module 13

COBOL "Intrinsic Functions"

• Using Intrinsic Functions


• Categories
• Syntax
• Working examples
• Reusable Code Libraries

This is a work-along module. If possible open your Client-IDE so that you can do the examples
alongside the instructor during this session. In order to do this, be sure that you have your client
product (ISPF, ZOD/IDz) up and running - and you have the eMail that was sent with the sample
programs available - to copy/paste into the library. 324
COBOL Program Big Picture - Topics in Module 13
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
Intrinsic Functions INITIALIZE
Reusable Code Libraries Counters, Accumulators, Flags
Reference Modification, Figurative Constants
z/OS ABENDS

• Concepts
Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Safeguards

• Create
Resolutions

COBOL • Maintain
Coding Standards
• Quality

Divisions •

Consistency
Compliance
Reusable Code - and Reusable Code Libraries
• (Not) reinventing the wheel has always been a good idea:
• Productivity
• Standardized applications
• Economy of scale
This is not really a controversial subject…

• There are five ways to reuse code:


1. Program Libraries (PDSs)
2. Copybooks (next Module)
3. SCM products: Git, RTC EE, Endevor…
4. IDz Snippets
5. ZOD/IDz Language Templates

• We will use Program Libraries


• Universally available on z/OS
• You will need to modify the COBUCLD
and COBUCLG JCL to compile/link and to
run/test programs stored in your reusable
code library. 326
Cracking the Code - Intrinsic Functions
• An intrinsic function (sometimes called a "built-in function") is a set of PROCEDURE
DIVISION keywords that performs an operation on data.
• Pre-packaged routines - similar in nature to Java Libraries, Intrinsic Functions can
simplify coding and testing - reusing existing working functionality as opposed to
writing new code for standard tasks
• The functions can be grouped into six categories, based on the type of service
performed:
1. Numeric
2. Mathematical
3. Statistical
4. Financial
5. Date/time
6. Character-handling The Intrinsic Functions
are similar to classes in
Java Frameworks 327
List of Enterprise COBOL Intrinsic Functions***
• How IBM categorizes the Intrinsic Functions

*** Note that Enterprise COBOL V6 includes additional (new) Intrinsic Functions
328
Coding Intrinsic Functions
You code an intrinsic function in one of two ways:
1. Value assignment from right-to-left (COBOL COMPUTE style)
• Specify the Data Division receiving variable name (must be type-compatible with the Function)
• Code the equal sign
• Code the reserved word: Function (this is capital-insensitive)
• Code the Function name
• Specify one or more parameters to the function - Separate the parameters by one or more blanks (spaces)
• Example:
Compute Ave-Tax = Function Mean (Tax-S Tax-T Tax-W Tax-B)

2. Value assignment from left-to-right (COBOL MOVE style)


• Code the COBOL MOVE keyword
• Code the reserved word: Function (this is capital-insensitive)
• Code the Function name
• Specify one or more parameters to the function - Separate the parameters by one or more blanks (spaces)
• Specify the receiving variable (must be type-compatible with the Function's return value)
• Example:
MOVE Function Length (Output-Record) To Rec-Lth

• For Intrinsic functions that return a numeric value you can use either the MOVE or COMPUTE coding style
• For intrinsic functions that return a non-numeric value you MUST use the MOVE coding style 329
Cracking the Code - Coding an Intrinsic Function
You invoke an Intrinsic Function by specifying its name, along with any required
arguments in the PROCEDURE DIVISION:
Examples:

COBOL Verb Intrinsic Function Argument

DISPLAY FUNCTION LOWER-CASE(Item-1).


MOVE FUNCTION UPPER-CASE(Item-1) to Item-2.
IF FUNCTION UPPER-CASE(LNAME) = ALL 'Z'
COMPUTE NUMVAL = FUNCTION SUM(ITEM-1, ITEM-2) * ITEM-3.
You can nest Intrinsic Functions - which can help solve specific processing requirements.
Find the (algebraic) highest price among two Alphanumeric fields that contain numbers:
Compute Product-Price =
Function Max (Function Numval-C(Price1) Function Numval-C(Price2)).
330
COBOL Intrinsic Functions Doc - on IBM.COM
From: https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlinf.htm

…you can find a short definition of Intrinsic Functions and Hyper-Links to details and examples
for each ➔

How
best to
learn
these?

Learn by
coding. 331
 Nothing to hand in

Workshop 13.1 - Create a Reusable


Code Library

1. Allocate a new COBOL library for your reusable code


programs and examples:
<TSOID>.LEARN.REUSABLE.COBOL

Note that if you're using ISPF:


• From =3.2
• Display statistics on <TSOID>.LEARN.COBOL
• PF3
• =3.2 and Allocate <TSOID>.LEARN.REUSABLE.COBOL

2. Repeat the above steps and create:


<TSOID>.LEARN.REUSABLE.JCL
332
 Nothing to hand in 333

Workshop 13.2 - Add a Numeric Intrinsic Function program to your Reusable Code Library
1. Open TESTCOB in the editor and File ➔ Save as… INTRNUM in LEARN.REUSABLE.COBOL
• Rename the program and delete the existing WORKING-STORAGE and PROCEDURE DIVISION code in INTRNUM

2. Copy COBUCLG and COBUCLD from LEARN.JCL to LEARN.REUSABLE.JCL


• Make the appropriate DSN changes from LEARN.COBOL ➔ LEARN.REUSABLE.COBOL in both files

3. From: https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rpari41e.htm
• Copy the General number handling code…
• Paste the code into INTRNUM
• Modify the program as you see here ➔
• Get rid of any syntax errors:
• Note that if you are using ISPF you will need to
Compile the program (see next step)

4. Edit COBUCLG in LEARN.REUSABLE.JCL


Change: LEARN.COBOL ➔ LEARN.REUSABLE.COBOL
Save the file - then do the same for COBUCLD

5. Run a COBUCLD on INTRNUM from LEARN.REUSABLE.JCL


• Note that if you want to Compile/Link/Go (run) instead of Debugging, you'll need to
add DISPLAY statements after the COMPUTE and MOVE.
334

Intrinsic Functions - INTRNUM Under Debug


• Be certain that you understand the Intrinsic Functions - as they are applied to the variables in
this program - and be able to explain the output results of the Debug run…

This is an UPPERCASE
rendering of the literal

This is the numerical max of two


formatted/edited numbers
 Nothing to hand in 000005 IDENTIFICATION DIVISION.
000006 PROGRAM-ID. INTRDATE.
000015 DATA DIVISION.
000016 WORKING-STORAGE SECTION.
Workshop 13.3 - Add a Date-Manipulation Intrinsic 000017 01 DATE-VARS.
000018 05 CURRENT-YEAR PIC X(4).
Function program to your Reusable Code Library 000019 05 CURRENT-MON PIC X(2).
000020 05 CURRENT-DAY PIC X(2).
000021 05 CURRENT-HOUR PIC X(2).
000022 05 CURRENT-MIN PIC X(2).
1. Copy and paste the following code into your 000023 05 CURRENT-SEC PIC X(2).
<TSOID>.LEARN.REUSABLE.COBOL library ➔ 000024
000025
05 CURRENT-MSEC
05 LOCAL-TIME.
PIC X(2).

000026 10 TIME-DIF PIC X(1).


…as a new program named: INTRDATE 000027 10 TIME-DIF-H PIC X(2).
000028 10 TIME-DIF-M PIC X(2).
000029 01 CURRENT-WEEK-DAY PIC 9(1).
2. Study the code, specifically the: 000030 01 WEEKDAYS-TABLE.
000031 05 PIC X(9) VALUE "Monday".
1. Line continuation character ( - ) in column 7 000032 05 PIC X(9) VALUE "Tuesday".
000033 05 PIC X(9) VALUE "Wednesday".
2. FUNCTION CURRENT-DATE 000034 05 PIC X(9) VALUE "Thursday".
000035 05 PIC X(9) VALUE "Friday".
• Note the number of elementary field value that 000036 05 PIC X(9) VALUE "Saturday".
CURRENT-DATE returns 000037 05 PIC X(9) VALUE "Sunday".
000038 01 REDEFINES WEEKDAYS-TABLE.
3. DAY-OF-WEEK used in a table lookup which returns the 000039 05 DT-OF-WK OCCURS 7 TIMES PIC X(9).
days name 000040 PROCEDURE DIVISION.
2.
000041
000042
MOVE FUNCTION CURRENT-DATE TO DATE-VARS.
3.
ACCEPT CURRENT-WEEK-DAY FROM DAY-OF-WEEK.
3. COBUCLG & COBUCLD INTRDATE 000044 DISPLAY "Date: Year " CURRENT-YEAR " Month " CURRENT-MON
000045 " Day " CURRENT-DAY "(" DT-OF-WK(CURRENT-WEEK-DAY) ")".
000047 DISPLAY "Time: Hour " CURRENT-HOUR " Minute " CURRENT-MIN
4. Return to: 000048 " Second " CURRENT-SEC "." CURRENT-MSEC.
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/ 000050 IF LOCAL-TIME NOT = 0 THEN
PGandLR/ref/rpari41e.htm 000051 DISPLAY "Time difference with Greenwich mean time for this"
1. Line continuation character ➔ 000052
000053
- "zone: "
TIME-DIF TIME-DIF-H " Hours " TIME-DIF-M " Minutes"
000054 END-IF.
5. Copy the Date and time code - and add it to INTRDATE 000055 GOBACK.
335
 Nothing to hand in

Workshop 13.4 - Add a Statistical Intrinsic Functions program to your Reusable Code Library
1. Create a new member in LEARN.REUSABLE.COBOL named: INTRSTAT
2. Return to: https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rpari41e.htm
3. Copy and paste the Statistics code into: INTRSTAT. Modify the code as shown below.
4. COBUCLG and COBUCLD the program

If you are unclear about the difference


between; Mean/Median/Range
• Check out the IBM documentation
• Google the dictionary definition

336
 Nothing to hand in

Workshop 13.5 - Add Finance Intrinsic Functions program to your Reusable Code Library
Repeat the previous process and create: INTRFINA - as shown in the screen capture below.

Note: As a COmmon Business Oriented


Language COBOL's legacy lies in back-
office data processing;
• Accounting
• Finance
• Banking
• Transaction Processing
There is extremely tight synergy between If you are unclear about the difference between;
the COBOL language - the Business PRESENT VALUE & ANNUITY
Applications it is used in and a • Check out the IBM documentation
• Google the dictionary definition
corporation's business.
One of the most important things you
can do when either applying for a job or
working at a job is to immerse yourself
in your company's vertical market space. 337
Review - Intrinsic Functions
• An intrinsic function is a function that performs a mathematical/statistical, date-manipulation, or string-
data operation. , and thereby allows you to make reference to a data item whose value is derived
automatically during execution.
• The functions can be grouped into six categories, based on the type of service performed:
• Mathematical
• Statistical
• Date/time
• Financial
• Character-handling
• General
• Date-Handling

About - general syntax/format:


https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlinffun.htm

Usage guidelines:
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/tasks/tpbeg18.htm

Intrinsic Function examples:


https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rpari41e.htm 338
COBOL Program Big Picture - Topics in Module 13
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
Intrinsic Functions INITIALIZE
Counters, Accumulators, Flags
z/OS ABENDS
Reusable Code Libraries Reference Modification, Figurative Constants • Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation •
• Concepts
Safeguards
• Resolutions

COBOL • Create Coding Standards


• Quality

Divisions • Maintain • Consistency


• Compliance
 Nothing to hand in 340

Workshop 13.5 - Add additional numeric examples to INTRNUM

Open INTRNUM in LEARN.REUSABLE.COBOL


• Add working examples of some of the COBOL Numeric Intrinsic
Functions that we did and didn’t cover in class
• For each new example either Compile/Link/Go or Debug
 These are some examples.
• The point of this exercise is to build out a collection of working
Intrinsic Function examples in your Reusable Code Library.
• Note that - even though the examples are shown here, making sure that
they work by running them is the point; i.e. why would you want to
spend time creating a reusable library of untested code?

Add this nested Intrinsic Function to the PROCEDURE DIVISION:


Compute x = Function Max((Function Sqrt(5)) 2.5 3.5)
Test the results of running it:
 Nothing to hand in * Fields for DATE-FUNCTIONS-2.
000100 01 DATE-IN.
000110 05 DATE-NUMERIC PIC 9(8).
77 BILLING-CYCLE-NBR-DAYS PIC 9(2) VALUE 0.
77 COMPUTED-DAYS-DIFF PIC S9(9) COMP.
Workshop 13.6 - Additional Date-Manipulation 000040 PROCEDURE DIVISION.
PERFORM DATE-FUNCTIONS-1.
functions in INTRDATE PERFORM DATE-FUNCTIONS-2.
GOBACK.
Copy and paste the following code into 000041
DATE-FUNCTIONS-1.
MOVE FUNCTION CURRENT-DATE TO DATE-VARS.
<TSOID>.LEARN.REUSABLE.COBOL(INTRDATE) ➔ 000042
000043*
ACCEPT CURRENT-WEEK-DAY FROM DAY-OF-WEEK.

000044 DISPLAY "Date: Year " CURRENT-YEAR " Month " CURRENT-MON
• The program uses a few new Intrinsic Functions to 000045
000046*
" Day " CURRENT-DAY "(" DT-OF-WK(CURRENT-WEEK-DAY) ")".

calculate dates - for various business purposes: 000047


000048
DISPLAY "Time: Hour " CURRENT-HOUR " Minute " CURRENT-MIN
" Second " CURRENT-SEC "." CURRENT-MSEC.
000049*
• Bill due date 000050 IF LOCAL-TIME NOT = 0 THEN
000051 DISPLAY "Time difference with Greenwich mean time for this"
• Premiums 000052- "zone: "
000053 TIME-DIF TIME-DIF-H " Hours " TIME-DIF-M " Minutes"
• Read the code - CAREFULLY 000054 END-IF.
DATE-FUNCTIONS-2.
000215* This is typical business date math. Where you need to add
• There are five parts to using the Intrinsic Functions * Days to a date, to derive a billing date, due-date, etc.
* 1. Get the Current-date (must be alphanumeric)
to do things like calculating dates MOVE FUNCTION CURRENT-DATE TO DATE-IN.
* 2. Specify the number of days to the next billing cycle
MOVE 60 TO BILLING-CYCLE-NBR-DAYS.
• Be sure that you understand the procedural logic 000250* 3. Function DATE-OF-INTEGER returns a standard date from a
000260* calculated that is the days-difference from 1/1/1601
• Be sure that you understand the data-typing necessary * 4. To calculate a date after a specific # of days add the
* specific # of days to INTEGER-OF-DATE
• After you've' cleaned up any syntax errors, run 000230
* Note that INTEGER-OF-DATE requires a PIC 9 field
COMPUTE COMPUTED-DAYS-DIFF =
INTRDATE using COBUCLG or COBUCLD FUNCTION INTEGER-OF-DATE (DATE-NUMERIC)
+ BILLING-CYCLE-NBR-DAYS.
* 5. To transform the # of days calculated to CCYYMMDD
• Change BILLING-CYCLE-NBR-DAYS 000270
* use DATE-OF-INTEGER of the above calculated date
COMPUTE DATE-NUMERIC =
FUNCTION DATE-OF-INTEGER (COMPUTED-DAYS-DIFF).
• Run the program again. DISPLAY "60 DAYS FROM TODAY: " DATE-NUMERIC. 341
Workshop 13.7a - Add more Examples and Search your Reusable Code Library
• From: https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/tasks/tpstr25.htm
• Try out these functions
• Try out several Intrinsic Function examples from:
• https://www.techagilist.com/mainframe/intrinsic-functions-cobol-reference/
• https://riptutorial.com/cobol/topic/7580/intrinsic-functions

• From: http://www.csis.ul.ie/cobol/course/RefMod.htm
• Read the text, and add some of the examples to your sample code.

342
 Nothing to hand in

Workshop 13.7b - Search your examples


• You have a new spec from a user for a report that needs to find
the largest of 4 variable values.
• Luckily you have your REUSABLE.COBOL library.
• Unfortunately, you've forgotten which program holds the MAX function

ZOD/IDz Users ➔ From Remote Systems


• Right-click on the library
• Specify: function max in the Search dialog
• Expand the twistie and double-click a line in Search Results

ISPF Users ➔ From 3.14 or 3.14


• Use SrchFor - to do the same thing

343
UNIT COBOL for z/OS - Module 14
COBOL String Handling
Functionality
• STRING
• UNSTRING
• INSPECT
• RefMod (review)
• The Intrinsic Functions for String Handling
• Coding Patterns & Examples
Articles on COBOL string handling
https://condor.depaul.edu/jpetlick/COBOL05.html
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/tasks/tpstr02.htm
344
345
COBOL Program Big Picture - Topics in Module 14
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Reusable Code Libraries Code Paragraph
• Concepts PERFORM Paragraph UNTIL <condition>
• Create OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
• Maintain INITIALIZE
Counters, Accumulators, Flags
z/OS ABENDS
• Understanding Reference Modification, Figurative Constants
• Safeguards Intrinsic Functions: Date, Math, Analytics, Text Manipulation
• Resolutions COBOL String Handling Functions: UNSTRING, STRING, INSPECT. Intrinsic Functions for PIC X data

COBOL Coding Standards


• Quality

Divisions •

Consistency
Compliance
Reusable Code - Review
• COBOL string parsing statement syntax is not entirely straightforward
• Consider creating another set of reusable code assets:
• A single program named - something like TXTPARSE
• Or separate modules, one for each statement type - some of these examples are lengthy

• Either way, you can still search for specific keywords or examples:
• But consider adding a "Tag" in COBOL Comments like you would with Slack or social media posts - to
return a subset of all the files - or something unique or meaningful
• Finally - at some point before the end of class, consider reviewing the work you've done going
back to Module 5 - culling out programs that have valuable sample code for harvesting:
• I/O routines
• Report writing logic
• Math examples
• Conditional examples
• Working COBOL program design patterns

346
Text Parsing and Manipulation - Options
There are 6 options for analyzing, splitting, joining and merging text in COBOL:
1. DATA DIVISION Group data hierarchies + MOVE statements
2. Joining data items (STRING)
3. Splitting data items (UNSTRING)
4. Converting and Evaluating data items (intrinsic functions that work with PIC X data)
5. Referring to substrings of data items (RefMod)
6. Tallying and replacing data items (INSPECT)

Each has its own pluses & minuses - and several can be used in a mix & match
approach; i.e. combining STRING with RefMods and/or Intrinsic Functions

We'll look the above options on the next few slides

347
COBOL String Handling Doc - on IBM.COM
From: https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/tasks/tpstr02.htm

…you can find examples of the specific text/string manipulation COBOL language features and
Hyper-Links to each statement

How best to
learn these?

Once
again…
learn by
coding. 348
IDENTIFICATION DIVISION.
PROGRAM-ID. STRING1.
349
DATA DIVISION.
1. DATA DIVISION + MOVE Statements WORKING-STORAGE SECTION.
01 RCD-01.
05 CUST-INFO.
Using Group/Hierarchical defined data structures you 10 CUST-NAME PIC X(15).
10 CUST-ADDR PIC X(35).
have complete control over the layout and format of your 10 CUST-PHONE.
text manipulation. 15 FILLER PIC X(1) VALUE '('.
15 AREA-CODE PIC X(3).
Further, you can combine MOVE with RefMods to tackle 15 FILLER PIC X(1) VALUE ')'.
15 PREFIX PIC X(3).
any text-sub-setting requirements: 15 FILLER PIC X(1) VALUE '-'.
15 SUFFIX PIC X(4).
• MOVE CUST-NAME(1:4) TO CUST-OUT. 05 BILL-INFO.
10 INV-NO PIC X(6).
10 INV-AMT PIC $$,$$$.99.
A typical problem: 10 AMT-PAID PIC $$,$$$.99.
10 DATE-PAID PIC X(8).
• Create a single custom-formatted report-line out of 10 BAL-DUE PIC $$,$$$.99.
10 DATE-DUE PIC X(8).
a group of discrete variable values (see below) 77 RPT-LINE PIC X(120).

COPY/PASTE this code into a new member of a library ➔


PROCEDURE DIVISION.
MOVE 'J.B. SMITH' to CUST-NAME.
Look over the code - and consider pluses/minuses of this MOVE '444 SPRING ST.,CHICAGO,IL.' TO CUST-ADDR.
approach Phone# MOVE '(212)555-1234' TO CUST-PHONE.
MOVE 'A14275' TO INV-NO.
MOVE 4736.85 TO INV-AMT.
COBUCLD it and view RPT-LINE in the Debugger MOVE 2400.00 TO AMT-PAID.
MOVE '09/22/76' TO DATE-PAID.
MOVE 2336.85 TO BAL-DUE.
MOVE '10/22/76' TO DATE-DUE.
MOVE RCD-01 TO RPT-LINE.
GOBACK.
2. STRING - Concatenate PIC X Data
STRING is used in place of multiple elementary MOVE
statements to join multiple text data fields into a single
variable
Example1: Concatenate 3 data items into 1;
STRING
VAR-1, VAR-2, VAR-3 *> Sending fields
DELIMITED BY SIZE *> Size of sending fields
INTO VAR-4 *> Receiving field
END-STRING.

Example2: Format a telephone number: PIC X(10) field https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.e


- of all numbers into a PIC X(13) output field. ntcobol.doc_4.2/PGandLR/ref/rlpsstri.htm

STRING This page contains a description of all the key phrases and
elements of the STRING statement.
'(' TEL-NBR(1:3) ') ' TEL-NBR(4:3) '-' TEL-NBR(7:4)
DELIMITED BY SIZE
INTO TEL-NBR-OUT.
END-STRING. 350
IDENTIFICATION DIVISION.
PROGRAM-ID. STRING2.
* The following example shows the STRING statement selecting and
STRING - Comprehensive Example * formatting information from a record into an output line.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 RCD-01.
05 CUST-INFO.
The IBM site: 10 CUST-NAME PIC X(15) VALUE 'J.B. SMITH'.
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGan
10 CUST-ADDR PIC X(35) VALUE
… has a comprehensive example
dLR/ref/rpstr04e.htm '444 SPRING ST.,CHICAGO,IL.'.
05 BILL-INFO.
of a STRING statement - which employs 10 INV-NO PIC X(6) VALUE 'A14275'.
many of its useful options and clauses. 10 INV-AMT PIC $$,$$$.99 VALUE '$4,736.85'.
10 AMT-PAID PIC $$,$$$.99 VALUE '$2,400.00'.
We've created a program from the code ➔ 10 DATE-PAID PIC X(8) VALUE '09/22/76'.
10 BAL-DUE PIC $$,$$$.99 VALUE '$2,336.85'.
10 DATE-DUE PIC X(8) VALUE '10/22/76'.
77 RPT-LINE PIC X(120).
77 LINE-POS PIC S9(3).
77 LINE-NO PIC 9(5) VALUE 1.
77 DEC-POINT PIC X VALUE '.'.
Please read the text on the IBM page - PROCEDURE DIVISION.
MOVE SPACES TO RPT-LINE.
which describes the details of this MOVE 4 TO LINE-POS.
particular STRING operation STRING
LINE-NO SPACE CUST-INFO INV-NO SPACE DATE-DUE SPACE
DELIMITED BY SIZE
BAL-DUE
Then COPY/PASTE this code into a new DELIMITED BY DEC-POINT
INTO RPT-LINE
member of a library - and COBUCLD it. WITH POINTER LINE-POS.
DISPLAY RPT-LINE.
GOBACK.
Question: How did 85 cents get dropped
from the results? 351
>>-UNSTRING--identifier-1--------------------------------------->
352
>--+-------------------------------------------------------------------------------------+-->

3. UNSTRING - Separating PIC X Variable Data '-DELIMITED--+----+--+-----+--+-identifier-2-+--+-----------------------------------+-'


'-BY-' '-ALL-' '-literal-1----' | .-------------------------------. |
|V ||
'---OR--+-----+--+-identifier-3-+-+-'
UNSTRING is used in place of multiple MOVE statements, to '-ALL-' '-literal-2----'
divide a (single) string into multiple substrings.
>--INTO--------------------------------------------------------->

It is similar to Reference Modification - but can be used when you don't .------------------------------------------------------------------------------------.
know what specific byte-position begins and ends the substrings V |
>----identifier-4--+---------------------------------+--+-----------------------------+-+-->
The data comes in separated by blanks '-DELIMITER--+----+--identifier-5-' '-COUNT--+----+--identifier-6-'
Examples: '-IN-' '-IN-'

>--+---------------------------------+-------------------------->
UNSTRING EMP-NAME DELIMITED BY SPACES *> Blanks separate EMP-NAME data '-+------+--POINTER--identifier-7-'
'-WITH-'
INTO FNAME, LNAME, MIDINIT *> Break EMP-NAME into FNAME, LNAME, MIDINT
>--+--------------------------------+--------------------------->
END-UNSTRING. '-TALLYING--+----+--identifier-8-'
'-IN-'

>--+------------------------------------------+----------------->
UNSTRING WS-INPUT-NAME-ADDR DELIMITED BY WS-DELIMITER1 '-+----+--OVERFLOW--imperative-statement-1-'
'-ON-'
INTO NAME-O, ADDR-O, CITY-O, STATE-O, ZIP-O
>--+-----------------------------------------------+------------>
END-UNSTRING. '-NOT--+----+--OVERFLOW--imperative-statement-2-'
'-ON-'

>--+--------------+--------------------------------------------><
UNSTRING ALL-FIELDS-1 DELIMITED BY '*' '-END-UNSTRING-'

INTO VAR-1, VAR-2, VAR-3, VAR-4, VAR-5 There are a number of UNSTRING variations - specific to what
field delimiter you're using:
TALLYING IN WS-UNSTRING-TALLY *> Count of the number of asterisks https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcob
ol.doc_4.2/PGandLR/tasks/tpstr05.htm
END-UNSTRING
IDENTIFICATION DIVISION.
PROGRAM-ID. UNSTRNG.
DATA DIVISION.
WORKING-STORAGE SECTION.

UNSTRING - Working examples 01 WS-INPUT-NAME-ADDR.


05 FILLER PIC X(060) VALUE
'Jonathan Sayles,14 Belmont Rd,Glen Rock,NJ,07452'.
01 WS-OUTPUT-UNSTR-1.
Copy and paste this program into your 05
05
NAME-O
ADDR-O
PIC X(25).
PIC X(20).
05 CITY-O PIC X(15).
REUSABLE.COBOL library 05
05
STATE-O
ZIP-O
PIC X(02).
PIC X(05).
77 WS-DELIMITER1 PIC X(01) VALUE ','.
01 EMP-RECORD.
05 FNAME PIC X(10).
05 LNAME PIC X(10).

• Debug the program - stopping on each UNSTRING


05 MIDINIT PIC X(01).
01 EMP-FULLNAME PIC X(21).
77 ALL-FIELDS-1 PIC X(20) VALUE

statement and viewing the variable values 'AB*CDEF*GHI*JKLM*NO'.


01 MISC-FIELDS.
05 VAR-1 PIC X(05).
05 VAR-2 PIC X(05).
05 VAR-3 PIC X(05).
05 VAR-4 PIC X(05).
05 VAR-5 PIC X(05).

• Modify the data values in the program that are to be 01 MISC-FIELDS.


05
05
VAR-6
VAR-7
PIC X(05) VALUE 'AB*CD'.
PIC X(05) VALUE 'EF*GH'.
UNSTRING'd. Experiment with different delimiters 05
05
VAR-8
VAR-9
PIC X(05) VALUE 'IJ*KL'.
PIC X(05) VALUE 'MN*OP'.
05 VAR-0 PIC X(05) VALUE 'QR*ST'.
77 ALL-FIELDS-2 PIC X(30).
PROCEDURE DIVISION.
MOVE 'CHESTER MCGRAW C' TO EMP-FULLNAME.
UNSTRING EMP-FULLNAME DELIMITED BY SPACES

• Add a few variables of your own - or a Group INTO FNAME, LNAME, MIDINIT
END-UNSTRING.

Hierarchy structure and experiment with UNSTRING UNSTRING WS-INPUT-NAME-ADDR DELIMITED BY WS-DELIMITER1
INTO NAME-O, ADDR-O, CITY-O, STATE-O, ZIP-O
END-UNSTRING.
UNSTRING ALL-FIELDS-1 DELIMITED BY '*'
INTO VAR-1, VAR-2, VAR-3, VAR-4, VAR-5.
STRING VAR-6, VAR-7, VAR-8, VAR-9, VAR-0
DELIMITED BY SIZE
INTO ALL-FIELDS-2.
353 GOBACK.
4. Intrinsic Functions that operate on character data
From: https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlinf.htm

….you will find all (except for the new COBOL v6) intrinsic functions well documented.

Seven intrinsic functions can be useful in attacking specific programming requirements:


• LENGTH - length of PIC X field
• MAX - highest EBCDIC value in a list
• MIN - lowest EBCDIC value in a list
• UPPER-CASE - transform all lower-case characters in a field to upper-case
• LOWER-CASE - transform all lower-case characters in a field to lower-case
• NUMVAL-C - obtain the numbers in a character (PIC X, PIC $$$) field.
• REVERSE - reverse the order of the characters in a PIC X field

You can combine the character-date Intrinsic Functions with:


• Other intrinsic Functions
• With other text-based logic and COBOL keywords 354
IDENTIFICATION DIVISION.
PROGRAM-ID. CHARFUNC. 355
DATA DIVISION.
WORKING-STORAGE SECTION.

Character (PIC X) Intrinsic Functions - Examples 01 NAME-ADDR.


05 FILLER PIC X(060) VALUE
'Jonathan Sayles, 14 Belmont Rd, Glen Rock, NJ, 07452'.

• Here's an example using the Intrinsic Functions 01 OUTPUT-FLDS.


05 WS-LENGTH-RESULT
05 WS-MAX-RESULT
PIC S9(09).
PIC X(10).
specific to character data 05 WS-MIN-RESULT
05 WS-UPPER-RESULT
PIC X(10).
PIC X(40).
05 WS-LOWER-RESULT PIC X(40).

• They're fairly simple to code - except for the last 05 WS-REVERSE-RESULT


05 WS-NUMVAL-RESULT-1
PIC X(40).
PIC 9(09).
05 WS-NUMVAL-RESULT-2 PIC 9(09).
example, where we're supposed to determine the 05 WS-NUMVAL-TEST-1
05 WS-NUMVAL-TEST-2
PIC X(10) VALUE '$9020.44'.
PIC $$9,999.99 VALUE '$9020.44'.
length of non-numeric data in a field. 77 ALL-FIELDS-1
01 MISC-FIELDS.
PIC X(40) VALUE 'AB*CDEF*GHI*JKLM*NO'.

• The FUNCTION LENGTH statement does not differentiate 05


05
ABCD
EFGH
PIC X(05) VALUE 'AB*CD'.
PIC X(05) VALUE 'EF*GH'.
05 IJKL PIC X(05) VALUE 'IJ*KL'.
between spaces and actual content. 05 MNOP PIC X(05) VALUE 'MN*OP'.
05 QRST PIC X(05) VALUE 'QR*ST'.

• The INSPECT statement returns a "TALLY" of the 05 NUM-FLD


PROCEDURE DIVISION.
PIC X(05) VALUE '1'.

MOVE FUNCTION MAX (ABCD, EFGH, IJKL, MNOP, QRST, NUM-FLD)


field length up to the first space. Allowing you to TO WS-MAX-RESULT.
MOVE FUNCTION MIN (ABCD, EFGH, IJKL, MNOP, QRST, NUM-FLD)
code logic like: TO WS-MIN-RESULT.
MOVE FUNCTION UPPER-CASE(NAME-ADDR)
TO WS-UPPER-RESULT.
MOVE FUNCTION LOWER-CASE(NAME-ADDR)
TO WS-LOWER-RESULT.
INSPECT ALL-FIELDS-1 TALLYING WS-LENGTH-RESULT MOVE FUNCTION REVERSE (FUNCTION LOWER-CASE (NAME-ADDR) )
TO WS-REVERSE-RESULT.
COMPUTE WS-NUMVAL-RESULT-1
FOR CHARACTERS BEFORE SPACE. = FUNCTION NUMVAL-C(WS-NUMVAL-TEST-1) * 2.
COMPUTE WS-NUMVAL-RESULT-2
= FUNCTION NUMVAL-C(WS-NUMVAL-TEST-2) * 2.
COMPUTE WS-LENGTH-RESULT = FUNCTION LENGTH (NAME-ADDR).
MOVE NAME-ADDR(1:WS-LENGTH-RESULT) TO NAME-ADDR-OUT. MOVE 0 TO WS-LENGTH-RESULT.
INSPECT ALL-FIELDS-1 TALLYING WS-LENGTH-RESULT
FOR CHARACTERS BEFORE SPACE.
GOBACK.
>>-INSPECT--identifier-1--TALLYING------------------------------>

.------------------------------------------------------------------------------------.

5. INSPECT |
|
V
.-------------------------------------------------------------. |
|
V
.------------------.
V |
||
||
>----identifier-2--FOR----+-CHARACTERS----+--------------+-+------------------------+-+-+-><
The INSPECT statement examines |
|
'-| phrase 1 |-' |
.----------------------------------------. |
characters or groups of characters in a |
|
|
V
.------------------. | |
V |||

data item and does the following: '-+-ALL-----+----+-identifier-3-+----+--------------+-+-+-'


'-LEADING-' '-literal-1----' '-| phrase 1 |-'

• Counts the occurrences of a specific characters in a |--+-BEFORE-+--+---------+--+-identifier-4-+--------------------|


'-AFTER--' '-INITIAL-' '-literal-2----'
data item
Format 2: INSPECT statement with REPLACING phrase
• Counts the occurrences of specific characters and >>-INSPECT--identifier-1--REPLACING----------------------------->
fills all or portions of a data item with specified
.-----------------------------------------------------------------------------------.
characters, such as spaces or zeros | .------------------. |
V V | |
• Converts all occurrences of specific characters in a >----+-CHARACTERS BY--+-identifier-5-+----+--------------+-+-------------------------+-+-><
| '-literal-3----' '-| phrase 1 |-' |
data item to user-supplied replacement characters | .--------------------------------------------------------------. |
| | .------------------. | |
| V V |||
'-+-ALL-----+----+-identifier-3-+--BY--+-identifier-5-+----+--------------+-+-+-'
+-LEADING-+ '-literal-1----' '-literal-3----' '-| phrase 1 |-'
'-FIRST---'

|--+-BEFORE-+--+---------+--+-identifier-4-+--------------------|
'-AFTER--' '-INITIAL-' '-literal-2----'

Two excellent web-pages on the use of INSPECT


• https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlpsinsp.htm
• https://www.techagilist.com/mainframe/cobol/inspect-statement-in-cobol-programs/ 356
IDENTIFICATION DIVISION.
PROGRAM-ID. INSPECT1.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 NAME-ADDR.
05 FILLER PIC X(060) VALUE
INSPECT - Example Program
PROCEDURE DIVISION.
'Jonathan Sayles, 14 Belmont Rd, Glen Rock, NJ, 07452'.
**1. Use INSPECT to determine if we have a valid Diagnostic Code
01 OUTPUT-FLDS.
** Bytes1 one => four must be either: DIAG or DXX9
05 WS-LENGTH-RESULT PIC S9(09). ** Create test data for all three scenarios
05 WS-MAX-RESULT PIC X(10). MOVE ZERO TO TALLY-1 TALLY-2.
05 WS-MIN-RESULT PIC X(10). INSPECT PRIMARY-DIAGNOSTIC-CODE
05 WS-UPPER-RESULT PIC X(40). TALLYING TALLY-1 FOR LEADING 'DIAG'
05 WS-LOWER-RESULT PIC X(40). TALLY-2 FOR LEADING 'DXX9'
05 WS-REVERSE-RESULT PIC X(40). IF TALLY-1 NOT = 1 AND TALLY-2 NOT = 1
05 WS-NUMVAL-RESULT-1 PIC 9(09). DISPLAY "*** INVALID DIAGNOSTIC-CODE-PRIMARY".
05 WS-NUMVAL-RESULT-2 PIC 9(09). **2. Debug and Monitor WS-CNTRn - reconcile with the INSPECT
05 WS-NUMVAL-TEST-1 PIC X(10) VALUE '$9020.44'. ** statement's logic
05 WS-NUMVAL-TEST-2 PIC $$9,999.99 VALUE '$9020.44'. MOVE 0 TO WS-CNTR1, WS-CNTR2, WS-CNTR3.
77 ALL-FIELDS-1 PIC X(40) VALUE 'AB*CDEF*GHI*JKLM*NO'. INSPECT WS-INSP TALLYING
77 WS-COB-CNTR PIC S9(03) VALUE +0. WS-CNTR1 FOR ALL 'E',
77 WS-COB-DATA PIC X(16) VALUE 'COBOL-IS-SO-EAZY'. WS-CNTR2 FOR LEADING 'W'
77 WS-CNTR1 PIC S9(03) VALUE +0. WS-CNTR3 FOR CHARACTERS.
77 WS-CNTR2 PIC S9(03) VALUE +0. **3. Same as #2 - except Monitor WS-COB-CNTR
77 WS-CNTR3 PIC S9(03) VALUE +0. MOVE 0 TO WS-COB-CNTR.
77 WS-DATA PIC X(11) VALUE '00ACADEMY00'. INSPECT WS-COB-DATA TALLYING WS-COB-CNTR
77 WS-INSP PIC X(11) VALUE 'WHEELAXLE'. FOR LEADING 'Z'
01 INSPECT-TALLY-FIELDS. REPLACING FIRST 'I' BY '2' AFTER INITIAL 'C'.
05 TALLY-1 PIC S9(05) COMP-3. **4. Same as #2 - except Monitor WS-CNTR2
05 TALLY-2 PIC S9(05) COMP-3. MOVE 0 TO WS-CNTR2.
01 MISC-FIELDS. INSPECT WS-DATA TALLYING WS-CNTR2
05 ABCD PIC X(05) VALUE 'AB*CD'. FOR LEADING '0' REPLACING
05 EFGH PIC X(05) VALUE 'EF*GH'. FIRST 'A' BY '2' AFTER INITIAL 'C'
05 IJKL PIC X(05) VALUE 'IJ*KL'. **5. Same as #2 - except Monitor WS-LENGTH-RESULT
05 MNOP PIC X(05) VALUE 'MN*OP'. ** Used to obtain the value of a non-space value in a field
05 QRST PIC X(05) VALUE 'QR*ST'. MOVE 0 TO WS-LENGTH-RESULT.
05 NUM-FLD PIC X(05) VALUE '1'. INSPECT ALL-FIELDS-1 TALLYING WS-LENGTH-RESULT
05 PRIMARY-DIAGNOSTIC-CODE PIC X(5). FOR CHARACTERS BEFORE SPACE.
GOBACK.
357
RefMods as String Manipulation
• Recall from Module 9 - Reference Modifications (aka RefMods) allow you to address
specific byte positions within a string:
• Move them/Assign them
• Use them as part of an Alphanumeric Intrinsic Function or STRING functions

STRING
'(' TEL-NBR(1:3) ') ' TEL-NBR(4:3) '-' TEL-NBR(7:4)
DELIMITED BY SIZE
INTO CUST-PHONE.
END-STRING.

MOVE TEL-NBR(1:3) TO AREA-CODE.


MOVE TEL-NBR(4:3) TO PREFIX.
MOVE TEL-NBR(7:4) TO SUFFIX.

358
359
COBOL Program Big Picture - Topics in Module 14
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Reusable Code Libraries Code Paragraph
• Concepts PERFORM Paragraph UNTIL <condition>
• Create OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
• Maintain INITIALIZE
Counters, Accumulators, Flags
z/OS ABENDS
• Understanding Reference Modification, Figurative Constants
• Safeguards Intrinsic Functions: Date, Math, Analytics, Text Manipulation
• Resolutions COBOL String Handling Functions: UNSTRING, STRING, INSPECT. Intrinsic Functions for PIC X data

COBOL Coding Standards


• Quality

Divisions •

Consistency
Compliance
 Nothing to hand in

Workshops - Module 14
1. Create new Reusable Code Library entries for the five new example programs in
this Module
• Study the code to understand the principles of the statements
• And study the web-page links for additional background
• COBUCLD each program
• Verify that the results line up with your expectations
• If they don't, return to the slides & web links for further study

2. Use TESTCOB to do the following; Using two or more of the alphanumeric methods
shown in this module:
• Display the last 4 digits of a fictitious social-security number
• Unformatted data records are being transmitted to your shops - and your program has to break
the each record's values out into 5 fields in Working-Storage ➔ WORKING-STORAGE

Record#1 Boris Johnson 56 UK 27589 1. FirstName X(15)


2. LastName X(20)
Record#2 Jacinda Ardern 39 NZ 12309 3. Age 9(03)
Record#3 Angela Merkel 65 DE 15201 4. State Code X(02)
5. Zip X(05) 360
UNIT COBOL for z/OS - Module 15
Introduction to COBOL Table Handling
• The OCCURS clause
• Differences between a subscript and table index
• Create a one-dimension table, by redefining values in
Working-Storage
• Initialize and load data in a COBOL table
• Refer to specific table row/field table occurrences in the
Procedure Division

Additional learning links:


https://condor.depaul.edu/jpetlick/COBOL09.html
http://www.pgrocer.net/Cis51/searchnt.html
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/igy3pg50.pdf
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/tasks/tptbl02.htm
361
362
COBOL Program Big Picture - Topics in Module 15
Identification Name the executable Program-ID. TABLES00.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
COBOL Table Handling • Inline PERFORM and PERFORM VARYING
• Concepts OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
• Loading INITIALIZE
z/OS ABENDS
Counters, Accumulators, Flags •
• Accessing Reference Modification, Figurative Constants •
Understanding
Safeguards
• Indexed by/Subscript Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Resolutions
• Single-Dim OCCURS COBOL String Handling Functions: UNSTRING, STRING
COBOL Reusable Code Libraries
• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
COBOL Tables – Overview and concepts
Because business-data-processing is frequently table-driven, COBOL supports many different
types of table structures and processing options:
1. Single occurrence COBOL field tables - Fixed-length Structures (Group) field tables – the most common format
2. Variable-length tables – where the number of table occurrences is not known until run-time
3. Multi-dimension tables - think data stored by: Year ➔ Month ➔ Week ➔ Day … a 4-dim table.

Two common reasons for utilizing tables include:


1. To simplify repetitive processing patterns and organize related repetitive data
2. To handle design issues that require dynamic, run-time-populated and/or dynamically-sized data structures

Example: You want to


analyze quarterly pricing data …or…
– going back n years.

Your options include:


• Separate COBOL Variables
• Static Table loaded from a file
• Dynamically-sized COBOL
Table - Populated from a file
364
Visualizing a One-Dim COBOL Table in Byte Storage

01 EMPLOYEE-RECORD

05 EMPLOYEE-NAME 05 EMPLOYEE-PHONES

15 PHONE(1) 15 PHONE(2) 15 PHONE(3)

ROBERT K KAHN (201)652-2438(919)123-4324(675)444-5534


Bytes

00000000001111111112222222222333333333344444444445555555555
12345678901234567890123456789012345678901234567890123456789
365

COBOL Single Dimension (One OCCURS Clause)


.

OCCURS n definitions are simply a different way of defining the bytes within a record. And many (many)
business data models consist of tabular data - i.e. Excel, DB2, etc.
In the above example, the EMPLOYEE-RECORD includes an OCCURS 3 table of phone numbers:
• MOVE EMPLOYEE-RECORD ➔ The entire 01-record, 59 bytes can be moved as a unit
• MOVE EMPLOYEE-NAME ➔ The employee-name value, the first 20 bytes can be moved as an element
• MOVE EMPLOYEE-PHONES ➔ The 3 occurrences of phone numbers 39 bytes can be moved as a unit
• MOVE PHONE(1) … or PHONE(2) … or PHONE(3) ➔ A single occurrence of phone number (13 bytes) can be moved
COBOL Tables – Considerations
• COBOL tables are one(1)-based in subscripts - not zero-based:
• From the prior slide: MOVE PHONE(1) TO PHONE-OUT moves: (201) 652-2438 to PHONE-OUT.
• The value within the parenthesis must be > 0 and <= the table's OCCURS limit
• Attempts to access COBOL table data beyond its definition results in a run-time error: S0C4
• MOVE 0 TO SUB.

• MOVE PHONE(SUB) TO PHONE-OUT S0C4

• Table rows are referred to as "occurrences"

• Tables can have multiple dimensions - OCCURS within OCCURS


• DECADE-EXPENSES OCCURS 5 TIMES.
• YEAR-EXPENSES OCCURS 10 TIMES.
• MONTH-EXPENSES OCCURS 12 TIMES PIC 9(9)V99.
• MOVE MONTH-EXPENSES(2, 1, 4) TO EXPENSE-DATA-OUT (Move Decade/Year/Month data ➔ DEXPENSE-DATA-OUT)
• COBOL allows up to seven levels of table OCCURS nesting.
• But in most programs, COBOL tables > three levels deep are rare

You can use special INDEX datatypes to reference table row data, or you can use subscripts – which are
numeric integer variables defined in WORKING-STORAGE. 366
Coding Pattern for COBOL Tables
There are three basic COBOL coding categories and
options to learn about:
1.Define the tables:
• Often - but not always in WORKING-STORAGE
• Specific syntax examples follow on the next slides

2.Load or Initialize COBOL tables:


• From files or databases
• Programmatically from within the PROCEDURE DIVISION

3. Process COBOL tables:


• Using the values procedurally in business logic computations and data manipulation
• Searching the tables for matching values in the PROCEDURE DIVISION – upcoming section

367
Define Simple (One-Dimension) Table – COBOL Syntax
Format:
• Give the table a group name, then define a subordinate item (the table element) to be repeated n times.
01 TABLE-GROUP-NAME.
05 ELEMENT-NAME OCCURS N TIMES. Table element OCCURS definition
10 ELEMENTARY-LEVEL-VARIABLES OF THE Table Element

• In the example above


• TABLE-GROUP-NAME is the name of an alphanumeric group item
• The table element definition which includes the OCCURS clause - is subordinate to the group item that contains the table.
• There would (typically) be multiple subordinate items - fields at level 10 or higher - within the 05 OCCURS

• Optional clause: INDEXED BY <IDXNAME>.


• If you declare a COBOL table and include the INDEXED BY clause, the COBOL compiler will create an internal subscript used to
reference table occurrences
• Using INDEXED BY can be substantially more efficient than using subscripts – particularly for large tables (> 100 rows)

01 TABLE-GROUP-NAME.
05 ELEMENT-NAME OCCURS N TIMES INDEXED BY TBL-IDX.
10 ELEMENTARY-LEVEL-VARIABLES OF THE TABLE ELEMENT 368
One-Dim COBOL Table Definitions – Examples
WORKING-STORAGE SECTION. WORKING-STORAGE SECTION.
01 WEEK-DAY-VALUES.
01 Territory-Totals. 05 FILLER PIC X(09) VALUE "SUNDAY ".
05 Territory-Sales-Totals PIC 9(7)V99 05 FILLER PIC X(09) VALUE "MONDAY ".
OCCURS 4 INDEXED BY TERR-IDX. 05 FILLER PIC X(09) VALUE "TUESDAY ".
05 FILLER PIC X(09) VALUE "WEDNESDAY".
01 Item-Table. 05 FILLER PIC X(09) VALUE "THURSDAY ".
05 Items-Group OCCURS 30. 05 FILLER PIC X(09) VALUE "FRIDAY ".
10 Item-Number PIC 99V99 COMP. 05 FILLER PIC X(09) VALUE "SATUDAY ".
10 Item-Name PIC X(30).
10 Item-Price PIC 9(05)V99 COMP-3. 01 Weekday-Table REDEFINES WEEK-DAY-VALUES.
10 Item-Tax PIC V99. 05 WS-Day-of-Week PIC X(09) OCCURS 7 TIMES.


PROCEDURE DIVISION.
Example of one-dimension COBOL table
INITIALIZE Item-Table, Territory-Totals. loaded by redefining hard-coded W-S values
SET TERR-IDX TO 1.

• The above tables will be loaded from an external file


• Territory-Sales-Totals is declared with an index (TERR-IDX)
defined by COBOL
• Item-Table access requires that you define a subscript

369
Load Tables using Initialize – Syntax
You can load a table:
1. Programmatically - from a screen, file or database) – Note that this is the most common pattern
2. REDEFINE hard-coded field values with an OCCURS (previous slides)
3. Using Initialize – see example below
4. Using the VALUE clause on elementary field definitions (rarely used).

Initialize examples:
• To move the value 3 into each of the elementary numeric data items in a table called TABLE-ONE, shown below, you can code
the following statement:

INITIALIZE TABLE-ONE REPLACING NUMERIC DATA BY 3.

• To move the character 'X' into each of the elementary fields in TABLE-ONE, you can code the following statement:
INITIALIZE TABLE-ONE REPLACING ALPHANUMERIC DATA BY "X".

• When you use the INITIALIZE statement to initialize a table, the table is processed as a group item (that is, with group
semantics); elementary data items within the group are recognized and processed.
• You can use the REPLACING phrase of the INITIALIZE statement, to initialize elementary field types with a specific value
• ALPHABETIC, DBCS, ALPHANUMERIC-EDITED, NATIONAL-EDITED, NUMERIC-EDITED
Variable-Length Tables are covered in Module 17
• The INITIALIZE statement can not assign values to a variable-length table
• A table that was defined using OCCURS DEPENDING ON 370
Load Tables From an Input File - Code Pattern Example
FILE-CONTROL.
• Most COBOL tables are loaded with data from an input file. SELECT INPUT-FILE ASSIGN TO EMPROJ.
DATA DIVISION.
• You READ and load (MOVE) the values into the table before FILE SECTION.
FD INPUT-FILE RECORDING MODE F.
your program refers to the table 01 EMP-PROJECT-TABLE-I.
05 EMP-PROJECT-I PIC X(4).
Use PERFORM VARYING IDX … or ... 05 EMP-NAME-I PIC X(15).
05 FILLER PIC X(61).
PERFORM VARYING SUB to populate table occurrences WORKING-STORAGE SECTION.
77 PROJECT-SUB PIC S9(4) COMP.
• When reading data to load your table, test to make sure that the 77 TABLE-MAX PIC S9(4) COMP VALUE 20.
77 SW-END-OF-FILE PIC X(01) VALUE SPACES.
data does not exceed the space allocated for the table (defined 88 END-OF-FILE VALUE 'Y'.
by the number of OCCURS) 01 EMP-PROJECT-TABLE. *> Define the table
05 EMP-PROJECT-ITEM OCCURS 20 TIMES.
• A good programming practices is to use a named variable value 10 EMP-PROJECT PIC X(4).
10 EMP-NAME PIC X(15).
rather than a literal for the OCCURS count. PROCEDURE DIVISION.
• If you end up making the table bigger, you need to change only one ...
OPEN INPUT INPUT-FILE.
value, instead of all references to a literal READ INPUT-FILE
AT END MOVE 'Y' TO SW-END-OF-FILE.
PERFORM VARYING PROJECT-SUB FROM 1 BY 1
What's the deal with Perform Varying? UNTIL PROJECT-SUB = TABLE-MAX *> Load the table
OR END-OF-FILE
MOVE EMP-PROJECT-I TO EMP-PROJECT (PROJECT-SUB)
This optional PERFORM statement clause increments s a subscript or MOVE EMP-NAME-I TO EMP-NAME (PROJECT-SUB)
(or index): READ INPUT-FILE
AT END MOVE 'Y' TO SW-END-OF-FILE
• Starting at the FROM value END-READ
• Up - or down - the BY value END-PERFORM.
• Ending when the UNTIL condition tests true GOBACK.

You will use the PERFORM VARYING pattern quite a bit – in external table loading and processing 371
Cracking the Code - Inline Perform
• Not only did the PERFORM VARYING
statement in the previous example
increment PROJECT-SUB - UNTIL some
condition, the PERFORM statement itself
did not branch to a paragraph…all of the
DO/Until/Iterative logic was contained
between PERFORM & END-PERFORM.

This option is called an "Inline Perform" and is


an alternative to performing a paragraph.

• You would typically use an Inline Perform to loop thru a small chunk of logic … a number of statements that
is too small to merit its own separate paragraph:
PERFORM VARYING IDX UNTIL IDX > 100
MOVE 10 TO TABLE-OCC(IDX)
DISPLAY TABLE-OCC(IDX), IDX
END-PERFORM.
372
373
Referencing Values in a One-Dimension COBOL Table
• You access an array occurrence with a numbered subscript or a defined table index between 1
and the max occurrence in the table
• PHONE(1) refers to the first phone number in the record
Record#1
Record#2
Record#3
Phone(1) occurrences in
each Employee-Record

• You can use a literal or a variable as a subscript into the table:


• Variables are used far more frequently in business program
• The variable must be declared as a PIC 9 integer
• If you have defined the COBOL table with INDEXED BY <indexName> - you will use the indexName as the subscript

• You can refer to a table(sub) value - or modify a table(sub) value


• DISPLAY PHONE(sub)
• MOVE '(323)555-2424' TO PHONE(sub)

• If the data in the table is numeric you can do arithmetic


• COMPUTE YEAR-TOTALS = QUARTER(1) + QUARTER(2) + QUARTER(3) + QUARTER(4).
COBOL Language Rules for Subscripts and Indexes
Each subscript/index must be either a:
• Positive integer or a variable which represents a positive integer, or a simple expression which evaluates to a
positive integer: TABLE-ELEMENT(SUB + 1).
• Subscripts must be defined in WORKING-STORAGE. Indexes are defined on the table declaration.
• Subscripts and indexes must be enclosed in parentheses/brackets.
• Subscripts/Indexes can be manipulated by arithmetic statements and PERFORM VARYING
• Indexes are manipulated using the COBOL SET keyword:
• SET QTY-IDX TO 1. SET QTY-IDX UP BY 1. SET QTY-IDX DOWN BY 1.
• Both subscripts and indexes can be manipulated in PERFORM …. VARYING statements:
• Inline PERFORM
• PERFORM EDIT-PARA VARYING TBL-IDX FROM 1 BY 1 UNTIL TBL-IDX > TBL-MAX

Important note: Table processing on tables defined with Indexes can be magnitudes-of-order more efficient
than subscripts. In small tables this may not matter, but in tables > 100 occurrences always try to use a table
index.
374
Review - COBOL Tables – Under the Debug Microscope
Like most programming languages, COBOL allows you to group contiguous elementary variables of identical type
and size into internal program tables.

COBOL program that processes the EMPLOYEE FILE EMPLOYEE FILE


Employee-name Three phone numbers in each record

EMPFILE Records
COBOL Table Declaration
EMPLOYEE-NAME

Three phone numbers

First EMPLOYEE FILE Table record read/Debug 375


376
COBOL Program Big Picture - Topics in Module 15
Identification Name the executable Program-ID. TABLES00.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
COBOL Table Handling • Inline PERFORM and PERFORM VARYING
• Concepts OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
• Loading INITIALIZE
z/OS ABENDS
Counters, Accumulators, Flags •
• Accessing Reference Modification, Figurative Constants •
Understanding
Safeguards
• Indexed by/Subscript Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Resolutions
• Single-Dim OCCURS COBOL String Handling Functions: UNSTRING, STRING
COBOL Reusable Code Libraries
• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
 Nothing to hand in 377

Workshop 15.1 - Study and Debug TABLES00


• Copy DDS0001.LEARN.COBOL(TABLES00) to your TSO-ID and copy the file:
DDS0001.LEARN.EMPFILE to your TSO-ID
• If you are using your own TSO/ISPF system I will send you the program and input file
• Look carefully at the three areas of COBOL table handling code discussed in this
Module:
1. Table definition
2. Loading the table -- N/A in this use case
3. Processing table information using a PERFORM VARYING

• Debug the program:


• You will need a new //EMPFILE DD card in your COBUCLD JCL
• If you are using your own ISPF system:
• I will send the contents of EMPFILE to you via eMail.
• Allocate EMPFILE as an: 80 Byte, Sequential Data Set
• Copy the data sent to your TSOID.LEARN.EMPFILE 377
378

Workshop 15.2 - Finish Coding TABLES01


• Copy DDS0001.LEARN.COBOL(TABLES01) to your TSO-ID and copy the file: DDS0001.LEARN.EMP1.PROJ to your TSO-ID
• If you are using your own TSO/ISPF system I will send you the program and input file
• Again, look carefully at the 3 areas of COBOL table handling code

• Debug the program:


• You will need a new //EMPROJ DD card in your COBUCLD JCL
• If you are using your own ISPF system:
• Allocate EMPFILE as an: 80 Byte, Sequential Data Set
• Copy the data records emailed to your new file: TSOID.LEARN.EMP.PROJ

• Finish coding paragraphs: 100 ➔ 500 Using the comments embedded in the program source
• Use PERFORM VARYING logic to iterate over the table.
• Use IF statements to Locate and compute the values ➔
400-TOTAL-PROJ-EXPENSE.
• Create a W-S field (A111-TOT).
• Loop thru the table. For Project A111 - Add (NBR-DAYS * PER-DAY-BILLING) + (NBR-OT * HOUR-OT-RATE) to A111-TOT.

500-TOTAL-ALL-PROJECTS-EXPENSE .
Is this a valid computation for
• Create a W-S field (COST-CALC). calculating all expenses?
• Use this computation to calc all expenses ➔ That's OK - your program is not
going into production
• Move COST-CALC to a numeric-edited field
 Nothing to hand in WORKING-STORAGE SECTION.
01 WEEK-DAY-VALUES.
Optional Workshop 15.3 05 FILLER PIC X(09)
05 FILLER PIC X(09)
VALUE
VALUE
"SUNDAY
"MONDAY
".
".
05 FILLER PIC X(09) VALUE "TUESDAY ".
Create a new Table-Handling program: 05 FILLER PIC X(09) VALUE "WEDNESDAY".
05 FILLER PIC X(09) VALUE "THURSDAY ".
1. Copy TABLES00 into new COBOL member 05 FILLER PIC X(09) VALUE "FRIDAY ".
05 FILLER PIC X(09) VALUE "SATUDAY ".
2. Copy the code shown here into your new program ➔
01 Weekday-Table REDEFINES WEEK-DAY-VALUES.
• As is
05 WS-Day-of-Week PIC X(09) OCCURS 7 TIMES.
3. Write a PROCEDURE DIVISION Paragraph that DISPLAYS Note: This code will be used in the course Final Exam
each day of the week from WEEKDAY-TABLE using a
subscripted table occurrence and a PERFORM
VARYING statement
4. Repeat #3 but utilize a COBOL table index definition • Create a W-S field: TBL-SRCH PIC X(09)

• Add the INDEXED BY clause to WS-DAY-OF-WEEK • In the paragraph:


• MOVE 'TUESDAY' TO TBL-SRCH
5. Add new paragraph with an inline perform • Code an inline PERFORM that loops
that loops thru the table and Displays the through your table, comparing
message and table occurrence as shown here: WS-DAY-OF-WEEK(idx) TO TBL-SRCH
• When found, display the following
message: Tuesday is day idx of the week
379
Optional Workshop 15.4 01 SALES-TABLE.

Create a Sales Report program: 05 REGION OCCURS 4 TIMES.


10 Q1-SALES PIC 9(5)V99 VALUE ZEROES.
• Using this table definition ➔
create your own test data 10 Q2-SALES PIC 9(5)V99 VALUE ZEROES.
• Four rows 10 Q3-SALES PIC 9(5)V99 VALUE ZEROES.
• Within each row four sets of sales data
10 Q4-SALES PIC 9(5)V99 VALUE ZEROES.
• Load the table with your own custom data.
• Create a report that summarizes sales data from the SALES-TABLE:
• All Q1-SALES for all Regions
• Compute HIGHEST-SALES-OUT = FUNCTION SUM(REGION(ALL)).
• Highest & Lowest Q1-SALES for all Regions:
• Compute HIGHEST-SALES-OUT = FUNCTION MAX(REGION(ALL)).
• By Region:
• Breakout of all Sales for each Region
• Use PERFORM VARYING
• All sales in the table (all Quarters and all Regions)
compute SALES-OUT = function SUM (Q1-SALES(ALL) ) + function SUM (Q2-SALES(ALL) ) +
function SUM (Q3-SALES(ALL) ) + function SUM (Q4-SALES(ALL) ).

380
 Nothing to hand in

Optional Workshop(s) 15.5 - PERFORM VARYING Table Searches


Study a little SQL: https://www.w3schools.com/sql/sql_where.asp - Spend 20-30 minutes on the SELECT/FROM/WHERE statements (If you
already know SQL - don't bother). Back to COBOL. For years your company has resisted moving their data store to DB2.  And instead have
asked developers to code SELECT/FROM/WHERE using table handling. So in order to do COBOL work; Enhance TABLES01 to answer the following
questions (You will need to study the data file associated with TABLES01 in the JCL, in order to test your work)
1. How many Programmer/Analysts work on project 'A111' and are from NC?
2. Is the COBOL alphanumeric comparison case sensitive? If it is, how can you make a search not case-sensitive?
3. Who's the highest paid Programmer/Analyst?
4. Who is the DBA (Database Admin) for project 'C222'?
5. List all of the employees who work on a project where the name ends in '333' - eg. A333, B333, D333, etc.
6. Can Kandace Springs program in COBOL?

Optional/Advanced/Challenge Workshop:
1. Use a RefMod and String/Unstring statement to create the following name output for the report:
• M. Hudak, A. Gupta, I. Krugs

2. In SQL WHERE clauses there are three common operators: BETWEEN, IN & LIKE. Create a new paragraph for each of these, and
emulate their behavior with COBOL tables and PERFORM VARYING:
• BETWEEN/Range Conditional, IN/OR conditional, LIKE/RefMod 381
UNIT COBOL for z/OS - Module 16

Intermediate Table Handling


• SEARCH
• SEARCH ALL

Additional content on SEARCH and SEARCH ALL:


• https://www.ibm.com/support/knowledgecenter/SS6SG3_6.3.0/pg/tasks/tptbl35.html
• https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/ref/rlpssear.htm
• https://www.tutorialbrain.com/mainframe/cobol_search_and_search_all/
• https://www.techagilist.com/mainframe/cobol/search-vs-search-all/ 382
383
COBOL Program Big Picture - Topics in Module 16
Identification Name the executable Program-ID. TABLES03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure COBOL Table Handling
DISPLAY, GOBACK • Concepts
Code Paragraph • Loading
PERFORM Paragraph UNTIL <condition> • Accessing
COBOL Table Handling • Inline PERFORM and PERFORM VARYING • Indexed by/Subscript
• SEARCH • Single-Dim OCCURS
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
• SEARCH ALL INITIALIZE
z/OS ABENDS
Counters, Accumulators, Flags • Understanding
Reference Modification, Figurative Constants • Safeguards
Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Resolutions
COBOL String Handling Functions: UNSTRING, STRING
COBOL Reusable Code Libraries
• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
Searching COBOL Tables
There are three ways to search through COBOL tables for values you want to find:
1. Perform Varying
• You've already seen this – essentially you manipulate an index or subscript within an inline PERFORM, or
paragraph PERFORM
2. Sequential SEARCH
• COBOL has a reserved word (SEARCH) that automatically will search through a table starting from a pre-
determined element, and going until:
• SEARCH finds a match
• Or the code hits an end-of-table condition
3. Binary SEARCH ALL
• COBOL also has a reserved phrase: SEARCH ALL that does a binary search through a COBOL table, until:
• SEARCH ALL finds a match
• The code hits an end-of table condition

• Both the Sequential and Binary searches require you to use a table with an INDEXED BY ….. Clause
• In addition, SEARCH ALL requires the table to be sorted on the key field you're searching with
• All three table search patterns can accomplish the same result – finding data in table, but they differ in
terms of: 1. Syntax, 2. Data pre-req's, 3. Run-time performance (table-search efficiency) 384
77 State-Search-Data PIC X(20). 385
01 States-Table-Seq.
05 State-Name OCCURS 50 TIMES Searching COBOL Tables
INDEXED BY St-Idx-Seq PIC X(20). Side-by-Side Syntax View
01 States-Table-Bin.
05 State-Name-Bin OCCURS 50 TIMES
Ascending key is State-Name-Bin
INDEXED BY St-Idx-Bin PIC X(20).

State Table Data


Procedure Division.
*** Option 1. PERFORM VARYING ****
PERFORM VARYING St-idx-Seq from 1 by 1 Until St-idx > 50
If State-Search-Data = State-Name (St-Idx-Seq)

*** Option 2. SEQUENTIAL SEARCH ****


Set St-Idx-Seq to 1.
SEARCH State-Name Varying St-Idx-Seq
At End take not found action…
When State-Search-Data = State-Name(St-Idx-Seq)
take found action…

*** Option 3. BINARY SEARCH ALL ****


SEARCH ALL States-Name-Bin
At End take not found action…
When State-Name-Bin(St-Idx-Bin) = State-Search-Data
take found action…
386
SEARCH - Linear Search Syntax and Coding Pattern Alabama
The SEARCH statement performs a sequential search beginning at the current index setting, progressing Alaska
typically to the end of the table or until the WHEN clause is satisfied. To modify the index setting before American Samoa
searching, use the SET statement. Arizona
Arkansas

State Table Data


California
Colorado
Connecticut
Delaware
District of
Columbia

Additional considerations: Florida


Georgia
• Conditional Expressions in the WHEN phrase are evaluated in the order in which they appear. Guam
Any COBOL Conditional Expression can be used Hawaii
Idaho
• If none of the conditions is satisfied, the index is increased to correspond to the next table element, and Illinois
the WHEN conditions are evaluated again. Indiana

• If one of the WHEN conditions is satisfied, the search ends. Iowa


Kansas
• The index remains pointing to the table element that satisfied the condition.
Kentucky

• If the entire table has been searched and no conditions were met, the AT END imperative statement is Louisiana
executed if there is one. If you did not code AT END, control passes to the next statement. Maine
Maryland
• Only one WHEN statement is permitted per SEARCH statement. Massachusetts
Michigan
• VARYING index is optional (SEARCH will use the table-index defined: INDEXED BY ….

)
387
Sequential SEARCH – Example
01 SALES-TAX.

05 FILLER PIC X(21) VALUE '280000005463968869950'.

05 FILLER PIC X(21) VALUE '329650006543603457350'.


Static/Redefined Table
05 FILLER PIC X(21) VALUE '557450007573101219150'.

05 FILLER PIC X(21) VALUE '726900008765280036375'.


Five rows
05 FILLER PIC X(21) VALUE '902650005431500000001'.

01 SALES-TAX-TABLE REDEFINES SALES-TAX.

05 SALES-TAX-ITEM OCCURS 5 TIMES INDEXED BY TX-IDX. INDEXED BY TX-IDX


10 SALES-TAX-L-RANGE PIC 9(6)V9(2).

10 SALES-TAX-RATE PIC V9(6).

10 SALES-TAX-H-RANGE PIC 9(5)V9(2).

PROCEDURE DIVISION.

SET TX-IDX TO 1.
• SET statement
SEARCH SALES-TAX-ITEM
• Sequential Search
AT END PERFORM 700-INVALID-TAX-ID

WHEN SALES-TAX-L-RANGE (TX-IDX) > IN-ITEM-TAX-ID • Found and Not-found


PERFORM 200-COMPUTE-WITHOLDING-TOTALS. conditional branches
388
Binary Table Search – Syntax and Coding Pattern Alabama
The SEARCH ALL statement performs a Binary search - which begins in the middle of Alaska
the table - then splits the remaining rows to search in half and continues to both search American Samoa

and split until either not found or end-of-table. Arizona


Arkansas
California
Colorado

State Table Data


Connecticut
Delaware
District of
Columbia
Florida

Other considerations: Georgia


Guam
• To use the SEARCH ALL statement to search a table: Hawaii
• The table must specify the ASCENDING or DESCENDING KEY phrases of the OCCURS clause, or both Idaho
Illinois
• The table must be ordered on the key or keys that are specified in the ASCENDING and DESCENDING KEY phrases.
Indiana
• In the WHEN phrase of the SEARCH ALL statement, you can test any key that is named in the ASCENDING or Iowa
DESCENDING KEY phrases. Kansas
Kentucky
• The test must be an equal-to condition, and the WHEN phrase must specify either a key (subscripted by the first Louisiana
index-name associated with the table) or a condition-name (88-level) that is associated with the key. Maine

• You do not need to set the index before you begin. The index is always the one that is associated with the first Maryland
Massachusetts
index-name in the OCCURS clause.
Michigan
• Table keys and WHEN comparison fields must be data-type compatible: PIC X ➔ PIC X (or) PIC 9 ➔ PIC 9 …
Binary Table and Search using SEARCH ALL – Annotated Example
01 STATES-ABBREV-TABLE. Table Group Definition

05 STATE-ABBREV-TBL OCCURS 50 TIMES Table (OCCURS clause) - The object of the SEARCH ALL statement
ASCENDING KEY IS ST-ABBREV-DAT ASCENDING KEY - Search-able variable - that the table is expected to be sorted on
INDEXED BY ST-ABBREV-IDX. Internal COBOL Index for table access
10 ST-ABBREV-DAT PIC X(02). Searchable variable - The variable referenced by ASCENDING KEY
10 FILLER PIC X(78).
400-STATE-BINARY-SEARCH-ALL. No need to "SET" the index for SEARCH ALL
MOVE 'KS' TO STATE-ABBREV-SEARCH. STATE-ABBREV-SEARCH is a PIC X WORKING-STORAGE variable referenced in WHEN

SEARCH ALL STATE-ABBREV-TBL SEARCH ALL - References the 05-variable that OCCURS 50 TIMES
AT END
DISPLAY 'NOT A STATE'
WHEN can ONLY reference the table variable(s) specified in the ASCENDING KEY
WHEN ST-ABBREV-DAT(ST-ABBREV-IDX) =
clause - and the only conditional comparison operator is equals "="
STATE-ABBREV-SEARCH
SET ST-NAME-IDX TO ST-ABBREV-IDX Can SET other indexes to the value of any COBOL table index
DISPLAY 'FOUND ' ST-NAME-DAT(ST-NAME-IDX).
389
390
Binary SEARCH ALL – Example
01 SALES-TAX.

05 FILLER PIC X(18) VALUE '280000003968869950'.


Static/Redefined Indexed Table - Five rows
05 FILLER PIC X(18) VALUE '329650003603457350'.
Ordered in ascending sequence by
05 FILLER PIC X(18) VALUE '557450003101219150'.
SALES-TAX-L-RANGE
05 FILLER PIC X(18) VALUE '726900002800363750'. • Matching the ASCENDING KEY IS clause
05 FILLER PIC X(18) VALUE '902650001500000000'.
• Which must be a subordinate variable to the
OCCURS data item
01 SALES-TAX-TABLE REDEFINES SALES-TAX.

05 SALES-TAX-ITEM OCCURS 5 TIMES Note that the table could be sorted in


DESCENDING order…
ASCENDING KEY IS SALES-TAX-L-RANGE INDEXED BY TX-IDX.

10 SALES-TAX-L-RANGE PIC 9(6)V9(2).

10 SALES-TAX-RATE PIC V9(3).

10 SALES-TAX-H-RANGE PIC 9(5)V9(2).

PROCEDURE DIVISION.
• NO SET statement
SEARCH ALL SALES-TAX-ITEM
• SEARCH ALL
AT END PERFORM 700-INVALID-TAX-ID • References the OCCURS table var
WHEN SALES-TAX-L-RANGE (TX-IDX) = IN-ITEM-TAX-ID • WHEN references the ASCENDING
PERFORM 200-COMPUTE-WITH-TAX-TOTALS.
KEY IS variable
• Found / Not-found conditional branches
SEARCH vs. SEARCH ALL vs. PERFORM VARYING - Considerations
SEARCH ALL Of the three table search options:
Is very fast – for large tables, compared to Perform Varying and 1. PERFORM loops are the slowest option
sequential SEARCH
2. SEARCH ALL (binary) is fastest, but usually only for tables >
100 elements
It divides the table into two halves and determines which half
does not contain the value in the WHEN clause. 3. SEARCH (sequentially) is faster than SEARCH ALL for small
tables, and considerably slower for very large tables
The half that could contain the WHEN clause value is then split into A Perform loop (especially an inline one) may be FASTER than some
halves, of which one is excluded. Etc. until the value is found in the SEARCH operations - depending on the data.
table ---- or not.
Always use a COMP field or table index.
The not found condition happens when a split table part is to small SEARCH ALL beats SEARCH (sequential) but SEARCH ALL requires
to be re-split – or it consist of just one value, and that value is not your table to be sorted before the statement is executed
the one you are searching for. • If your program's table "input" isn't sorted, consider the overhead
to sort it before deciding between a sequential SEARCH or a binary
With just 10 comparisons it is possible to find a value in an array in SEARCH ALL.
(give or take) ~1,000 values – and it's conceivable that it could take • If you search a large table many times, then doing the sort is
< 10 comparisons. probably a good idea. IBM provides a "nifty" way to do this - if you
aren't familiar with the technique. See COBOL SORT keyword
Contrast this with SEARCH – which could require 1,000 SEARCH ALL only permits WHEN conditions that test for equality
comparisons.
Additional research:
Note that with SEARCH ALL it is your responsibility to make sure
• Check out: Http://publibfp.boulder.ibm.com/cgi-bin/bookmgr/BOOKS/igy3pg40/1.12.10.2
that the contents of the table is sorted as defined in ASCENDING or
DESCENDING KEY – part of the OCCURS clause definition.
391
392
COBOL Program Big Picture - Topics in Module 16
Identification Name the executable Program-ID. TABLES03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure COBOL Table Handling
DISPLAY, GOBACK • Concepts
Code Paragraph • Loading
PERFORM Paragraph UNTIL <condition> • Accessing
COBOL Table Handling • Inline PERFORM and PERFORM VARYING • Indexed by/Subscript
• SEARCH • Single-Dim OCCURS
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
• SEARCH ALL INITIALIZE
z/OS ABENDS
Counters, Accumulators, Flags •
• SORT Reference Modification, Figurative Constants •
Understanding
Safeguards
Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Resolutions
COBOL String Handling Functions: UNSTRING, STRING
COBOL Reusable Code Libraries
• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
 Nothing to hand in 393

Workshop 16.0
1. COBUCLD the program TABLES03
This program is a table processing sample that you can TABLES03
use as a model for other workshops in this module. SEARCH/ALL Example
From the code note the syntax and structure of the
following:
• Multiple table declarations
• Tables are loaded from external files
• Both Sequential SEARCH and Binary SEARCH ALL
code samples are in the PROCEDURE DIVISION
• Note the number of Debug Steps (F5s) needed to find 'KS' using the binary
search versus the sequential search
• If you test with 'NY' as the SEARCH argument, you'll find that there's a problem.
What is the problem? What are some ways to fix it?
 Nothing to hand in

Example 1 - Linear Search


Optional Workshops 16.1
1. Create two working programs out of the Example slide
SEARCH code from earlier in this module (these slides)➔
• Copy the code to your ID:
• Code which I will email you
• Create one new program for each example:
• Note that in Example 2 change the
PERFORM statements to COBOL DISPLAYs
• Be mindful of the 3 areas of table handling (previous module)
• Add comments to the program - so that you can

Example 2 - Binary Search


easily reuse the code in upcoming workshops
• Debug your program:
• You will NOT need any new //DD cards

2. TABLES01 Rewrite:
• Replace the PERFORM VARYING code in the TABLES01
program with linear (SEARCH) and binary (SEARCH ALL)
394
COBOL logic
Optional Workshop 16.2a - Maintenance on Editing/Validation Program
HOSPEDIT is part of a larger Hospital/Insurance application. HOSPEDIT needs work:
• New Valid Insurance Types must be added
• The output report is hideous: The report looks awful, and there are errors in the totals and counters fields
• RUN and Debug HOSPEDIT - then look at the resulting output data - if you doubt this

1. Create an external table file composed only of the following values in 5 separate rows:
HMO, PRI, PPO, AFF, MED
• Define the table declaration in WORKING-STORAGE
• You'll need to spend time coding in the ENVIRONMENT DIVISION and DATA DIVSION

• Use a COBOL Search, in place of the current 88-level for VALID-INS-TYPE in the validation routine
• Use the Patient's input file INS-TYPE value as the search argument against your new table

Terms used in the program:


• PATIENT-TOTAL-AMT - The running total of patient charges before this program executes
• PAT-TOTAL-AMT-NET - New charges tacked on "today" as the program runs - a new "running total" for this patient
• AMT-PER-DAY - Gross charges per patient/per day
• INS-COVERAGE-PERC - 10% hard-coded in WORKING-STORAGE 395
Optional Workshop - Workshop 16.2b - Maintenance on HOSPEDIT
Fix the problems in the output report (the report layout/U.I.):
1. See next slide for a mock-up of what a minimally-professional report might look like
2. Clean up the arithmetic errors in the program stats
3. And write the output report detail/records ONLY for good (valid) input data
4. The data for Lex Luthor, Frank Thomas and BillieJoe Mcallister is incorrect.
Fix the records so that they're written to the valid output file (HOSPOUT) instead of
the error file

396
Optional Workshop 16.2c - Maintenance on Editing/Validation Program

New Report Headers

Formatted
Phone# New Output Fields in the report

Translate Network data values: I = In … O = Out

Add/Change the following to RPTFILE


New statistics

Gross Total = All daily amounts from valid records


397
 Nothing to hand in

Optional/Advanced - Redesign and Restructure HOSPEDIT


Did you have any trouble actually figuring out how HOSPEDIT does what it does when you
Desk-Checked the code? No? Well I did. And the logic I wrote 12 years ago is nothing short of
hideous.
So - along with being flat-out wrong, the program is badly designed/structured 
• Multiple/Separate READ statements
• Paragraphs that do more than one thing; I.E. they're "overloaded"
• Separate CLOSE statements
• Zero comments - of any discernible value
• Additionally there are some flat-out errors in the final stats

Your to do:
• Fix the HOSPEDIT program's design and coding issues
• Make a copybook out of WS-INPUT-REC. Add a COPY statement to the program
• Add a few reasonable comments
398
 Nothing to hand in

Optional/Advanced Workshop - Complex SEARCH Example


Define, load and use table that contains 10 elements of 40 Create a new COBOL program for the
bytes each, and three keys. The primary and secondary following complex (3-Dim) table.
keys (KEY-1 and KEY-2) are in ascending order, but the
least significant key (KEY-3) is in descending order…………… 1. To create the rest of this program - you'll
01 TABLE-A. need:
05 TABLE-ENTRY OCCURS 10 TIMES • Standard COBOL boilerplate:
ASCENDING KEY-1, KEY-2 IDENTIFICATON DIVISION DATA DIVISION, etc.
DESCENDING KEY-3
INDEXED BY INDX-1.
• Three variables in WORKING-STORAGE
10 PART-1 PIC 99. • Note that TABLE-A should be defined in
10 KEY-1 PIC 9(5). WORKING-STORAGE
10 PART-2 PIC 9(6). In the PROCEDURE DIVISION:
10 KEY-2 PIC 9(4). • DISPLAY the OUTPUT-AREA
10 PART-3 PIC 9(18). • Load TABLE-A from an external file.
10 KEY-3 PIC 9(5).Copy code

*** Search this table by using the following statements:


2. Create test data for the program (10 rows
as specified by the OCCURS clause):
SEARCH ALL TABLE-ENTRY
AT END
• Sort the test data in the external file
PERFORM NOENTRY manually***
WHEN KEY-1 (INDX-1) = VALUE-1 AND • KEY-1, KEY-2 (ascending)
KEY-2 (INDX-1) = VALUE-2 AND • KEY-3 (descending)
KEY-3 (INDX-1) = VALUE-3
MOVE PART-1 (INDX-1) TO OUTPUT-AREA
END-SEARCH
*** We'll learn about JCL Sorting in Module 18 399
UNIT COBOL for z/OS - Module 17

Advanced Table Handling


• Multi-Dimension Tables
• Visualizing
• Defining
• Loading
• Searching
• Variable Length Records
Additional learning links:
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/tasks/tptbl05.htm
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/tasks/tptbl42.htm
https://condor.depaul.edu/jpetlick/COBOL10.html
400
401
COBOL Program Big Picture - Topics in Module 17
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure COBOL Table Handling
DISPLAY, GOBACK • Concepts
Code Paragraph • Loading
PERFORM Paragraph UNTIL <condition> • Accessing
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename> • Indexed by/Subscript
INITIALIZE • Single-Dim OCCURS
Counters, Accumulators, Flags
Table Search z/OS ABENDS
COBOL Table Handling Reference Modification, Figurative Constants • Sequential Search • Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation • •
• Multi-Dimension Tables COBOL String Handling Functions: UNSTRING, STRING •
Binary Search
DFSORT •
Safeguards
Resolutions
• Variable Blocked Records
COBOL Reusable Code Libraries
• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
Multi-Dimension (OCCURS within OCCURS) COBOL Tables
On the surface, multi-dimension tables sound a little scary - like only Stephen Hawking would
use them. But in reality? You've understood and worked with two, three and even four dim tables
since you were 8 years old:
• Business: • School:
• Yearly sales is comprised of: • Each Semester has:
• Quarterly sales is comprised of: • Course offerings - with:
• Monthly sales • Instructors
• Students
• A retail store can have many: • Test Results
• Departments - which can have several: • Calendars:
• Managers who supervise • Years
• Sales people • Months
• Stock people • Days
• Customer service reps • Hours
Multi-Dim tables are nothing new in real life - although programming them in COBOL is new.
Let's begin…
402
403

Two-Dimension Table == MS-Excel Spreadsheet


Project Quarterly Expenses ……………….…… One of the best ways to visualize
a two-dim table is to think of it like
the rows and columns of an MS-
Excel spreadsheet

Nine rows - Nine projects


In each row there are five
columns:
• Project-Name
• Expenses:
• Which occur 4 times
per/row
Visualizing a Two-Dim Table 2-Dim Table definition
01 STUDENT-GRADES.

05 STUDENT-NAME PIC X(20).

05 SEMESTER OCCURS 2 TIMES.

10 CLASS-DETAILS OCCURS 2 TIMES.

20 CLASS-NBR PIC X(5).

20 GRADE-EVAL PIC 9(2).

Name Class-NBR(1,1) Grade(1,1) Class-NBR(1,2) Grade(1,2) Class-NBR(2,1) Grade(2,1) Class-NBR(2,2) Grade(2,2)

Class-Details(1,1) Class-Details(1,2) Class-Details(2,1) Class-Details(2,2)

Semester (1) Semester (2)

Entire Table: Student-Grades

By defining the table as shown above, we have programmatic


access to every element including groups of element occurrences 404
Visualizing a Two-Dim Table - Declarations and Data
01 STUDENT-GRADES.

05 STUDENT-NAME PIC X(20).

05 SEMESTER OCCURS 2 TIMES.

Data is 10 CLASS-DETAILS OCCURS 2 TIMES.

treated as a 20 CLASS-NBR PIC X(5).

two-dim Table 20 GRADE-EVAL PIC 9(2).

STUDENT-GRADES

STUDENT-NAME SEMESTER(1) SEMESTER(2)

CLASS-DETAILS(1,1) CLASS-DETAILS(1,2) CLASS-DETAILS(2,1) CLASS-DETAILS(2,2)

CLASS-NBR(1,1) GRADE(1,1) CLASS-NBR(1,2) GRADE(1,2) CLASS-NBR(2,1) GRADE(2,1) CLASS-NBR(2,2) GRADE(2,2)

Bobby Fischer AAAAA94BBBBB87CCCCC78DDDDD99


0000000000222222222233333333334444444444555
1234567890123456789012345678901234567890123 405
Multi-Dimension COBOL Tables – Additional Examples 406

Two-Dim Table
Using the previous slide as an
01 SALES-DATA.
05 CORPORATION-NAME PIC X(30). example, draw a mental-
05 YEARLY-SALES OCCURS 5 TIMES. image of how the data in this
10 CALENDAR-YEAR PIC X(4). two and three-dim table can
10 QUARTERLY-DETAILS OCCURS 4 TIMES.
20 SALES-FIGURES PIC $$,$$$,$$9.99. be visualized or understood

01 COMPANY-ORG-THREE-DIM-TABLE.
05 COMPANY-LOCATION OCCURS 4 TIMES. This is important, if you are
10 LOCATION-ID PIC X(05). going to be able to code
10 TERRITORY-TABLE OCCURS 13 TIMES. business logic that processes
20 TERRITORY-NAME PIC X(20).
20 TERRITORY-REP OCCURS 4 TIMES. information organized in
30 PRIVATE-DATA. nested OCCURS data
40 SALARY PIC 9(09). structures.
Three-Dim Table 40 CURRENT-ASSIGNMENT PIC X(60).

MOVE SALES-FIGURES(2, 3) TO THIRD-QUARTER-DATA-OUT. *> Two-Dim Table

MOVE 'INDUSTRY-CONSTRUCTION-ANALYST' TO CURRENT-ASSIGNMENT(1, 10, 3). *> Three-Dim Table

PERFORM VARYING LOC-IDX FROM 1 BY 1 UNTIL LOC-IDX > 4


PERFORM VARYING TERR-IDX FROM 1 BY 1 UNTIL TERR-IDX > 13
PERFORM VARYING DATA-IDX FROM 1 BY 1 UNTIL DATA-IDX > 4
COMPUTE SAL-TOT = SAL-TOT + SALARY(LOC-IDX, TERR-IDX, DATA-IDX). *> Three-Dim Table
TABLES02
Loading a Multi-Dimension Table
Just Like one-dim tables, you can load a 2-or-3-Dim table:
1. Programmatically - with values from an online screen, file or
database
• This is will be the rule not the exception for how you load
COBOL tables in real corporate application COBOL programming
• Because it allows the business the flexibility of modifying your
application without having to recompile programs
2. REDEFINES - constant field values with an OCCURS
3. Using Initialize
4. Using the VALUE clause on elementary field definitions.

• To load a table from a file you will nest

TABLES04
PERFORM statements as shown here ➔
• Two-Dim table (5 X 5)
• Two subscripts each varying from 1 by 1
• Move statement to value specific CELL(Row, Col)
RefMod used to make the (Row, Col) construction of the table
clearer

407
Referencing Data in a Multi-Dimension Table with a Subscript

Rule-of-thumb; You need a subscript or Index references for each OCCURS clause in
the table definition Record Layout
If your program has loaded DDS0001.LEARN.STUDENT.COURSES into the WS-STUDENT-TABLE, the following code is valid:
MOVE 3 TO STUDENT-SUB.
MOVE WS-STUDENT-TABLE(STUDENT-SUB) TO STUDENT-OUT. Move STUDENT-TABLE occurrence 3 …
MOVE WS-STUDENT-NAME(STUDENT-SUB) TO STUDENT-OUT.
MOVE 2 TO COURSES-SUB.
MOVE WS-COURSE-GRADE (STUDENT-SUB, COURSES-SUB) Move WS-COURSE-GRADE(3,2) …
TO COURSE-OUT.
PERFORM VARYING STUDENT-SUB FROM 1 BY 1 Iterate thru the outer table …
UNTIL STUDENT-SUB > 5 OR STUDENT-FOUND
PERFORM VARYING COURSES-SUB FROM 1 BY 1
UNTIL COURSES-SUB > 5 OR STUDENT-FOUND Iterate thru the inner table …
IF WS-COURSE-NBR (STUDENT-SUB, COURSES-SUB) = 'ANTH101'
AND WS-COURSE-GRADE (STUDENT-SUB, COURSES-SUB) = '3'
MOVE WS-STUDENT-NAME(STUDENT-SUB) TO STUDENT-OUT WHEN/IF specific student found stop search
MOVE 'Y' TO SW-STUDENT-FOUND
END-IF
END-PERFORM
END-PERFORM. 408
Referencing Data in a Multi-Dimension Table with a SEARCH
Considerations for
using SEARCH on a
multi-dim table:
• You will PERFORM
VARYING an Index FROM
1 BY 1 on the outer-table
until:
• End of Table
• Or Item Found ***

• You can SEARCH the


inner-table

• And use WHEN to locate


items of interest

• Reminder: COBOL
SEARCH requires an
Indexed Table

*** It is important to test for the Item-Found condition on both the inner and outer table iterations. Why? 409
Cracking the Code -
Variable Length Records
Variable-Length files allow shops to save disk space, by writing & reading data that
does not contain trailing FILLER/Space characters.
Variable Length files have 4 Byte descriptors at the beginning of each record. These
descriptors are used by the z/OS to READ & WRITE the correct number of bytes
in each Block and Record.
To use Variable-Length files:
1. Allocate a new 80-byte Variable Blocked file:

4 Bytes < file LRECL


1. RECFM: VB
2. LRECL: 84 Note: 80 bytes of data + 4 byte descriptor
3. BLKSIZE: 0

2. Create a Sandbox program with code like this ➔


1. RECORD VARYING FROM 1 TO 80
• Note the PIC clause must be 4 less than the Allocated VB file size
2. DEPENDING ON VARIABLE
• Must be a WORKING-STORAGE PIC 9 variable
• You will move a numeric value to the variable telling z/OS the size
(in bytes) of VB records to write
• z/OS will place a numeric value in the variable equal to the length of the
VB record read
410
Visualizing Variable Length Records
A Variable Blocked file contains:
• Data - records
• RDWs - Record Descriptor Words: A four-byte header that indicates the length of each record
• BDWs - Block Descriptor Words: Another four-byte header that indicates the length of each block of records
• Typically you let z/OS calculate the BDW size - by coding Block Contains 0

BR R BR R BR R
DD record D record DD record D record DD record D record …
WW W WW W WW W

COBOL I/O behavior:


• Upon READ - z/OS registers the length of each record in the FD's DEPENDING ON program variable
• Upon WRITE your program is responsible to specify the length of record-being-written in the same
DEPENDING ON program variable as the file being written to
411
412
COBOL Program Big Picture - Topics in Module 17
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure COBOL Table Handling
DISPLAY, GOBACK • Concepts
Code Paragraph • Loading
PERFORM Paragraph UNTIL <condition> • Accessing
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename> • Indexed by/Subscript
INITIALIZE • Single-Dim OCCURS
Counters, Accumulators, Flags
Table Search z/OS ABENDS
COBOL Table Handling Reference Modification, Figurative Constants • Sequential Search • Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation • •
• Multi-Dimension Tables COBOL String Handling Functions: UNSTRING, STRING •
Binary Search
DFSORT •
Safeguards
Resolutions
• Variable Blocked Records
COBOL Reusable Code Libraries
• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
 Nothing to hand in

Workshop 17.1 - Sample Table-Handling Program


Open LEARN.COBOL(TABLES02). This
program demonstrates working
table-handling patterns. Read
through the code paying attention to
the areas we covered in this Module.

Browse
DDS0001.LEARN.STUDENT.COURSES -
and visually map the repeating data
areas of each record to the DATA
DIVISION layout (…STUDENT-TABLE…)

Debug the program - note the


SELECT/ASSIGN clauses - and note
that the output file is not producing
anything. Why? Fix the problem ☺

Note the two different types of table


searches - both Syntax and Logic flow
413
Optional Workshop 17.2a - Table-Handling Program
Using the file: LEARN.STUDENT.COURSES create a program that generates the following report…...
Date: xxxx/xx/xx Student Courses Breakout Page: nn
• You can (and should) copy code out Student Name: XXXXXXXXXXXXXXXXXXXX
TABLES02: Course: XXXXXXXXXX Grade: X
• COBOL Boilerplate Course: XXXXXXXXXX Grade: X
• Input File handling …
Student Name: XXXXXXXXXXXXXXXXXXXX
• Loading the table(s) Course: XXXXXXXXXX Grade: X
• The grades should display as A, B, C, D, F …
------------------------------
• If you encounter an grade value other Total number of students: nn
than A, B, C, D, F write that record to an
Student with highest QPA: XXXXXXXXXXXXXXXXXXXX
error file with an appropriate error
message Student with lowest QPA: XXXXXXXXXXXXXXXXXXXX
Average QPA for all students: nn
• But you will need to translate them in
order to calculate QPA statistics
• A=4, B=3, C=2, D=1, F=0

• If possible, use the Intrinsic functions on


the table data to find the lowest &
highest QPA 414
415

Optional Workshop 17.2b - Table-Handling program

You will also need: Record Layout - LEARN.STUDENT.COURSES


• The Weekday Table (Workshop 15.2) for the report
• An EVALUATE to translate the letter grades into integers

When you've finished the report on the previous slide create a 5X5
WORKING-STORAGE table out of the LEARN.STUDENT.COURSES data
and perform the following Searches:
• Find anyone who's studied TRIG551 or DRUM310
• Is SALLY HARRIS taking ear-training (EART164)?
• What did LISA CRUDUP get in PSYCH23A? I left this code in the program
(no need to thank me) ☺
• Are there any records with invalid grades
• Use an 88-level to define invalid vs. valid grades (A, B, C, D, F)
Optional Workshop 17.3a -
"Alexa, What's the weather for the next 3 days?"
From the data in a file named: LEARN.WEATHER - which is a
112:00AM8510462
fictional feed from the NWS - create the following report: 101:00AM8410766
102:00AM8310868
103:00AM8210971
104:00AM8120372
105:00AM8020472

for your LEARN.WEATHER file


Hourly Weather: Bangor, ME
106:00AM8720472

(Incomplete) Copy-able data


Date: xxxx/xx/xx Time: hh:mm:ss 107:00AM7621459
108:00AM7531459
Date Time Temp Wind Humidity 109:00AM7631458
============ ============= ============= ============= ============= 110:00AM7731458
111:00AM8831449
Wednesday 12:00 PM 85 NW 4 mph 66%
112:00PM8551445
101:00PM8451445
1:00 PM 87 NW 5 mph 68% 102:00PM6350446
103:00PM6950437
2:00 PM 88 NW 5 mph 67%
104:00PM6570438
105:00PM6770439
106:00PM7671039
… … .. … .. 107:00PM7771470
108:00PM6681471
Thursday 12:00 AM 68 SW 4 mph 65% 102900PM6780462
110:00PM5880463
111:00PM5780454
1:00 AM 69 SW 5 mph 66%
212:00AM9610455
202:00AM8914446
… … … … … 202:00AM7945447

416
Optional Workshop 17.3b Steps -
"Alexa, What's the weather for the next 3 days?"
Use the incomplete copy-able data on the previous slide to create a new, FB/LRECL:20 Sequential Data Set
• Create a total of 3 days worth of weather data

Code a program starting from the record layout:


• Create a two-dim table for the weather data
• DAYS (3 occurrences)
01 WEEKDAYS-TABLE.
• Hours (24 occurrences) 05 PIC X(9) VALUE "Monday".
• Day-Of-Week PIC 9(1) 05 PIC X(9) VALUE "Tuesday".
• Time-Of-Day PIC X(7) 05 PIC X(9) VALUE "Wednesday".
• Temp PIC X(2) 05 PIC X(9) VALUE "Thursday".
05 PIC X(9) VALUE "Friday".
• Wind-Direction PIC 9(1)
05 PIC X(9) VALUE "Saturday".
• Wind-speed PIC X(2) 05 PIC X(9) VALUE "Sunday".
• Humidity PIC X(2) 01 REDEFINES WEEKDAYS-TABLE.
05 DT-OF-WK OCCURS 7 TIMES PIC X(9).

• Translate the Day-Of-Week numbers into the proper week-day using the above table.
• MOVE DT-OF-WK(Day-Of-Week) to some-pic-x-9-field
• Always starting with Monday. And the Time-Of-Day hours will always start with 12:00 AM
• Create another table to translate Wind-Direction - which is a PIC 9(1) input field from the NWS.
• Table translations:
1➔N 2➔NE 3➔E 4➔SE 5➔S 6➔SW 7➔W 8➔NW
• Use the Wind-Direction number as a subscript into the Wind-Direction table to retrieve the values
417
1,
Optional Workshop 17.3c - Hourly updates/Hourly reports
1. Once the table is loaded - you need to provide an update mechanism to change
values in the table on a cell-by-cell basis based on hourly feeds from the NWS:
• Create a new table file for the hourly feed: 112:00AM85
101:00AM84
• Day 102:00PM83
• Time 203:00AM82
• Temp 104:00PM86
305:00AM80
• Read the new hourly feed data into a table
• Update the Temp column of the weather data table
• Write out a new report
2. It turns out the NWS is better at predicting the weather than I/T. There've been
some really odd values in the feed - so the bosses have asked you edit the data:
• Day must be: 1, 2, or 3
• Time must be between: 12:00AM and 11:00PM
• Temp must be between 32 and 99F
• Wind direction must be; N, NE, SE, S, SW, W, NW
• Wind speed must be > 0 and < 99
• Humidity must be > 30 and < 80 418
01 TWO-DIM-TABLE-VALUES.
05 ROW1 PIC X(48) VALUE
'TUBA101BCALC687BSOCS200AALGB124APHYS002BFLUT140C'.
Advanced/Optional Review
05 ROW2 PIC X(48) VALUE Question 17.4  Nothing to hand in
'BIOL201ATRIG551BSHAK213CPSYC234ABIOL002CDRUM310B'.
05 ROW3 PIC X(48) VALUE Why doesn't the code on the
'POLY555CGEOM231BRLIT560ABIOL136AMECH002BACCO140D'.
05 ROW4 PIC X(48) VALUE left work? Note: We're searching the
'TUBA567ASTAT043CSHOP980BCHEM534BSTT0002AVIOL610A'. Student Table for someone who's gotten
05 ROW5 PIC X(48) VALUE
'MEDC522DPIAN003ASPAN760AEBRT164ARUSS002APIAN170A'. an "A" in both TUBA567 and VIOL610.
01 WS-STUDENT-RECORD-RDF REDEFINES TWO-DIM-TABLE-VALUES.
02 WS-STUDENT-TABLE-RDF OCCURS 5 INDEXED BY ST-IDX.
05 WS-STUDENT-COURSES-RDF.
10 WS-STUDENT-COURSE-TAB-RDF OCCURS 6 TIMES
1. Create a Sandbox program out
INDEXED BY CRS-IDX. of this sample
15 WS-COURSE-NBR-RDF PIC X(7).
15 WS-COURSE-GRADE-RDF PIC X(1).
2. COBUCLD your program
.....
PERFORM VARYING ST-IDX FROM 1 BY 1
UNTIL ST-IDX > 5 OR MUS-FOUND
SET CRS-IDX TO 1
3. Monitor the indexes & table
* Find the first TUBA student with an "A" in TUBA and VIOLA values and figure out why this logic
SEARCH WS-STUDENT-COURSE-TAB-RDF
WHEN WS-COURSE-NBR-RDF (ST-IDX, CRS-IDX) = 'TUBA567' will never work
AND WS-COURSE-GRADE-RDF (ST-IDX, CRS-IDX) = 'A'
AND WS-COURSE-NBR-RDF (ST-IDX, CRS-IDX)= 'VIOL610'
AND WS-COURSE-GRADE-RDF (ST-IDX, CRS-IDX) = 'A' Hint see "Compound IF Conditions"
DISPLAY '*** Musician Found ***' earlier in this slide deck.
MOVE 'Y' TO SW-MUS-FOUND
END-SEARCH
END-PERFORM. 419
UNIT COBOL for z/OS - Module 18

Batch Logic Patterns


• Control Break Logic
• Single Level Control Break
• Multi-level Control Break
• Sorting Data
• External MVS Utility Sort
• Internal COBOL Sort
• Master File Update Logic

420
421
COBOL Program Big Picture - Topics in Module 18
Identification Name the executable Program-ID. CNTRLBR1.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE COBOL Table Handling
Executable statements that
Signed Conditions, Class Conditions • Multi-Dimension Tables
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior • Variable Blocked Records
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure COBOL Table Handling
DISPLAY, GOBACK • Concepts
Code Paragraph • Loading
PERFORM Paragraph UNTIL <condition> • Accessing
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename> • Indexed by/Subscript
Control Break Logic INITIALIZE • Single-Dim OCCURS
• MVS Utility Sort Counters, Accumulators, Flags
Table Search z/OS ABENDS
Reference Modification, Figurative Constants
• Internal COBOL Sort •
Intrinsic Functions: Date, Math, Analytics, Text Manipulation •
Sequential Search
Binary Search


Understanding
Safeguards
• COBOL Logic Pattern COBOL String Handling Functions: UNSTRING, STRING • DFSORT • Resolutions

COBOL Reusable Code Libraries


• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
Control Break Reports
A Control Break report displays data
grouped by a "control field" - in a manner
like what you're seeing here (grouped by
State) ➔

This (report output) may look daunting,


but in fact, there is only one additional
programming construct that you haven't
yet learned ………. which is:
Sorting Data
Control Break reports use data that has
been sorted on the report "control field".
The sorting creates data sub-groups of
records. In this case - the State where
each president was born.

Important note for those of you using your own z/OS systems -
you will need to find JCL that invokes you shop's sort utility. 422
Sorting Data - How To
• Sorting data is integral to business data processing - and has been since the 1960s
• There are several ways to sort data on the mainframe:
• The COBOL programming SORT keyword ("internal COBOL sort")
• This option has the additional feature of COBOL being able to filter the file-to-be-sorted
• An MVS Utility Sort product such as: DFSORT, ICETOOL, SYNCSORT ("external/utility sort")

• Your shop will have installed one or more Sort products/utilities, and should be able to provide
you with JCL to invoke the sort

Net: A Sort utility reads un-sequenced file records, and outputs the records in sorted sequence
as defined in the JCL's "SORT Cards"

AB.IN.FILE Sort Utility AB.OUT.FILE

CCCCCCCCCCCCCCC //SORTIN DD DSN=AB.IN.FILE AAAAAAAAAAAAAAA


XXXXXXXXXXXXXXX //SORTOUT DD DSN=AB.OUT.FILE BBBBBBBBBBBBBBB
KKKKKKKKKKKKKKK SORT FIELDS=(1,15,CH,A) CCCCCCCCCCCCCCC
AAAAAAAAAAAAAAA DDDDDDDDDDDDDDD
… …
423
DFSORT UTILITY - JCL EXAMPLE
//DDS0001S JOB , JOB Card
// MSGCLASS=H,MSGLEVEL=(1,1),TIME=(,4),REGION=0M,COND=(16,LT)
//SORTSTEP EXEC PGM=SORT
Execute SORT Utility
//SYSPRINT DD SYSOUT=*
//SYSOUT DD SYSOUT=*
Utility Completion Msgs
//SORTIN DD DSN=DDS0001.LEARN.ACCT.DATA,DISP=SHR Unsorted input file
//SORTOUT DD DSN=DDS0001.LEARN.ACCT.SORT.DATA,DISP=(NEW,CATLG,DELETE),
// STORCLAS=USRBASE,SPACE=(TRK,(12,5),RLSE), Allocate new output file
// DCB=(LRECL=170,BLKSIZE=0,RECFM=FB,DSORG=PS)
//SYSIN DD *
SORT FIELDS=(99,15,CH,A) SORT Control Cards

Create the //SORTOUT data set by sorting each of the //SORTIN file records
- By 15 characters
- Starting at byte 99
- In CHaracter (Alphanumeric)/Ascending (EBCDIC) sequence**

** You can also sort by Packed


IBM's DFSORT "Getting Started" PDF: Decimal, Binary (COMP)
https://www-01.ibm.com/servers/resourcelink/svc00100.nsf/pages/zOSV2R3sc236880/$file/iceg200_v2r3.pdf and other datatypes 424
Sorted File
Control Break Reports - AAAAAAAAAA
AAAAAAAAAA

COBOL Logic Pattern AAAAAAAAAA


BBBBBBBBBB
BBBBBBBBBB
CCCCCCCCCC PROGRAM
CCCCCCCCCC
1. HOUSEKEEPING
Creating Control Break Reports with CCCCCCCCCC
1a. OPEN FILES/INITIAL READ
COBOL is straightforward, once you 1b. DO CONTROL BREAK
understand the fundamental mechanics 1d. MOVE IN-SORT-FLD ➔ WS-CONTROL-FLD AAAAAAAAAA
of the sorted input file compare: Record…AAAAAAAAAA … 1e. DO DETAIL PROCESSING LOGIC
IN-SORT-FIELD
1. Housekeeping, including Priming Read Values 2. Loop until end-of file:
Record…AAAAAAAAAA … READ-NEXT RECORD
IN-SORT-FLD = WS-CONTROL-FLD? AAAAAAAAAA
2. Compare Infile sorted record-key with DO DETAIL-LOGIC AAAAAAAAAA
stored sorted-record-key Record…BBBBBBBBBB … READ-NEXT RECORD
IN-SORT-FLD = WS-CONTROL-FLD? BBBBBBBBBB

3. If equal/same sub-group:
L DO CONTROL-BREAK AAAAAAAAAA
MOVE IN-SORT-FLD ➔ WS-CONTROL-FLD
Do Record Processing O READ-NEXT RECORD
BBBBBBBBBB
BBBBBBBBBB
Else/new sub-group Record…BBBBBBBBBB …
Do Control Break
O IN-SORT-FLD = WS-CONTROL-FLD?
DO DETAIL-LOGIC BBBBBBBBBB

P Record…CCCCCCCCCC … READ-NEXT RECORD BBBBBBBBBB

4. Read Next Input file record IN-SORT-FLD = WS-CONTROL-FLD? CCCCCCCCCC


DO CONTROL-BREAK BBBBBBBBBB
… MOVE IN-SORT-FLD ➔ WS-CONTROL-FLD
READ-NEXT RECORD

Note that WS-CONTROL-FLD is sometimes referred to as a "HOLD-KEY" Can you guess why? 425
FILE-CONTROL.
SELECT PRINT-LINE ASSIGN TO PRTLINE.
Creating Control Break Reports SELECT ACCT-REC ASSIGN TO ACCTSORT. *> Sorted input file
CNTRLBRK
- Coding the Logic Pattern ... "Pseudocode"
WORKING-STORAGE SECTION.
01 WS-BREAK-CONTROLS.
INIT-RTN. 05 HOLD-CONTROL-KEY PIC X(15). *> "Hold Key"
• Open all files ...
PERFORM 100-INIT-RTN
• Read Sorted File PERFORM 300-PROCESS-RECORDS UNTIL EOF-INPUT
• Move Control-Key to Hold-Key ...
• Perform Control-Break -- to 100-INIT-RTN.
generate report headers OPEN FILES
PERFORM 700-READ-RECORD - Read first record from file sorted on Control Key
MOVE IN-CONTROL-KEY TO HOLD-Control-Key *> Set HOLD-Key
MAIN (300-PROCESS-RECORDS) PERFORM 500-CONTROL-BREAK *> Initial Control Break for headers
(have "next" record from previous logic) ...
• Compare Infile-Key to Hold-Key 300-PROCESS-RECORDS.
• USA-STATE is the Infile-Key ...
• If equal (if from same sub- IF HOLD-CONTROL-KEY = IN-CONTROL-KEY *> Process Detail Records in same sub-group
PERFORM 400-MOVE-DATA
group) ELSE
- Do Detail processing PERFORM 500-CONTROL-BREAK *> Process Control Break (new sub-group)
• If Not equal (next sub-group) ...
- Do Control Break 400-MOVE-DATA.
processing Add to sub-totals
Write Detail Line
READ NEXT RECORD FROM Sorted input file (ACCTSORT)
500-CONTROL-BREAK.
Write Trailer-rec
Write headers
Note: There are a number of Move IN-CONTROL-Key Value to HOLD-CONTROL-KEY
different - and valid Control Break 426
Understanding CNTRLBRK - Sample Control Break Program Under Debug
Monitors of key field values

Sorted
Data
File

427
Visual Debug View
Two-Level Control Break Reports
Two-Level Control Break programs are almost as
common in business as single-level programming
requirements.

Note this example-report of patient expenses


broken out by Wards within Hospitals ➔

Two-Level Control Breaks follow the same COBOL logic


pattern as single-level:
1. The input file must be pre-sorted:
• Inner Control Break values within Outer Control Break
values; i.e. WARD within HOSPITAL

2. You'll code logic reading an input file and checking a hold


value against the:
• Outer-Control Break Value - first - then checking against the
• Inner-Control Break Value
… and doing the appropriate processing
428
Sort - Two-Level Control Breaks
//DDS0001S JOB , JOB Card
// MSGCLASS=H,MSGLEVEL=(1,1),TIME=(,4),REGION=0M,COND=(16,LT)
//SORTSTEP EXEC PGM=SORT
Execute SORT Utility
//SYSPRINT DD SYSOUT=*
//SYSOUT DD SYSOUT=*
Utility Completion Msgs
//SORTIN DD DSN=DDS0001.LEARN.HOSP.WARD,DISP=SHR Unsorted input file
//SORTOUT DD DSN=DDS0001.LEARN.HOSP.WARD1.DATA,DISP=(NEW,CATLG,DELETE),
// STORCLAS=USRBASE,SPACE=(TRK,(1,5),RLSE),
Allocate new output file
// DCB=(LRECL=80,BLKSIZE=8000,RECFM=FB,DSORG=PS)
//SYSIN DD *
SORT FIELDS=(1,16,CH,A,17,20,CH,A) SORT Control Cards

Create the //SORTOUT data set by sorting each of the //SORTIN file records as follows:
• Outer-Level Control Break:
- 16 characters
- Starting at byte 1
- In CHaracter/Ascending sequence (1,16,CH,A,17,20,CH,A)
• Inner-Level Control Break:
- 17 characters
- Starting at byte 20 Major/Outer Minor/Inner
- In CHaracter/Ascending sequence Sort Sort
429
Two-Level Control Break Program Example: CNTRLBR2

Hospital Control Break ➔

End of Input File ➔

Patient Detail Processing ➔

Not End-of-File ➔

Ward Control Break ➔ 430


Two-Level Control Break Program Example: CNTRLBR2
As mentioned previously, there are several different algorithmic approaches to programming Control
Breaks. CNTRLBR2 represents an example of a "tricky" coding solution. As such it might not be the
ideal model for production tasks. However you might run into something like this.

• Copy CNTRLBR2 from


DDS0001.LEARN.COBOL
• COBUCLG the program and look
over the results
You will need a //INFILE DD that points
to: DDS0001.LEARN.HOSP.WARD1.DATA
And a SYSOUT=* for the PRTLINE DD card

• COBUCLD the program


• Monitor (at least) the variables In this program LEVEL-CONTROL is
over-loaded. It is used as an END-OF-
shown in the Monitors view FILE flag and used to establish (after
from the screen capture each input record has been read)
whether to do first-time-in processing,
• Step through the code, paying to do an outer-Level control break,
attention to the comments and inner-Level control break, or to do
the value: LEVEL-CONTROL detailed processing.

431
ENVIRONMENT DIVISION.

Internal COBOL Sort Program INPUT-OUTPUT SECTION.


FILE-CONTROL.
SELECT IN-FILE ASSIGN TO RENTALS
...
There is a COBOL SORT verb - that (depending on SELECT OUT-FILE ASSIGN TO RENTSRT
the COBOL compiler directives defined at your shop) ...
SELECT WORK-FILE ASSIGN TO WRKFILE.
will sort input data - as part of a COBOL program - DATA DIVISION.
FILE SECTION.
allowing you to scrub or process the input data prior FD IN-FILE.
...
to releasing records to be sorted - or the FD OUT-FILE.
01 OUTPUT-RENTAL.
output/sorted records before printing. ...
SD WORK-FILE
RECORD CONTAINS 56 CHARACTERS
DATA RECORD IS WORK-RENTAL.
The operational characteristics of internal COBOL 01 WORK-RENTAL.
sort include: 05 RENTAL-ID-W PIC 9(5).
WORKING-STORAGE SECTION.
PROCEDURE DIVISION.
• SORT WORK FILE - ENVIRONMENT DIVISION OPEN INPUT IN-FILE
OUTPUT OUT-FILE.
SORT WORK-FILE ON DESCENDING KEY RENTAL-ID-W
• SORT DESCRIPTOR - FILE SECTION INPUT PROCEDURE 200-SRT-INPUT-PROCD
OUTPUT PROCEDURE 300-SRT-OUTPUT-PROCD.

• SORT Keyword GOBACK.


200-SRT-INPUT-PROCD SECTION.
READ SORT-IN-FILE AT END MOVE 'Y' TO OFCODE.
• USING File MOVE INPUT-RENTAL TO WORK-RENTAL.
RELEASE WORK-RENTAL.
• GIVING File 300-SRT-OUTPUT-PROCD SECTION.
• INPUT PROCEDURE RETURN WORK-FILE
AT END ...
• OUTPUT PROCEDURE MOVE WORK-RENTAL TO OUTPUT-RENTAL. 432
WRITE OUTPUT-RENTAL.
Optional Logic Pattern - Master File Update Logic
• Following closely on the heels of Control Break logic is Read-next-master-rec
2
Read-next-trxn-rec
Master File update logic. Master Files updates made by
sequential ("transaction") files was a staple of batch while not (at-end-of-master and at-end-of-trxn-files)
application programming in the 60's - 70's and 80's 3 if master-key < trxn-key
4
then
• And while the data sources have morphed from QSAM to rewrite-master-file-from-master-rec
VSAM to DL/I to IDMS to DB2, the basic logic pattern is still read-next-master-rec
else
in use it is one of the most efficient ways to apply if master-key = trxn-key 5
Add/Change/Delete records to a master file then
update-master-rec-using-trxn-rec
• The basic constructs: read-next-trxn-rec
else
1. Both master and transaction files are sorted on the same key if master-key > trxn-key 6
2. The program reads a record from each file then
add-new-trxn-rec-to-master-file
3. And performs a looped-compare routine, comparing that "same read-next-trxn-rec
L key" from both files end-if
4. If the Master-Key value < Transaction-Master-Key value that end-if
O there are no transaction-updates so rewrite the Master File and end-while
O read the next master-file record

P 5. If the Mast-key value = the Transaction key apply the updates


from today's transaction file and read the next trxn-record
6. If the Master-Key value > the Transaction key value create a new Another COBOL Masterfile Update program:
Master File record from the Transaction file.
https://www.tek-tips.com/faqs.cfm?fid=1109 433
434
COBOL Program Big Picture - Topics in Module 18
Identification Name the executable Program-ID. CNTRLBR1.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE COBOL Table Handling
Executable statements that
Signed Conditions, Class Conditions • Multi-Dimension Tables
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior • Variable Blocked Records
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure COBOL Table Handling
DISPLAY, GOBACK • Concepts
Code Paragraph • Loading
PERFORM Paragraph UNTIL <condition> • Accessing
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename> • Indexed by/Subscript
Control Break Logic INITIALIZE • Single-Dim OCCURS
• MVS Utility Sort Counters, Accumulators, Flags
Table Search z/OS ABENDS
Reference Modification, Figurative Constants
• Internal COBOL Sort •
Intrinsic Functions: Date, Math, Analytics, Text Manipulation •
Sequential Search
Binary Search


Understanding
Safeguards
• COBOL Logic Pattern COBOL String Handling Functions: UNSTRING, STRING • DFSORT • Resolutions

COBOL Reusable Code Libraries


• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
 Nothing to hand in

Workshop 18.1 - One Level Control Break Program


You will be responsible for LEARN.COBOL(CNTRLBRK) - which does Control Break
reporting on the USA's president's birth-state (USA-STATE).
• Review the code - and all elements of the Control Break logic
• Create your own copy of the ACCT.DATA file - and run a Sort Utility sorted on State
Ascending
• Debug CNTRLBRK:
• Step into the code
• Add Monitors to USA-STATE and WS-CONTROL-KEY
• Step thru the code - and after you've been thru the input file cycle once or twice Resume (run to
EOJ) and view the report in JES
• Change the DFSORT to sort by state Descending
• Run (not Debug…run) CNTRLBRK again
• Did you have to recompile/link? Why - or why not?
435
Workshop 18.2 - One Level Control Break Program

• Add a column to the far-right side of the report named: SALARY-ACCUM


• In this column display the accumulated salary while each presidents was in office
• Multiply the SALARY * number of years in office

• Also add a set of accumulators at the end of the report:


• Total of all presidents' Salaries (All presidents from all states)
• President that has highest Salary
• President that has the lowest Salary
• The average salary for all presidents

436
 Nothing to hand in

Optional Workshop 18.3 - Learn CNTRLBR2


As mentioned previously, there are a number of different algorithmic approaches to programming
Control Breaks. CNTRLBR2 represents an example of "tricky" coding.

• Copy CNTRLBR2 from


DDS0001.LEARN.COBOL
• COBUCLG the program and look
over the results
You will need a //INFILE DD that points
to: DDS0001.LEARN.HOSP.WARD1.DATA
And a SYSOUT=* for the PRTLINE DD card

• COBUCLD the program


• Monitor (at a minimum) the
variables shown in the screen In this program LEVEL-CONTROL is
capture ➔ over-loaded. It is used as an END-OF-
• Monitor as many variables as you FILE flag and used to establish (after
need to understand the program each input record has been read)
logic whether to do first-time-in processing,
to do an outer-Level control break,
• Step through the code, paying inner-Level control break, or to do
attention to the comments and detailed processing.
the value: LEVEL-CONTROL 437
Optional Workshop 18.4 - Turn CNTRLBR1
into a One Level Control Break Program
• Make a copy of CNTRLBR2 - name it
CNTRLBR1
• Remove all the references to WARD:
• Fields in the DATA DIVISION
• Headings
• Counters
• Hold-fields
• Etc.
• Processing logic for WARD data
• Run the program - and sand the output for
WARD information

438
UNIT COBOL for z/OS - Module 19
COBOL Subroutines
• Calling Subprograms
▪ Dynamic Calls
▪ Static Calls
• LINK-EDIT requirements:
• Parameter passing requirements (positional parameters)
▪ ENTRY USING
▪ LINKAGE SECTION
• Application architectures based on Subprograms
• So-called "Three-Tier Architecture"

Subprograms:
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/tasks/tpsub02.htm
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/concepts/cpsubw05.htm 439
440
COBOL Program Big Picture - Topics in Module 19
Identification Name the executable Program-ID. EBUD01.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE Control Break Logic
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK• WHEN
MVS Utility Sort
ZERO
• Internal COBOL Sort
IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields • COBOL Logic Pattern
Compound IF, Nested IF, EVALUATE COBOL Table Handling
Executable statements that
Signed Conditions, Class Conditions • Multi-Dimension Tables
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior • Variable Blocked Records
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure COBOL Table Handling
DISPLAY, GOBACK
• Concepts
Code Paragraph • Loading
PERFORM Paragraph UNTIL <condition> • Accessing
OPEN <Filename>, READ <Filename> AT END, WRITE, CLOSE <Filename> • Indexed by/Subscript
Calling Subprograms INITIALIZE • Single-Dim OCCURS
• Calling Protocol Counters, Accumulators, Flags
Table Search z/OS ABENDS
• LINKAGE Section Protocol Reference Modification, Figurative Constants • Sequential Search • Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation •
• Link-Edit Concerns COBOL String Handling Functions: UNSTRING, STRING
Binary Search • Safeguards
• DFSORT • Resolutions
• 3-Tier Architecture
COBOL Reusable Code Libraries
• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
Production Applications - Scale & Scope
• Production batch cycles consist of as many
batch programs as the mid-term workshop had
paragraphs … or in the case of larger batch
systems, as many batch programs as the mid-
term has COBOL statements.

Treatment Modules & Subroutines

Field Billing
DATEV
Verification

• Production applications are nearly always large and complex.


In order to simplify their development, maintenance, testing &
support, shops use modular design principles … functional
decomposition of complex business requirements into not just
paragraphs, but into complete COBOL programs, or "subroutines"
Customer Insurance
Account Policy
441
Subprograms and Production Batch Applications
Implementing applications using a modular-design approach
• Is not difficult - in and of itself
• Can simplify application maintenance and testing
• Provides a smoother on-ramp to modern languages (rewrite/refactor) - than
monolithic application designs
• Provides a more robust and flexible application architecture such as the
Three-Tier Architecture

Modular application designs employ subprograms; aka "subroutines"


• Successfully creating and calling subprograms requires you to understand:
• CALL USING and ENTRY USING protocols
• Types of calls
• LINKAGE SECTION nuances
• Parameter passing
• LINK-EDIT workflow 442
Subprogram Usage within Production Batch Applications
Three types - or three common uses for Subprograms:
1. Modular application design - implemented using Subprograms
• Functional decomposition of an application into Called & Calling programs

2. Called "Utilities"
• Date routines
• Complex edits
• Calculations or routines - that changes frequently
• Non-business, but software-application requirements:
• Auditing/Balancing
• Logging
• Security/Validation

3. Reengineer/Restructure/Refactor a monolithic application


• Almost all shops that I work with are currently doing this 443
1. Modular Application Design
Similar to the Program
Control Flow diagram - right? MAIN
CALL SUB01 USING A, B, C
Except that the nodes are CALL SUB02 USING D, G, H The CALL statement transfers

independent COBOL … control from one program to


another within a run unit.

programs - instead of
paragraphs
ENTRY USING A, B, C ENTRY USING D, G, H

SUB01 SUB02
CALL SUB03 USING A, K, U
CALL SUB05 USING G, X, Z
CALL SUB04 USING M

ENTRY USING A, K, U ENTRY USING M ENTRY USING G, X, Z

SUB03 SUB04 SUB05

444
1. Modular Application Design
PROGRAM-ID. SUB01.
WORKING-STORAGE. *> Data passed to called programs
01 CALLING-FLDS.
05 Z PIC… The CALL statement transfers control from
05 K PIC… one program to another within a run unit.
05 U PIC…
LINKAGE SECTION. *> Data received from calling program
01 A PIC… *> Linkage definitions for
01 B PIC… *> data values
01 C PIC… *> passed from MAIN
PROCEDURE DIVISION USING A, B, C.
*> Addressability to Linkage variable values
... ...
CALL 'SUB03' USING Z, K, C .
... ...
GOBACK. *> Control returned to MAIN

PROGRAM-ID. SUB03.
LINKAGE SECTION.
01 A PIC … *> Linkage Parms. Values passed from
01 K PIC … *> SUB01
01 U PIC … *> MAIN
PROCEDURE DIVISION USING A, K, U.
* Addressability to data from calling program
... ...
GOBACK. *> Control returned to calling program 445
2. Calling a "Utility Subprogram"
Over the years most COBOL shops have built a
collection of reusable routines that provide
MAIN
utility functions to business applications thru
CALL 'DATET USING WS-DATE-VAL, WS-RC
standard Called/Calling protocols: CALL 'SUBROGAT' USING WS-POLNO
• Date/Time validation WS-CLAIMNO, WS-CLAIM-AMT
• Audit and Logging routines The CALL statement transfers control from one program to another within the run unit.

• Security - especially for online applications


• Business-specific functionality - one-off routines ENTRY USING LS-DATE-VAL, ENTRY USING LS-POLNO,
required to process data specific to the company's LS-RC LS-CLAIMNO, LS-CLAIM-AMT

unique business rules DATET


** COBOL processing logic ** SUBROGAT
• Calls to external applications: ** COBOL processing logic **
• Government functional requirements
• Business partner/Supplier applications
• etc.

• The coding rules for calling a utility


subprogram are the same as for creating a
modular application design.
446
447
3. Refactoring an existing Monolithic COBOL Program into a Modular Design
Many shops seek the benefits of three-tier architectures.
INSCLAIM
Even if their COBOL code is monolithic, refactoring can
potentially be used to extract paragraphs from existing COBOL
300-COMPUTE-CLAIM.
programs into standalone subroutines. These subroutines can CALL 'CLMPAID' USING
be called from any COBOL application. CALL statements DEDUCTIBLE-MET-WS, CLAIM-PAID-WS,
replace the original inline code. CLAIM-AMOUNT, POLICY-COINSURANCE.

CALL 'CLMPAID' USING…


ENTRY USING DEDUCTIBLE-MET-LS,
CLAIM-PAID-LS,CLAIM-AMOUNT,
Paragraphs become Called modules POLICY-COINSURANCE.

CLMPAID
CALL 'SUBROGATION' USING WS-POLNO
WS-CLAIMNO, WS-CLAIM-AMT

ENTRY USING LS-POLNO


LS-CLAIMNO, LS-CLAIM-AMT
Paragraphs become Called modules
DEDUCTBL
IDENTIFICATION DIVISION.
CALLED/CALLING Programs PROGRAM-ID. CLAIMS.
DATA DIVISION.
WORKING-STORAGE SECTION.
In this example the main program 01 WS-CLAIM-ID PIC X(6) VALUE 'PL0443'.

"CLAIMS" does some initial


01 WS-CLAIM-POLICY PIC X(15) VALUE 'PERSONAL LINES'.1
01 WS-RETURN-CODE PIC X(3) VALUE SPACES.
processing of data then CALLs PROCEDURE DIVISION.
"RATING" * Processing pre-call*
2 CALL 'RATING' USING WS-CLAIM-ID, WS-CLAIM-POLICY, WS-RETURN-CODE.
* Processing post-call
The coding pattern: IF WS-RETURN-CODE = 0
DISPLAY 'CLAIM NBR : ' WS-CLAIM-ID
1. The calling program contains DISPLAY 'CLAIM POLICY : ' WS-CLAIM-POLICY
WORKING-STORAGE variable values GOBACK.
to-be-passed to the subroutine
IDENTIFICATION DIVISION.
2. "CLAIMS" Calls "RATING" USING PROGRAM-ID. RATING.
(passing the addresses of) its DATA DIVISION
WORKING-STORAGE fields WORKING-STORAGE SECTION.
01 WS-RATING-POLNO PIC X(4).
3. The subroutine's PROCEDURE DIVISION
code looks like this:
LINKAGE SECTION.4
01 LS-CLAIM-ID PIC X(6).
• PROCEDURE DIVISION USING LS-VAL1, ... 01 LS-CLAIM-POLICY PIC X(15).
• 01 LS-RETURN-CODE PIC X(3).
3
ENTRY USING LS-VAL1, LS-VAL2…..
PROCEDURE DIVISION USING LS-CLAIM-ID LS-CLAIM-POLICY LS-RETURN-CODE.
4. The subroutine's USING definitions * Processing LS data *
are declared in its LINKAGE SECTION MOVE LS-CLAIM-ID(3:4) TO WS-RATING-POLNO
* Return to calling program *
5. The subroutine further processes the IF WS-RATING-POLNO ...
data sent via the calling program, MOVE '-1' TO LS-RETURN-CODE 5
updates values and does a GOBACK GOBACK. 448
CALLED/CALLING Parameter Passing Protocol
PROGRAM-ID. CLAIMS.
WORKING-STORAGE SECTION. Calling Program
01 WS-CLAIM-ID PIC X(6) VALUE 'PL0443'. WORKING STORAGE variable/values used as
01 WS-CLAIM-POLICY PIC X(15) VALUE 'PERSONAL LINES'. parameters are passed positionally - that is from
01 WS-RETURN-CODE PIC X(3) VALUE SPACES. left-to-right P1,P2, P3 … (commas are optional)
PROCEDURE DIVISION.
CALL 'RATING' USING WS-CLAIM-ID, WS-CLAIM-POLICY, WS-RETURN-CODE.

PROGRAM-ID. RATING.
LINKAGE SECTION.
Called Program
01 LS-CLAIM-ID PIC X(6). LINKAGE SECTION variable values are received
01 LS-CLAIM-POLICY PIC X(15). positionally - from left-to-right: P1, P2, P3...
01 LS-RETURN-CODE PIC X(3). NOTE - the size (definition) for each LINKAGE
PROCEDURE DIVISION USING LS-CLAIM-ID LS-CLAIM-POLICY LS-RETURN-CODE. variable must match the size of the Calling
... Process data passed from CLAIMS ...
MOVE '-1' TO LS-RETURN-CODE program's variable - byte for byte

Parameters are passed - CALL 'XYZ' USING ….. BY:


• Reference (the default) - Through LINKAGE, the data items in the called program receives pointers to (addresses of) the
WORKING-STORAGE fields in the calling program. Changes made to data items defined in the called program's LINKAGE
SECTION will modify values in the calling program's WORKING-STORAGE

• CONTENT - Data Item values are passed and the called program cannot change the value of the calling
program's variable - referenced in the CALL statement’s USING parameters phrase.
• VALUE - Primarily used when calling non-COBOL the called program cannot change the value of this
parameter as referenced in the CALL statement’s USING phrase, 449
CALLED/CALLING Programs
Parameter Lengths

The LINKAGE SECTION variable declarations in the called subroutine referenced by USING:
• Must be 01-Level variable declarations
• Must match byte-for-byte with the WORKING-STORAGE variable lengths defined in the calling
program It's the length of each called/calling variable pair that's important - not the name, not the
type… the length.
• To z/OS, variable types are ignored when passed using CALL statements
• The Compiler and LINKAGE Editor will not catch length discrepancies
between Calling and Called programs
Why am I hitting this
• Differences between lengths often result in S0C4 ABENDS  "parameter stuff" so hard??
450
Link-Edit Requirements and the types of Subprogram Calls
1. Static Calls occur when you code: CALL 'SUB0O' in single or double-quotes. A copy of the
Compile/Linked version of the program is included in your load module at Link Edit time.
• Note that if the Linkage Editor cannot find the subroutine your program is Calling you will get an 8 or 12 Link Edit result
- which will not produce a Load Module

2. Dynamic Calls occur when you code: CALL WS-PROGRAM - where WS-PROGRAM is an 8-character
PIC X variable that contains the name of the module.
• A dynamically-called program is loaded (when Called) into an Address Space at runtime.
Just like SYSLIB for the compile step looks for Copybooks & Includes at Compile time, the Link Edit step
contains a //SYSLIB entry used to specify a list of libraries - that is
searched for dynamically called routines.
Library search order: 1. CEE.SCEELKED 2. TSOID.LEARN.LOAD

You must Compile/Link-Edit your programs from the lowest level upwards in calling sequence.
If PROG1 CALLS ➔ PROG2 CALLS ➔ PROG3 - You Compile/Link PROG3 … then … PROG2 … then … PROG1

Dynamic Calls: https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/concepts/cpsub04b.htm 451


Refactoring Production Batch Applications
1. The concept of implementing applications around a modular-design came along after several
generations of COBOL applications had been built - and maintained - and were supporting the
world's commerce.
2. Theoretically, there's no denying that a modular design is superior to large monolithic systems
so for the last 5-10 years companies have invested considerable resources looking to isolate
and extract business rules from COBOL systems - with limited success. Why?
• Many of the teams doing the work were not "deep" in the COBOL language - nor z/OS technology.
They missed key application nuances - and things predictably did not pan out
• These teams often came from distributed systems built using modern O-O Languages and structured
programming constructs. While it is certainly possible to achieve modern structured applications using
COBOL, few companies knew how to - or if they did, were willing to spend the money.
• VARIABLE-SCOPE: In Java/C++/Perl/etc. - even without an O-O implementation virtually all variables are local.
COBOL variables are 100% global in scope - and the impact of modifying a single field might take days-to-weeks to
Challenges

unravel…much less tracing and refactoring dozens to hundreds of variables


• SEMANTICS INTERWOVEN INTO PROGRAM FLOW: In 3GLs often the business rules are woven into the
procedural logic (PERFORM PARA-X 10 TIMES - where each iteration does some different business process). This
type of linear process is possible in O-O languages, but it is not common and certainly not considered a best
practice.
• SIZE: Individual COBOL programs consisting of over 30K lines-of-code are not uncommon. Programs have often
been "patched" with little to no commenting - making refactoring a daunting proposition.

3. Still, refactoring abides… So let's look at a simple example 452


Refactoring the Midterm Program - Step 1; Find a candidate for refactoring
• Initial candidates for refactoring COBOL business
rules into subroutines are often reusable, isolated
business rules, executed once or at most a few
times in a program, and without:
• U.I. Logic
• Database/File Logic
• GO TO - outside of the "perform chain" Logic

• In the Insurance Claim program turning 300-


COMPUTE-CLAIM into a subprogram might work ➔
• But note that you should consider refactoring the
310-COMPUTE-DEDUCTIBLE paragraph into its
own subprogram - if the deductible processing logic
is reusable in and of itself.
• Assuming you want to do this you first analyze the
code, and find the variables needed to Call both
subroutines ➔

453
IDENTIFICATION DIVISION. Refactoring the Midterm Program -
PROGRAM-ID. CMPCLAIM. *> Previously 300-COMPUTE-CLAIM
DATA DIVISION. Step 2; Create Subroutine(s)
WORKING-STORAGE SECTION.
LINKAGE SECTION. *> Used in the call from INSCLAIM • Assuming you've chosen to create two subprograms:
01 DEDUCTIBLE-LS PIC S9(5)V99.
01 POLICY-AMOUNT PIC S9(7)V99. • Create new COBOL library members
01 DEDUCTIBLE-PERC PIC V999. • Copy/Paste the paragraph code into each
01 POLICY-DEDUCTIBLE-MET-LS PIC X(1).
88 DEDUCTIBLE-MET VALUE 'Y'. • Create the LINKAGE SECTION and PROCEDURE DIVISION USING
01 POLICY-DEDUCTIBLE-PAID PIC S9(4). statements - for both the called and calling programs in the subroutine
01 CLAIM-PAID-LS PIC S9(7)V99. stack
01 POLICY-COINSURANCE PIC V99.
01 CLAIM-AMOUNT PIC S9(7)V99. • Create any additional logic or data items needed
01 PAY-THE-CLAIM-LS PIC X(1).
• Comment out the INSCLAIM paragraph code. Add a Call to CMPCLAIM
PROCEDURE DIVISION USING DEDUCTIBLE-LS, POLICY-AMOUNT
DEDUCTIBLE-PERC, POLICY-DEDUCTIBLE-MET-LS, USING all of the variables needed by both CMPCLAIM and DEDUCT
POLICY-DEDUCTIBLE-PAID CLAIM-PAID-LS, POLICY-COINSURANCE, • Compile/Link: DEDUCT … then … CMPCLAIM
CLAIM-AMOUNT, PAY-THE-CLAIM-LS.

CALL 'DEDUCT' USING DEDUCTIBLE-LS, POLICY-AMOUNT, IDENTIFICATION DIVISION.


DEDUCTIBLE-PERC, POLICY-DEDUCTIBLE-MET-LS PROGRAM-ID. DEDUCT. *> Previously 310-COMPUTE-DEDUCTIBLE
POLICY-DEDUCTIBLE-PAID. DATA DIVISION.
LINKAGE SECTION.
IF DEDUCTIBLE-MET 01 DEDUCTIBLE-LS PIC S9(5)V99.
COMPUTE CLAIM-PAID-LS ROUNDED = CLAIM-AMOUNT 01 POLICY-AMOUNT PIC S9(7)V99.
- (POLICY-COINSURANCE) *(CLAIM-AMOUNT) 01 DEDUCTIBLE-PERC PIC V999.
ELSE 01 POLICY-DEDUCTIBLE-MET-LS PIC X(1).
COMPUTE CLAIM-PAID-LS ROUNDED = CLAIM-AMOUNT 01 POLICY-DEDUCTIBLE-PAID PIC S9(4).
- DEDUCTIBLE-LS - (POLICY-COINSURANCE) *(CLAIM-AMOUNT) PROCEDURE DIVISION USING DEDUCTIBLE-LS, POLICY-AMOUNT,
END-IF DEDUCTIBLE-PERC, POLICY-DEDUCTIBLE-MET-LS
POLICY-DEDUCTIBLE-PAID.
SUBTRACT CLAIM-PAID-LS FROM POLICY-AMOUNT END-SUBTRACT MOVE .002 TO DEDUCTIBLE-PERC.
COMPUTE DEDUCTIBLE-LS ROUNDED =
IF POLICY-AMOUNT > ZERO POLICY-AMOUNT * DEDUCTIBLE-PERC
MOVE 'Y' TO PAY-THE-CLAIM-LS
ELSE IF POLICY-DEDUCTIBLE-PAID >= DEDUCTIBLE-LS
MOVE 'N' TO PAY-THE-CLAIM-LS MOVE "Y" TO POLICY-DEDUCTIBLE-MET-LS
END-IF. ELSE
GOBACK. MOVE "N" TO POLICY-DEDUCTIBLE-MET-LS
END-IF. 454
Refactoring the Midterm Program - Step 3;
Modify the original program logic
When the code for your subroutine
compiles/links it's time to:
• Modify the original monolithic program:
• Collect the names of the all variables to be
passed into the subroutines
• Call the subroutine(s)
• Comment out the original code
• Compile/Link the original monolithic
program that now calls your subroutin
• Test the new application by debugging it
455
Three-Tier Architecture
User Interface
1. U.I. 3270, Eclipse/Java,
iPhone, etc.
• Web, Java, 3270, iPhone

2. Middle-tier - Business Rules


• COBOL, PL/I, Assembler Business Logic Business Logic

3. Data -
• QSAM, VSAM, DL/I, DB2 QSAM VSAM DB2 DL/I

By isolating functionality (code) along three-tier architectural lines:


• The cost of development and maintenance drops
• The rate of modernization and transformation improves
• The quality of testing improves
Another explanation: https://www.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.base.doc/ae/covr_3-tier.html 456
457
COBOL Program Big Picture - Topics in Module 19
Identification Name the executable Program-ID. EBUD01.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE Control Break Logic
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK• WHEN
MVS Utility Sort
ZERO
• Internal COBOL Sort
IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields • COBOL Logic Pattern
Compound IF, Nested IF, EVALUATE COBOL Table Handling
Executable statements that
Signed Conditions, Class Conditions • Multi-Dimension Tables
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior • Variable Blocked Records
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure COBOL Table Handling
DISPLAY, GOBACK
• Concepts
Code Paragraph • Loading
PERFORM Paragraph UNTIL <condition> • Accessing
OPEN <Filename>, READ <Filename> AT END, WRITE, CLOSE <Filename> • Indexed by/Subscript
Calling Subprograms INITIALIZE • Single-Dim OCCURS
• Calling Protocol Counters, Accumulators, Flags
Table Search z/OS ABENDS
• LINKAGE Section Protocol Reference Modification, Figurative Constants • Sequential Search • Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation •
• Link-Edit Concerns COBOL String Handling Functions: UNSTRING, STRING
Binary Search • Safeguards
• DFSORT • Resolutions
• 3-Tier Architecture
COBOL Reusable Code Libraries
• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
 Nothing to hand in 458
Workshop 19.1a - Subprogram Concepts
MAINPGM
This will require you to compile/link and run the six programs
MOVE 'MAIN' TO A, B, C, D,
shown here. E, F, G, H, I, J, K, L, M

You will need to create Compile & Link only JCL file - minus CALL 'SUB01' USING A, B, C
the "GO" step from COBUCLD CALL WS-SUB02 USING H, I, J

• You can do this by simply deleting the lines from


GO to the end of the COBUCLD file -
and saving the file as: COMPLINK
ENTRY USING A, B, C ENTRY USING H, I, J
• And you'll need a separate JCL for SUB01 SUB02
just the GO step - in order to run the
MOVE 'SUB01' TO A, B, C, MOVE 'SUB02' TO H, I, J,
CALLING/CALLED programs D, E, F, G K, L, M

• You do this by deleting the Compile CALL 'SUB03' USING D, E, F


and Link-Edit steps CALL WS-SUB04 USING G CALL WS-SUB05 USING K, L, M

See next slides for steps/details…

ENTRY USING D, E, F ENTRY USING G ENTRY USING L, M, N


SUB03 SUB04 SUB05
MOVE 'SUB03' TO D, E, F. MOVE 'SUB04' TO G MOVE 'SUB05' TO K, L, M
GOBACK. GOBACK. GOBACK.
 Nothing to hand in

Workshop 19.1b - Steps and LINKAGE and WORKING-STORAGE Copybooks


You will need a separate compile/link
JCL file and a separate Run JCL file to
complete this assignment:
1. Create COMPLINK:
• Open COBUCLD and Save As…
COMPLINK.
• Edit COMPLINK and delete all of
the lines in the GO step - including
all //DD cards
• Save your work

2. Create DEBUGO
• Open COBUCLD and save it as
COMPLINK DEBUGO
Compile/Link (only) JCL • Edit DEBUGO and delete all of the
Compile & Link JCL statements
DEBUGO • Save your work
Go step + //DD cards for files 459
 Nothing to hand in
Workshop 19.1c - Detailed Steps
1. Create the Compile/Link standalone JCL - save it in your LEARN.JCL library

2. Compile/Link SUB01

3. COBUCLD MAINPGM (why COBUCLD???) - for TSO users - follow these steps
and do a debug of the Main Program

4. Debug MAINGPGM - it will call SUB01


• Monitor the sending parms
• When Debug enters SUB01 Monitor the USING parms
• Study the cause/effect between LINKAGE and WORKING-STORAGE when you're using
subprograms
5. Finish coding & debugging the rest of the Subroutines in this Workshop
• There's nothing to hand-in.
• But subprograms are everywhere in corporate COBOL jobs - and you must build your
working-knowledge of the nuances in Module 19
460
 Nothing to hand in

Workshop 19.1d - Tools and Techniques to Simplify Your Work

To simplify your work:


• Open multiple programs
simultaneously
• Go into full-screen mode
• Select and Drag the editor-
view-tabs to create a multi-
program "dashboard"

Note: If you're using IDz try the


Scan for Compatibility tool for
detecting Call/Calling
parameter mismatches.

461
 Nothing to hand in 462

Optional Workshop 19.2 - Another Series of Programs


Because subroutines are so ubiquitous in production work, do the following:
Open these four programs -- and read through them starting with EBUD1TST ➔ EBUD03
1. EBUD1TST
2. EBUD01
3. EBUD02
4. EBUD03

• What does each of them do?


• How is it done?
• Pay attention to EBUD03

Compile & Link all four


subroutines then Debug
EBUD1TST all the way through
to ➔ EBUD03
 Nothing to hand in

Optional/Advanced Workshop 19.3 - Three-Tier Architecture for INSCLAIM


• Using the code on the slides in this module
that describe the first and second steps of
refactoring the Midterm program:
• Make a copy of INSCLAIM
• Refactor the copy and change the
paragraph(s) that do computing
claims and deductible (Step1 and
 Step 2)
• Test your work

463
 Nothing to hand in

Optional/Advanced Workshop 19.3a - Three-Tier Architecture for INSCLAIM


Step 3 - Create a separate I/O routine for the INSCLAIM file:
• Pass the I/O routine a parameter named WS-ACTION - with values: OPEN, CLOSE, READ
• Remove the I/O operations - OPEN, READ, CLOSE (and Environment and DATA DIVISION entries)
from INSCLAIM for the CLAIM FILE. INSCLAIM.
...
• Call your I/O routine to handle the data file 300-OPEN-FILES.
operations. MOVE 'OP' TO CLAIMFILE-ST-WS.
CALL 'INSCLIO' USING CLAIM-RECORD-WS, CLAIMFILE-ST-WS.
• Pass a 90-Byte IO-Area (CLAIM-RECORD-WS) ...
400-READ-CLAIMS.
to hold the data read from CLAIM FILE MOVE 'RE' TO CLAIMFILE-ST-WS.
CALL 'INSCLIO' USING CLAIM-RECORD-WS, CLAIMFILE-ST-WS.
• Here's a Snippet showing what you could ...
WRITE PRINT-LINE FROM DETAIL-LINE
use as changes to INSCLAIM AFTER ADVANCING 2 LINES
ADD 1 TO LINE-COUNT.
...
900-WRAP-UP.
You will need to Compile/Link the IO-Routine before CLOSE PRINTFILE.
Compiling/Linking the INSCLAIM program. MOVE 'CL' TO CLAIMFILE-ST-WS.
CALL 'INSCLIO' USING CLAIM-RECORD-WS, CLAIMFILE-ST-WS.

1. Create/Compile/Link the IO-Routine (next slide). Then Modify/Compile/Link/Debug the INSCLAIM program
and its IO-Routine (INSCLIO) as shown here. Validate the Three-Tier Architecture approach to INSCLAIM
2. When you're satisfied that this works - add logic to INSCLIO that removes the OPEN/WRITE/CLOSE I/O
processing from INSCLAIM and into INSCLIO. 464
 Nothing to hand in 465

Optional/Advanced Workshop 19.3b - I/O Module Code


IDENTIFICATION DIVISION. PROCEDURE DIVISION USING IO-AREA, CLAIMFILE-ST-LS.
PROGRAM-ID. INSCLIO. MOVE CLAIMFILE-ST-LS TO CLAIMFILE-ST-WS.
ENVIRONMENT DIVISION. PERFORM 100-PROCESSING.
INPUT-OUTPUT SECTION. GOBACK.
FILE-CONTROL.
SELECT CLAIMFILE 100-PROCESSING.
ASSIGN TO UT-S-CLAIM EVALUATE TRUE
ORGANIZATION IS SEQUENTIAL WHEN OPEN-FILE
FILE STATUS IS CLAIMFILE-ST-WS. PERFORM 300-OPEN-FILE
DATA DIVISION. WHEN READ-FILE
FILE SECTION. PERFORM 400-READ-FILE
FD CLAIMFILE WHEN CLOSE-FILE
RECORD CONTAINS 90 CHARACTERS. PERFORM 500-CLOSE-FILE
01 CLAIM-RECORD PIC X(90). END-EVALUATE.
*
WORKING-STORAGE SECTION. 300-OPEN-FILE.
01 MISC-FIELDS. OPEN INPUT CLAIMFILE
05 CLAIMFILE-ST-WS PIC X(02). IF NOT CLAIMFILE-OK
88 OPEN-FILE VALUE 'OP'. DISPLAY 'CLAIM FILE PROBLEM'.
88 READ-FILE VALUE 'RE'. *
88 CLOSE-FILE VALUE 'CL'. 400-READ-FILE.
88 CLAIMFILE-OK VALUE '00'. READ CLAIMFILE INTO CLAIM-RECORD-WS
05 CLAIMFILE-EOF PIC X(01). AT END
88 NO-MORE-CLAIMS VALUE 'Y'. MOVE "Y" TO CLAIMFILE-EOF
END-READ.
IF CLAIMFILE-OK OR NO-MORE-CLAIMS
LINKAGE SECTION. MOVE '00' TO CLAIMFILE-ST-WS
01 CLAIM-RECORD-WS PIC X(90). ELSE
01 IO-AREA REDEFINES CLAIM-RECORD-WS PIC X(90). DISPLAY 'CLAIM FILE PROBLEM'.
01 CLAIMFILE-ST-LS PIC X(02). 500-CLOSE-FILE.
CLOSE CLAIMFILE.
** 120-Minute Session **

UNIT COBOL for z/OS - Module 20


Using ISPF for COBOL Development
o Terms, Concepts and Navigation
o PF-Keys and Setup (Option 0 entries)
o Editing and Browsing source files
▪ File navigation and paging
▪ Command Line Commands
▪ Prefix Are Commands
▪ Split screen,
▪ Hex On
o 3270 Control Keys
o Data Set Utilities
IBM TSO/ISPF Tutorials:
https://www.ibm.com/support/knowledgecenter/SSLTBW_2.1.0/com.ibm.zos.v2r1.f54em00/elc.htm
https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.f54em00/ispem11.htm
https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zcourses/zcourses_ispfintro.htm
https://www.youtube.com/watch?v=vrCqIaB_23U&t=2s 466
467
COBOL Program Big Picture - Topics in Module 20
Identification Name the executable Program-ID. EBUD01.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Calling Subprograms
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values • Calling Protocol
REDEFINES • LINKAGE Protocol
Variable declarations - Fields 88 Named condition • Link-Edit Concerns
that contain values to be Signed Numeric PIC • 3-Tier Architecture
FILLER
Data processed in the program's VALUE Control Break Logic
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK• WHEN MVS Utility Sort
ZERO
• Internal COBOL Sort
• COBOL Logic Pattern
IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields
Compound IF, Nested IF, EVALUATE COBOL Table Handling
Executable statements that
Signed Conditions, Class Conditions • Multi-Dimension Tables
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior • Variable Blocked Records
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure COBOL Table Handling
DISPLAY, GOBACK
• Concepts
TSO/ISPF Code Paragraph
PERFORM Paragraph UNTIL <condition>
• Loading
• Accessing
• The Panels OPEN <Filename>, READ <Filename> AT END, WRITE, CLOSE <Filename> • Indexed by/Subscript
• Navigation INITIALIZE • Single-Dim OCCURS
Counters, Accumulators, Flags
• TSO Commands Reference Modification, Figurative Constants
Table Search z/OS ABENDS
• Sequential Search • Understanding
• Edit & Browse Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Binary Search • Safeguards
• Command Line COBOL String Handling Functions: UNSTRING, STRING • DFSORT • Resolutions
Prefix Area
COBOL Reusable Code Libraries
• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
468
TSO/ISPF
• TSO
• Time Sharing Option

• ISPF
• Interactive System Programming/Productivity Facility ISPF
• Tools for COBOL Business Application Development
• Alternative to IDz/VS Code/ZOE
TSO
• 3270-Data Stream based
• G.A. 46 years ago
z/OS
ISPF runs on TSO runs on z/OS.
• Integrates with: The different systems software layers
• SCM tooling provide different services to users.
• DB2 tooling
• Compilers/Link-Editors/Debuggers
• Data File Editors
• Custom in-house tools and 3rd Party Tools:
• Build
• Code standards
• SDLC workflow
TSO/ISPF
ISPF Primary Option
Menu

=0
Setup/Configuration Hierarchical Collection of panels
=4 =5 =6
=1 =2 =3 =7 Customized
Foreground Background CLIST/REXX
Browse/View Edit Data Set Utilities Compile/Link ISPF Dialog Manager ISPF Menu Options
Compile/Link Commands

Allocate
Copy
• Navigation among panels using:
Rename… • PF-Keys
• Command Line Commands
Search
• =4 and =5 are rarely utilized
Compare
• Typically replaced by custom "Build Procs"
• Shops have created custom Build using either panels or
List of Data Sets CLIST/REXX front-ends to JCL
DSLIST
• =7 (typically) only used by systems developers
• z/OS Source Management tools (installed as ISPF Dialogs)
control access to Programs and Copybooks
469
ISPF - Tools, Development Scenarios and Use Cases
1. Setup Defaults =0 5. Working with Data Sets =3
• Log List • File Allocate = 3.2
• PF Keys • File Copy = 3.3
• DSList = 3.4
2. ISPF/Panel navigation
• Outlist = 3.8
• Command line
• Data Set Compare =3.12
• Stacking commands
• SearchFor = 3.14
• PF3 (the "right-mouse button" of ISPF)
6. Executing TSO Command = 6
3. View files =1
• REXX/CLIST
• Dialog navigation • TSO Commands
• Command line commands
7. 3270 Control Keys
• PF-Keys
• Attention
4. Edit files =2 • SysRequest
• Command line commands • EOF
• Prefix area commands

470
Telnet Screen
• Lists Systems
Software
("Applications")
available on the
LPAR you're
connecting to,
using an:
• I/P Address
• Port#

• Every shop will


have a unique set
of Systems TSO
Software,
environments • The zserveros "development" LPAR
available products • Systems Software available
and tools
• To RACF authorized users
• Some shops still • Multiple test environments for:
call this the 'VTAM
Screen' • CICS
• IMS
471
Login Process
• Different from shop-to-shop
• Besides logging in you can change:
• Password
• Logon Proc

• Control key is <Enter>


• This is 3270-emulator
specific

A Logon Proc establishes your personal development space on an LPAR


• Tools available Like an Eclipse Workspace!
• Data Sets available
• Authorizations
• Virtual Storage size for the Address Space your TSO session will be loaded into
472
ISPF - Primary Option Menu
• Displays ISPF tooling
as menu options

• You will se dialogs that


exist for you - given
your Logon Proc

• Where to get the tools:


• Navigation to ISPF
Dialog functionality
 An ISPF Dialog is
like an Eclipse View Every shop's ISPF menus, dialogs, tools and process are unique
• Between all z/OS shops worldwide
• Often even within a single large company

This stick-figure shows up if you type on a dialog


where you're not supposed to. Press the Attn key 473
ISPF - Navigation Options and Techniques
From the menu options: 2 =3.4 save;sub;=3.8
Option ===> _______________________________
Option/Command line: • Navigation to the panels where the tools exist:
• =n or =n.x
• Also allows you to run an interactive TSO Command -
• =x or PF3 - Close the dialog
prefixed by: TSO
• TSO command;command;=n
• Can "stack" command line commands ;

From the ISPF dialogs:


• Tab key is your scroll bar
• Mouse also works to navigate within a panel
• Up/Down/Left/Right Arrows are functional
• =n navigation - Must prefix with = sign
• =n.n

3270 Control Keys:


• PF3 ➔ Back or "up" one dialog
• Enter ➔ "Double-click"
474
ISPF =0
Configure ISPF:
• Personalized options stored in
Login Proc library on z/OS
• Primarily used for:
• PF-KEY customization
• Log/List defaults

• Position cursor on Underscore


and press <Enter>

Almost always Delete Log/List Data Sets

Standard Defaults
Some also like: PF4 . . . CANCEL

475
ISPF =1 1.

View** or Browse Files:


Leave blank for all members
Analyze:
• Programs, JCL, Copybooks
• Data Sets 2. You can fully-qualify DSNs
(with apostrophes) or leave
• To find a file to browse: out the high-level qualifier
1.
• Use the ISPF Library option (if it's your TSO-ID)
2.
• Browse a Sequential data set or other library

** "View" allows you to edit but doesn't lock the file. You must Save As to persist source changes 476
ISPF =1 View or Browse Files Command Line Commands ===> 477
• Navigation
PF-KEYS: • Top … Bottom of file
• F7 / F8 Up/Down Paging size • L nnn … Locate Line Number
• m F7 / m F8 Top/Bottom • Find: F Prev
• n F7 / n F8 # lines up/# lines down • M(ax): PF7, PF8
• F10 / F11 = Right/Left • File changes:
• F3 • Cancel, Save
• F2 / F9 Split/Swap • Snippets:
• F5 Find/Repeat Find • Copy from member / fully-qualified PDS(member)
• F3 End/Exit dialog • Create to member / fully-qualified PDS(member)
• Ancillary:
•  Enter -Activates Command Line Commands • RES - Reset ISPF data set/editing display
• Profile - ISPF options in effect for browsed/edited member
Paging/Scrolling: • X nnn/X all - Exclude lines
• Page • Stack Command Line Commands ;
• Half • PFSHOW
• Csr • Hex on/Hex off
• Caps On/Caps Off
Notes: • Bounds/Bnds
• PC Nav Keys do not work • Hilite On/Off
• There are many Edit/Browse techniques featured in the
lesson recording - that are not in these slides
• F —Show the First Line(s)/L - Last Line(s) of excluded records
ISPF =2 Edit Files Prefix Area Commands ===>
• ( — Column Shift Left
Same U.I. as =1 and many • ) — Column Shift Right
functional similarities: • < — Data Shift Left
• > — Data Shift Right
PF-KEYS: • A — Specify an After destination for Move/Copy
• F5/F6 - Selective Find/Change • B — Specify an After destination for Move/Copy
• F3 - End/Save • BOUNDS — Define Boundary Columns for action (F, C, etc.)
• F4 - Cancel changes/Leave • C/CC — Copy Lines
• F7/F8/F10/F11 - Set Paging: • COLS — Identify Column numbers across the screen
• D/DD — Delete Lines
• Page
• I — Insert Lines
• Half
• L / F — Show the Last / First n Excluded Line(s)
• Csr
• LC/UC - Convert Chars to Lower/Uppercase
• M/MM — Move Line/Move block of lines
Command Line Commands: • O — Overlay Lines
• Cut/Copy/Paste - to clipboard • R/RR — Repeat Line/Repeat block of lines
• Change • S — Show Lines
• Caps On/Off • TABS — Control Tabs
• Undo • TE — Text Entry
• Bounds/Bnds • TS — Text Split
• Rec(overy) On/Off • X/XX — Exclude Line/Exclude block of lines
• Autosave 478
ISPF =3
Data Set Utilities:
• Self-descriptive options
• Dslist probably the most
common tool for accessing
ALL files - for browse & edit
• Workflow is often multiple
dialogs:
• Specify File-1 & options
• Specify File-2 & options

• Outlist is an alternative to
SDSF for JES listings
• Often this panel will contain
custom (in-house) entries
• Usage includes:
• Run in foreground - Immediate (and more expensive) execution of utility
• Run in batch - Submit job to execute utility - note that you will need a Job Card

479
ISPF =3.1, 3.2, 3.2 - Working with files
3.1
• Work with a specific library
• Compress PDS

3.2 3.1
• Allocate space
• Delete
• Rename

3.3
• Copy PDS or Sequential Data Set
• Two-part dialog
3.2

3.3 - Part 2 3.3 - Part 1 480


ISPF =3.4 DSList - 1 of 3
3.4 == IDz/ZOD Remote Systems view
• Enter File or Library name:
• Partial or fully-qualified DSN
• No apostrophes

Actions member list:


• Edit - opens member list
• D - Delete: Entire data set
 D - Can delete at the member level
 C - Copy
• S - Short statistics

481
=3.4 DSList 2 of 3 - Sort on Last Modified
From 3.4
• Can sort the 3.4 member
list on a number of list
columns:
• Size
• Cha - last modified
• Cre

482
ISPF =3.8 - Outlist
Alternative to SDSF
Requires:
• JOBNAME
• MSGCLASS
• JOBID
• Wildcards work
• Use tso st Command Line
Command to obtain

From in spool file:


• Basically =1 (browse)
• Nav techniques
• PF-keys
• (include PF10/PF11)
• M PF
• L line#
• F important tool

483
ISPF =3.12 - SuperC - 1 of 3
Compare contents of files:
• Libraries
• Data Sets
• Library Members

Four-part dialog
1. Specify "to" data set <Enter>
2. Specify "from" data set
• Also specify different
types of listing results

Note that if you are


using zTrial your TSO
ID will be IBMUSER

484
ISPF =3.12 - SuperC - 2 of 3
If Batch execution:
3. Specify batch job characteristics
4. Creates a temp JCL file
• TSOID.SPFTEMPn.CNTL
• SUB from command line

485
ISPF =3.12 - SuperC - 3 of 3
When job finishes go to SDSF or Outlist (3.8) to view the compare results
• Often useful to print utility output
• Or change your session U.I. settings
• 27X132

486
ISPF =3.12 - SrchFor
Search through Data Set:
• Library/PDS
• Sequential file
• VSAM file
Specify:
• Search string
• File Name
• Output file data set
- ISPF will Allocate
• Run job in:
- Batch
- TSO Foreground

487
ISPF =6 - Command Shell
A panel for running
"commands" in the
TSO foreground:
• TSO Commands
• Press F1 to list them

• REXX Commands
• An important interactive
language for doing lots of
different TSO/ISPF work:
• Creating tools
• Running "applets"
• Parsing text
• Setting up
environments
• Running Jobs Can re-run an existing command (shown on the panel) by setting your
• CLISTs mouse focus on the command and pressing <Enter>
• The previous decades'
version of REXX
TSO Commands = DOS Commands
REXX/CLISTs = .BAT files or Unix shell scripts
• Still lots of them hanging 488
around
IDz - TSO Host Connection Emulation (HCE)
• Right-click over an RSE option
• From the Context Menu select Host Connection Emulator
• Select your mainframe application; TSO, IMS, CICS, etc.
• Login – as per normal

489
IDz - Customizing your Host Connection Properties
From the Host
Properties tab, you
can change the
following settings:
• Screen size
• LU name
• For CICS and IMS
testing
• Code page
• Connection timeout
• Security

490
IDz - Connect to a Second LPAR from HCE
• From the Window menu:

491
IDz - Hide/Show Keypad – for 3270 Control Keys
• Use the two icons on the bottom/right-hand side of the window, to:
• Hide the PF-Key Pad
• Show the PF-Key Pad

492
IDz - Defining Custom Control Keys

• IDz “Preferences” for mapping


the right and/or left Control (Ctrl)
keys to 3270 keypad function

Optional Workshop
1. From Window > Preferences
2. Type Host C in the edit area (top left)
3. From Host Connection Control Keys map either the
left or right Ctrl key to any of the options in the
drop-down box
4. Click OK
5. Test your new control key mappings
493
494
COBOL Program Big Picture - Topics in Module 20
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
INITIALIZE
Counters, Accumulators, Flags
z/OS ABENDS
Reference Modification, Figurative Constants • Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Safeguards
COBOL String Handling Functions: UNSTRING, STRING • Resolutions

COBOL Reusable Code Libraries


• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
ADFz - zTrial - Access to IDz EE, File Manager, DB2 and ISPF
From: https://www.ibm.com/account/reg/us-en/signup?formid=urx-30291
Register for zTrial. You will receive a link, uid, pwd in a few hours

Click the link, and when zTrial opens, click this icon on the bottom toolbar:
Be patient - this is a cloud-based, virtual product

Logon with: IBMUSER / SYS1


You have access to all of IDz EE now

Right-click on zos_dev, and select: Host Connection Emulation

From the VTAM screen connect with ➔


LOGON IBMUSER

Respond to the HCE password request with: SYS1


Hit <Enter> to scroll past the broadcast messages
495
** 90-Minute Session **

UNIT COBOL for z/OS - Module 21


DB2 - COBOL/Embedded SQL
• The Relational Model
• Interactive SQL
Learning Links • Embedded SQL
z/OS DB2 PDF from IBM • EXEC SQL API Syntax
Tutorial - Current Features: https://www.db2tutorial.com/
• Prep
Overview: https://www.youtube.com/watch?v=aMnBCOq9qrk
Glossary of terms https://mariadb.com/kb/en/relational-databases-basic-terms/
• Testing
COBOL/DB2: https://www.youtube.com/watch?v=dOdSTq5Gjpg
SQL Error Codes: https://www.ibm.com/support/knowledgecenter/SSEPEK_11.0.0/codes/src/tpc/db2z_n.html
Brilliant SQL Tutorial: https://www.youtube.com/watch?v=bEtnYWuo2Bw
Built-in-Functions ttps://www.ibm.com/support/knowledgecenter/en/SSEPEK_11.0.0/sqlref/src/tpc/db2z_sqlfunctionslist.html
In-Depth SQL Course: https://www.khanacademy.org/computing/computer-programming/sql/sql-basics/v/welcome-to-sql
496
Topics
• DB2 and the Relational Model
• The Elements of DB2
• Architecture
• Data Objects
• DB2 Catalog
• Tables

• DB2 Development Tools


• DB2I/SPUFI
• IDz

• Accessing information in DB2 Tables - SQL/DML


• All rows/All columns - All rows//Some columns - Some rows/All columns - Some rows/Some columns
• SQL Predicates
• Derived Column Values
• Table Joins

• Accessing DB2 from COBOL


• APIs
• Singleton Select, Set-Level Select Statements
• Update/Delete/Insert
• DCLGEN
• Build 497
The Relational Database Model - Discussion
Q. What is the difference between a TSO/Sequential file and a database?
A. TSO files store data. A database stores data and also stores the relationships among the data
Unlike all the File & DBMS models prior to the early 1970s, such as DL/I, IDMS, VSAM, Model 204, ADABAS etc.
DB2's "relational model" is based completely on tables consisting of relationships and search paths based on
run-time value/conditional expressions - instead of hardwired pointers. What on earth does that mean?
DL/I databases model business data using a static (pointer-based) hierarchical model - with a single top-level
entry point and specific rules used to navigate the hierarchy - in COBOL. When business requirements change
the cost of modifying the database structure and all the code that supports the specific hierarchy is huge.
IDMS hoped that its network or Codasyl model would provide more flexibility by providing multiple paths through
the data. This was the case initially, but IDMS databases became unwieldy to support and over-time enterprise
IDMS applications fell out of favor.
While both DL/I, IDMS and all older DBMSs utilized hardwired pointers to maintain the relationships among the
entities, relational Databases use only paired values to both store "relationships among the data" and to access
the data. This makes the relational model simultaneously far more flexible and operationally slower than the
pointer-based systems it replaced. DB2 is IBM's implementation/product based on the relational model of data

The Relational Model: https://mariadb.com/kb/en/understanding-the-relational-database-model/


https://en.wikipedia.org/wiki/Relational_model 498
Overview
DB2 is a relational DBMS (Data Base Management System)
A relational database is a database in which all the data is **logically contained
in tables.

DB2 Tables

** DB2 data is physically contained in VSAM files 499


500
Elements of DB2 - Relational Tables
A DB2 (relational) table is a collection of rows and columns organized around a primary key
• EMPNO ➔ Primary Key - Unique value within the table. Armed with a Primary Key value I can find its row in a table
• LASTNAME ➔ Column
Columns - Column Data type and size

R
O
W
S
Elements of DB2 - Architecture
QMF
Eclipse tools interacts with DB2 resources DB2I CICS
SPUFI
through a JDBC driver

DB2
Client Software Utilities
IDz/ZOD/3270

z/OS Call
Attach
• LOCATION/PORT#

TSO
DB2 System Thread
Batch

DB2 IMS TM
Runtime
BUFFER
DASD IMS Thread: Control Structure used
POOLS
Batch to communicate requests to DB2
as well as send/receive data
Elements of DB2 - Data Objects

z/OS
• LOCATION/PORT# STOGROUP
VSAM
DB2 System DATABASE**

TABLESPACE
Access to DB2 Tables is defined in
the DB2 Catalog using DBA Grant
statements – not RACF VIEW TABLE INDEX
DB2 Catalog ALIAS
• Grant/Privileges
• Meta-Data SYNONYM COLUMN
We strongly recommend that you pick up
a DB2 book if you're seriously interested
in COBOL/DB2. You can't go wrong with DB2 Libraries
• SDSNLOAD
authors like Craig Mullins or publishers
• PROCLIB
like Mike Murach. • RUNLIB.LOAD
**A DB2 Database is a logical - not physical structure
503
Elements of DB2 - Create Table Statement
CREATE TABLE DSN81110.EMP (  Schema.Table_Name: Schema = TSOID of table creator
EMPNO CHAR(6) NOT NULL,  Primary Key: Column(s) whose values uniquely identify all rows
FIRSTNME VARCHAR(12) NOT NULL,  Column(s): Column Name Type(size) Null specifier
MIDINIT CHAR(1) NOT NULL,
LASTNAME VARCHAR(15) NOT NULL, The DB2 DCLGEN utility creates a COBOL record-layout
based on the DB2 CREATE TABLE statement.
WORKDEPT CHAR(3) ,
PHONENO CHAR(4) ,
HIREDATE DATE ,
JOB CHAR(8) ,
EDLEVEL SMALLINT ,
SEX CHAR(1) ,
BIRTHDATE DATE ,
SALARY DECIMAL(9 , 2) ,
BONUS DECIMAL(9 , 2) ,
COMM DECIMAL(9 , 2) )
504
Elements of DB2 - DB2 Catalog
DB2 maintains a set of tables that contain metadata about the data that DB2 controls. These tables are collectively known
as the DB2 catalog. The catalog and its tables contain information about DB2 objects; Tables, Views, and Indexes.
When you create, alter, or drop an object, DB2 inserts, updates, or deletes
rows of the catalog that describe the object.

The DB2 catalog consists of tables of data about everything defined to


the DB2 system, including table spaces, indexes, tables, copies of table STOGROUP
spaces and indexes, and storage groups.
DATABASE

TABLESPACE

VIEW TABLE INDEX


ALIAS
SYNONYM COLUMN
505
Elements of DB2 - DB2 Data Types
Like COBOL variables, every column in every Db2 table has a data type. The data type influences the range of
values that the column can have and the set of operators and functions that apply to it.

You specify the data type of each column at the time that you create the table. Using ALTER TABLE - you can
change the data type of a table column. The new data type definition is applied to all data in the associated table
when the table is reorganized (a DB2 Utility)
SQL Development Tools -
DB2I/SPUFI - 1 of 2

SQL Processor Using File Input

 File of interactive SQL statements

 QSAM file for SQL results

 SPUFI workflow-settings

https://www.ibm.com/support/knowledgecenter/SSEPEK_10.0.0/apsg/src/tpc/db2z_executesqlspufi.html 506
507
SQL Development Tools -
DB2I/SPUFI - 2 of 2
 Interactive SQL

 Interactive SQL

Press F3 ➔

Browse Results in Output File ➔


508
IDz - Data Tools and the Data Explorer View
Add the Data Explorer view to the z/OS Projects perspective, so that you can add DB2 connections
and execute SQL statements

Window
Show View ➔ Other…
Data Source Explorer ➔

Explore the IDz's DB2/SQL functionality in Module 8


The IDz Tools Training: https://community.ibm.com/community/user/ibmz-and-linuxone/viewdocument/pdfs-for-the-entry-level-training-m?CommunityKey=b0dae4a8-74eb-44ac-86c7-90f3cd32909a&tab=librarydocuments
509
IDz - Connecting to DB2
From the Data Source Explorer – select New Connection Profile

• Select: DB2 for z/OS as the database manager


• Enter Properties:
• Location:
• TCP/IP Location name of the DB2 Server on
z/OS (get values from DBA)
• Host:
• IP Address of the z/OS mainframe
• Port number:
• For DB2 on z/OS Note that connection values
to your DB2 system will be
• Do NOT check: completely different
• Retrieve objects created
by this user only
• User name/Password:
• Required – or use Single sign-on
▪ Click Test Connection, and if successful, Click Finish
▪ Then from the Data Source Explorer view ➔
▪ Right-click on the Location
▪ Select New SQL Script
Location
510
Elements of DB2 - Interactive SQL - DML Statements
SELECT <COLUMNS> INSERT <COLUMNS> UPDATE <SCHEMA.TABLE>
FROM <SCHEMA.TABLES> INTO <SCHEMA.TABLE> SET <COLUMN> = <VALUE>
WHERE <CONDITIONS>
ORDER BY <SORT_COLUMNS> DELETE FROM <SCHEMA.TABLE)
WHERE <CONDITIONS>

SQL Links:
Brilliant SQL Tutorial: https://www.youtube.com/watch?v=bEtnYWuo2Bw
In-Depth SQL Course: https://www.khanacademy.org/computing/computer-programming/sql/sql-basics/v/welcome-to-sql
511
SQL Select - All Rows/All Columns
Select * from DSN81110.EMP;

All Columns
512
SQL Select - SELECT All Rows/Some Columns
SELECT WORKDEPT, FIRSTNME, LASTNAME, JOB, PHONENO, SALARY
FROM DSN81110.EMP
ORDER BY WORKDEPT

Column subset
of the table ➔
513
SQL Select - SELECT Some Rows/All Columns
SELECT *
FROM DSN81110.EMP
WHERE JOB IN ('DESIGNER', 'SALESREP') AND SALARY > 24000
ORDER BY JOB, SALARY
Row Subset
514
SQL Select - SELECT Some Rows/Some Columns
SELECT JOB, SALARY, WORKDEPT, LASTNAME, PHONENO
FROM DSN81110.EMP
WHERE JOB IN ('DESIGNER', 'SALESREP') AND SALARY > 24000
ORDER BY JOB, SALARY

Column subset
Row Subset
515
SQL Select - Additional WHERE Options and Predicates

Comparison operators

WHERE clause predicates


516
SQL Select - Derived Column Data
SELECT WORKDEPT AS DEPARTMENT, DEC(AVG((SALARY + BONUS + COMM)), 9, 2) AS "Average",
DEC(MAX((SALARY + BONUS + COMM)), 9, 2) AS "Maximum", DEC(MIN((SALARY + BONUS + COMM)), 9, 2) AS "Minimum",
DEC(SUM((SALARY + BONUS + COMM)), 9, 2) AS "Sum"
FROM DSN81110.EMP
GROUP BY WORKDEPT 1. Code & Run Query

2. Export All Results

4. Once in the land of Excel, format the


cells, and create a graph of the data

3. To a CSV file
SQL Select - Table Joins
SELECT D.DEPTNAME, E.LASTNAME, E.PHONENO
FROM DSN81110.DEPT D, DSN81110.EMP E
WHERE D.DEPTNO = E.WORKDEPT Primary Key
ORDER BY 2 Table Join Condition 
Foreign Key

You will need one join condition for every pair of


tables you wish to access with an SQL join statement
517
SQL Select - Join 3 Tables
SELECT D.DEPTNAME, E.LASTNAME, EP.ACTNO, EP.EMSTDATE, EP.EMENDATE
FROM DSN81110.EMP AS E, DSN81110.EMPPROJACT AS EP, DSN81110.DEPT AS D
WHERE E.WORKDEPT = D.DEPTNO AND E.EMPNO = EP.EMPNO AND E.LASTNAME = 'VORHEES'

Primary Key

Foreign Key

Primary Key

Foreign Key

Coding correct DB2/SQL joins requires you to match the


correct primary/foreign key relationships in the WHERE
clause. A two-table join requires one join condition.
A three-table join requires two join conditions, etc.
518
SELECT JOB,
SQL SELECT - Additional Samples SUM(CASE WHEN WORKDEPT = 'A00' THEN 1 ELSE 0 END) AS A00,
SUM(CASE WHEN WORKDEPT = 'B01' THEN 1 ELSE 0 END) AS B01,
SELECT WORKDEPT, AVG(SALARY) SUM(CASE WHEN WORKDEPT = 'C01' THEN 1 ELSE 0 END) AS C01,
FROM DSN8C10.EMP SUM(CASE WHEN WORKDEPT = 'D11' THEN 1 ELSE 0 END) AS D11,
SUM(CASE WHEN WORKDEPT = 'D21' THEN 1 ELSE 0 END) AS D21,
GROUP BY WORKDEPT SUM(CASE WHEN WORKDEPT = 'E01' THEN 1 ELSE 0 END) AS E01,
ORDER BY 2; SUM(CASE WHEN WORKDEPT = 'E11' THEN 1 ELSE 0 END) AS E11,
SUM(CASE WHEN WORKDEPT = 'E21' THEN 1 ELSE 0 END) AS E21
FROM EMP GROUP BY JOB;
SELECT WORKDEPT, JOB, SALARY
FROM EMP
WHERE JOB = 'MANAGER' SELECT 'ACCOUNTING', E.DEPT, E.PERF, E.PERF, E.PERF,
UNION ALL P.HOURS, P.HOURS, P.HOURS
FROM DDS0001.EMPL AS E, DDS0001.PAY AS P
SELECT WORKDEPT, JOB, SALARY WHERE E.NBR = P.NBR AND E.DEPT = 'ACC'
FROM EMP UNION
WHERE SALARY > 30000; SELECT 'ACCOUNTING, FIN',E.DEPT, E.PERF, E.PERF,
E.PERF, P.HOURS, P.HOURS, P.HOURS
FROM DDS0001.EMPL AS E, DDS0001.PAY AS P
SELECT WORKDEPT, JOB, SALARY WHERE E.NBR = P.NBR AND E.DEPT IN ('ACC','FIN')
FROM EMP UNION
WHERE JOB = 'MANAGER' SELECT 'ACCOUNTING, FIN, MKT',E.DEPT, E.PERF, E.PERF,
UNION E.PERF, P.HOURS, P.HOURS, P.HOURS
FROM DDS0001.EMPL AS E, DDS0001.PAY AS P
SELECT WORKDEPT, JOB, SALARY WHERE E.NBR = P.NBR AND E.DEPT IN ('ACC','FIN','MKT')
FROM EMP UNION
WHERE SALARY > 30000 SELECT 'PROBLEM DEPARTMENTS',E.DEPT, E.PERF, E.PERF,
ORDER BY 3 DESC; E.PERF, E.PERF, E.PERF, E.PERF
FROM DDS0001.EMPL E
WHERE NOT EXISTS
(SELECT * FROM DDS0001.PAY P WHERE E.NBR = P.NBR)
519 ORDER BY 1;
520
SQL Examples - UPDATE, DELETE, INSERT
INSERT INTO DSN8B10.EMP
DELETE VALUES
FROM PAYROLL ('000205','MARY','T','SMITH','D11','2866',
WHERE RATE <= 52 AND '1981-08-10','ANALYST',16,'F','1956-05-22',
DED >= 23 AND 16345,500,2300);
HOURS = 40;
INSERT INTO SMITH.TEMPEMPL
SELECT *
UPDATE PAYROLL FROM DSN8B10.EMP;
SET RATE = 42
WHERE NBR = 'AAAAAAAA';
INSERT INTO SESSION.TEMPEMPL
SELECT *
FROM DSN8B10.EMP
WHERE WORKDEPT='D11'

Do not run the above queries against the zserveros DB2 Tables
Accessing DB2 from COBOL - Embedded SQL
Embedded SQL statements:
• Can be coded in the A or B margin
• Begin with EXEC SQL
• Are terminated with END-EXEC

Operational Embedded SQL statements must be


coded in the PROCEDURE DIVISION
• OPEN CURSOR
• FETCH
• CLOSE CURSOR
• Singleton SQL Statements

Non-operational SQL statements should be


coded in WORKING-STORAGE. They include;
• DECLARE CURSOR
• INCLUDE <copybook>

521
Elements and Infrastructure - Non-operational SQL Statements
DATA DIVISION.

WORKING-STORAGE SECTION EXEC SQL INCLUDE PAYROLL END-EXEC.
• DCLGEN copybook

EXEC SQL INCLUDE SQLCA END-EXEC.


• IBM z/OS DB2 standard structure (collection of variables) -
updated by DB2 after each SQL statement.
• Similar to the File Status indicator for QSAM/VSAM I/O

EXEC SQL DECLARE <CURSORNAME> CURSOR… END-EXEC.


• A Cursor is a defined pointer control that allows 3GLs such
as COBOL, PL/I and Assembler - scroll through a "result
set" of rows from the successful execution of an
Embedded SQL statement
… • The DECLARE Cursor statement defines and names a
PROCEDURE DIVISION.
unique Cursor - as well as assigning an SQL statement to it

522
01 SQLCA. 05 SQLCAID PIC X(8).
Embedded SQL Infrastructure - SQLCA 05 SQLCABC PIC S9(9) BINARY.
05 SQLCODE PIC S9(9) BINARY.
In WORKING-STORAGE you code: EXEC SQL INCLUDE SQLCA END-EXEC - 05 SQLERRM.
to check whether your statement executed successfully. 49 SQLERRML PIC S9(4) BINARY.
This is almost exactly like the FILE-STATUS language element 49 SQLERRMC PIC X(70).
05 SQLERRP PIC X(8).
05 SQLERRD OCCURS 6 TIMES
In the PROCEDURE DIVISION check (IF SQLCODE < 0) the SQLCODE after
PIC S9(9) BINARY.
each operational embedded SQL statement. 05 SQLWARN.
10 SQLWARN0 PIC X.
SQLCODE Values 10 SQLWARN1 PIC X.
• 0 ➔ SQL statement execution was successful 10 SQLWARN2 PIC X.
10 SQLWARN3 PIC X.
10 SQLWARN4 PIC X.
• +100 ➔ Row Not Found … or no more rows for a FETCH 10 SQLWARN5 PIC X.
10 SQLWARN6 PIC X.
• < 0 ➔ The Embedded SQL statement failed. 10 SQLWARN7 PIC X.
• Note that SQLCA can provide additional element/values that can be 10 SQLWARN8 PIC X.
interrogated to determine what programmatic action to take based on 10 SQLWARN9 PIC X.
the feedback from DB2. 10 SQLWARNA PIC X.
05 SQLSTATE PIC X(5).
Additional links about the SQLCA:
https://flylib.com/books/en/4.64.1.70/1/
https://www.ibm.com/support/producthub/db2/docs/content/SSEPGG_11.5.0/com.ibm.db2.luw.apdv.embed.doc/doc/c0006155.html
https://www.ibm.com/support/knowledgecenter/SSHRBY/com.ibm.swg.im.dashdb.sql.ref.doc/doc/r0002212.html
https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/rzajp/rzajpsqlcacobol.htm 523
Non-operational SQL Statements - Host Variables
Host variables are variables you declare in a program for use within an SQL statement. You can:
• Retrieve data into the host variable for your application program's use.
• Place data into the host variable to insert into a table or to change the contents of a row.
• Use the data in the host variable when evaluating a WHERE or HAVING clause.

01 DCLDEPT.
10 DEPTNO PIC X(3).
10 DEPTNAME.
49 DEPTNAME-LEN PIC S9(4) USAGE COMP.
49 DEPTNAME-TEXT PIC X(36).
10 MGRNO PIC X(6).
10 ADMRDEPT PIC X(3).
10 LOCATION PIC X(16).
...
MOVE 'NEW DEPARTMENT NAME' TO DEPTNAME-TEXT.
MOVE 19 TO DEPTNAME-LEN.

EXEC SQL INSERT INTO DEPT VALUES (:DEPTNO, :DEPTNAME, :MGRNO, :ADMRDEPT) END-EXEC.

MOVE 'A00' TO DEPTNO.


EXEC SQL SELECT DEPTNO, DEPTNAME, MGRNO, ADMRDEPT, LOCATION FROM DEPT INTO :DCLDEPT WHERE DEPTNO = :DEPTNO
END-EXEC.

Additional links about DB2 host variables:


https://flylib.com/books/en/4.64.1.71/1/
https://www.ibm.com/support/knowledgecenter/en/SSEPEK_12.0.0/intro/src/tpc/db2z_dataaccesswithhostvariables.html
https://www.ibm.com/support/producthub/db2/docs/content/SSEPGG_11.5.0/com.ibm.db2.luw.apdv.embed.doc/doc/c0021478.html 524
Host Variable -
Data Types
While most of your host variables
will be defined using DCLGEN
(next topic) - from time-to-time you
will have to define DATA DIVISION
variables to receive DB2 result set
data - or provide WHERE clause
operators (IF COLM = :VAR).

This table translates the DB2


CREATE TABLE statement column
types to their COBOL equivalents.

DB2 Data Types -

525
Non-operational SQL Statements - DCLGEN
DCLGEN reads the DB2 Catalog and produces a DECLARE TABLE
statement and the associated COBOL host variables, so that
you do not have to code them yourself.

DCLGEN may be fired off from:


• IDz - from the Data Explorer view
• DB2I

CREATE TABLE PAYROLL (


NBR CHAR(8) FOR SBCS DATA NOT NULL, D
RATE DECIMAL(5 , 2) NOT NULL WITH DEFAULT,
DED DECIMAL(3 , 0) NOT NULL WITH DEFAULT, C
DB2 Catalog HOURS SMALLINT NOT NULL WITH DEFAULT

• Grant/Privileges L
• Meta-Data
G
ALTER TABLE PAYROLL ADD CONSTRAINT NBR PRIMARY KEY E
(NBR);

ALTER TABLE PAYROLL ADD CONSTRAINT NBRA1AYA FOREIGN KEY


N
(NBR)
REFERENCES EMPLOYEE
(NBR)
ON DELETE CASCADE;

526
DB2TEST
Embedded SQL - Elements and Infrastructure
Embedded SQL statements:
• Can be coded in the A or B margin
• Begin with EXEC SQL
• Are terminated with END-EXEC

Operational Embedded SQL statements must


be coded in the PROCEDURE DIVISION
• OPEN CURSOR
• FETCH
• CLOSE CURSOR

Examples of Embedded SQL…


527
Operational SQL Statements - SQL Cursor Processing
DECLARE CURSOR In either WORKING-STORAGE or PROCEDURE DIVISION
• Defines/Names a cursor used to retrieve rows from the Result Set generated by the execution of a
DB2/SQL Embedded SQL statement. The SQL statement is part of the cursor declaration

OPEN CURSOR In the PROCEDURE DIVISION


• Executes the Embedded SQL statement defined in the cursor - and creates the Cursor's Result Set.
If there are no rows in the Result Set upon OPEN CURSOR, the SQLCODE is set to +100

FETCH CURSOR In the PROCEDURE DIVISION - almost always within a loop


• FETCH returns the next row of the cursor's Result Set. If there are no more rows in the Result Set the
SQLCODE is set to +100

CLOSE CURSOR In the PROCEDURE DIVISION


• CLOSE releases all DB2 resources held by the cursor 528
Embedded SQL - Singleton Select
MOVE 'AAAAAAAA' TO NBR.
DB2SINGL
EXEC SQL
SELECT NBR, RATE, DED, HOURS
INTO :NBR :RATE :DED :HOURS
TSO Batch FROM DDS0001.PAYROLL
WHERE NBR = :NBR
Program END-EXEC.

IF NBR='AAAAAAA' 4K VSAM Page

Tablespace

529
Embedded SQL Examples - UPDATE, DELETE, INSERT
MOVE '000205' TO NBR.
MOVE 40 TO DED. MOVE 'MARY' TO FNAME.
MOVE 55 TO RATE. MOVE'SMITH' TO LNAME.
MOVE 32 TO HOURS. MOVE'D11' TO WORKDEPT.
MOVE '1981-08-10' TO DOB.
EXEC SQL DELETE
Set-level Update

FROM PAYROLL EXEC SQL
WHERE RATE <= :RATE AND INSERT INTO DSN8B10.EMP Single (new) row Insert
DED > :DED AND VALUES (:NBR, :FNAME, :LNAME, :WORKDEPT, :JOINED,
:POSITION, :DOB, :EXT, :PBC, :DIV-NBR)
HOURS = :HOURS
END-EXEC.
END-EXEC.

EXEC SQL
INSERT INTO SMITH.TEMPEMPL
MOVE 42 TO RATE. SELECT * Multiple row(s) Insert
MOVE 'AAAAAAAA' TO NBR. FROM DSN8B10.EMP;
EXEC SQL UPDATE PAYROLL END-EXEC.
SET RATE = :RATE …
WHERE NBR = :NBR EXEC SQL
END-EXEC. INSERT INTO SESSION.TEMPEMPL
SELECT *
FROM DSN8B10.EMP
Selective row(s) Insert
Unique-Key (single-row) Update
WHERE WORKDEPT='D11'
END-EXEC. 530
Embedded SQL Infrastructure - DB2 Build
There are two additional build steps (besides Compile/Link) needed to
generate an executable/load module for your programs:
1. Preprocess:
• Parses your COBOL looking for EXEC SQL ……. END-EXEC.
• It removes those APIs (which are not COBOL compiler compliant replacing
them with CALLs to DB2 system routines
• And Preprocess creates a DBRM in a DBRMLIB
2. Bind:
• BIND validates your SQL (from the DBRM Library) against the DB2 Catalog
• If your statements are syntactically correct, BIND creates a Package or a
Plan - depending on the BIND statements you've used in your JCL
• Bind chooses the access path to your DB2 data - optimizing the SQL based
on:
• Your statements
• The presence (or absence) of index entries on columns you've or Plan
referenced in your code
• The state of the data in your table - as determined by RUNSTATS

Learning Links on Build:


Collections and Packages: https://www.ibmbigdatahub.com/blog/plans-collections-versions-packages-dbrms-confusion
Build Process: https://www.ibm.com/support/knowledgecenter/en/SSEPEK_11.0.0/intro/src/tpc/db2z_programprepprocesses.html
DB2I Build Dialogs: https://www.ibm.com/support/knowledgecenter/SSEPEK_11.0.0/apsg/src/tpc/db2z_db2ipanelsprogramprep.html 531
532
Embedded SQL - Additional topics
Host Variable Arrays
• https://www.ibm.com/support/knowledgecenter/SSEPEK_10.0.0/sqlref/src/tpc/db2z_hostvararraysinplicandcobol.html

Optimizing SQL Queries


• https://www.ibm.com/support/producthub/db2/docs/content/SSEPGG_11.5.0/com.ibm.db2.luw.admin.perf.doc/doc/c0054707.html

Stored Procedures
• https://www.ibm.com/support/knowledgecenter/SSEPEK_12.0.0/apsg/src/tpc/db2z_programexpcobol.html
Embedded SQL Infrastructure - Null Values
Some columns cannot have a meaningful value in every row. Db2 uses a special value indicator, the null value,
to stand for an unknown or missing value: think: Not Available …or… Not Applicable

A null value is a special value that Db2 interprets to mean that no data is present. You can test for the presence
of nulls with the following: WHERE <COLUMN> IS … IS NOT NULL;

Ex. SELECT * FROM DEPT WHERE MGRNO IS NOT NULL ORDER BY DEPTNAME DESC;

In Embedded SQL you use a PIC S9(4) COMP field as an "indicator" for the presence of a null value…

77 NULL-IND PIC S9(4) COMP.


...
EXEC SQL
SELECT DEPTNO, MGRNO
INTO :DEPTNO, :MGRNO:NULLIND
FROM DEPT
WHERE DEPTNO LIKE 'D8_'
END-EXEC.
Nulls are allowed in the
IF SQLCODE > 0
IF :NULL-IND = -1 MGRNO column
DISPLAY "No manager assigned"
ELSE
... 533
534
COBOL Program Big Picture - Topics in Module 21
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
INITIALIZE
Counters, Accumulators, Flags
z/OS ABENDS
Reference Modification, Figurative Constants • Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Safeguards
COBOL String Handling Functions: UNSTRING, STRING • Resolutions

COBOL Reusable Code Libraries


• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
 Nothing to hand in 535
Workshop 21.1 - Setting up for the DB2 Labs
1. If you are using your own shop's DB2 Subsystem, discuss accessing the tables & views via your shop's DB2
tools with: DBAs, Management, Tech-leads or other senior developers

2. If you are using zserveros, you will can access DB2 via IDz - Follow the steps described earlier in this section

3. If you are using ZOD you must utilize the zTrial software: https://www.ibm.com/account/reg/us-
en/signup?formid=urx-30291 - just as you did for the ISPF workshops. You can launch ADFz - or use SPUFI.
Remember that you have a total of 3 days (not business days/calendar days) to utilize this cloud-based system

4. To learn Interactive SQL there are a number of free online systems that provide a SQL parser. Google:
• Datacamp.com
• Khan Academy - SQL Training
• Ed-x
• SQLZoo

Note that the above are not IBM endorsements


They are SQL trial/learning options

Note also that you may use two or more of the above options
 Nothing to hand in 536

Workshop 21.2a - Interactive SQL Statement Code/Test


1. If you are using your own shop's DB2 Subsystem; Follow the standard options for using
SPUFI or QMF to code/test ISQL against your in-house tables.
1. The IBM/DB2 IVP tables might be installed and available
2. If you'll be using your company's own tables, contact your DBA. Let them know that you
are learning SQL. Stay away from joining million+ row test tables, etc.

2. If you are using IDz and zserveros; After following the setup in this module:
• Browse the EMP, DEPT, EMPROJ, etc. tables using the Data Source Explorer tools
• Code and run each of the interactive statements in this Module
• From SQL Select All Rows/All Columns ➔ SQL Select - Additional Samples
• Then begin writing your own interactive SQL - using the tables in the DSN81101 Schema
• Note - do NOT update rows in the DSN81101 tables

3. If you are working with the free SQL courses, when you're finished with the samples, be
sure to have coded & tested:
• Table Joins
• UNION/UNION ALL
• Many different WHERE predicate options
 Nothing to hand in 537

Workshop 21.2b - Using the zTrial System


1. As you did in Module 20 (ISPF):
• Register for zTrial
• Start zTrial
• Connect to IDz
2. From My Data Sets Note that if you have been using your own TSO/ISPF environment you will likely
• Scroll to DDS0001.TEST.SPUFI use QMF or SPUFI - to write & test SQL against your company's own tables.
• Open SPUFIZOS.sql
• Click here to connect to a database - and connect to DALLASB - where you can access the DSN81101 tables

You will have access to the DSN81101 tables from the DALLASB system
 Nothing to hand in 538

Workshop 21.3 - Embedded SQL Statement Code/Test


1. If you are using your own shop's DB2 Subsystem, follow the standards for writing simple COBOL
batch/Embedded SQL programs - and testing against in-house tables. You will need the following:
• Batch DB2 Build JCL build JCL, which includes:
• Precompile** ➔ Compile ➔ Link ➔ Bind**

2. If you are using either IDz or ZOD,


• From DDS0001 copy:
• LEARN.COBOL(DB2TEST) …and… DB2SINGL
• LEARN.JCL(DB2TEST …and…DB2SINGL)

• In your copy of the JCL files:


• CHANGE DDS0001 => <Your_TSOID> all
• Allocate your own LEARN.DBRMLIB
• TRACKS: 1, 3, 20, 80 Byte LRECL, 0 Blocks, PDSE

• Debug DB2TEST and DB2SINGL

• Create your own SQL statements for both programs


• Build
• Debug **Needed for DB2/COBOL programs
UNIT COBOL for z/OS - Module 22
Information Management Systems
• IMS Component View
• Hierarchical Data Model
• DL/I Language
• DBD/PSB/PCB
3-Part Article-set on IMS • Status (return) Codes
• http://www.dbazine.com/ofinterest/oi-articles/ims1/


http://www.dbazine.com/ofinterest/oi-articles/ims2/
http://www.dbazine.com/ofinterest/oi-articles/ims3/
• Sample IMS DB Program
YouTube Video: https://www.youtube.com/watch?v=DhlpnSbSuJE
Wiki with deep/broad IMS content: http://exampleproblems.com/wiki/index.php/IMSDB

IMS Book: https://www.amazon.com/I-M-S-Programming-Techniques/dp/0442805055/ref=sr_1_fkmr0_1?dchild=1&keywords=ims+kapp+and+leben&qid=1597261409&sr=8-1-fkmr0

IMS Application Programming: https://www.ibm.com/support/knowledgecenter/SSEPH2_13.1.0/com.ibm.ims13.doc.pdf/dfsapgk1.pdf

IMS https://en.wikipedia.org/wiki/IBM_Information_Management_System

Brief history of IMS: https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.imsintro.doc.intro/ip0ind0011003710.htm 539


540
COBOL Program Big Picture - Topics in Module 22
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
INITIALIZE
Counters, Accumulators, Flags
z/OS ABENDS
Reference Modification, Figurative Constants • Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Safeguards
COBOL String Handling Functions: UNSTRING, STRING • Resolutions

COBOL Reusable Code Libraries


• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
541

Note on learning IMS


• This module focuses entirely on IMS DB - not IMS DC (TM). Unlike every other
topic in this course - with the possible exception of Module 9, IMS DB is a difficult
learn.
• It's not only the COBOL syntax, it's:
1. DBMS & IMS Architecture
2. The Hierarchical Data Model
• Visual/Conceptual understanding
• Rules for processing data and database navigation
3. Control Blocks
4. CBLTDLI CALLS and CALL options
5. The tight integration of IMS data base access with COBOL program procedural logic
• The intent of this module is to provide you with a foundation to learn IMS
• To be ready for IMS work you will need:
• A quality IMS DB class (minimum three-days/24 hours)
• Hands-on lab time
542

1. IMS - one of the first Data Based Management Systems


A DBMS is a system that allows multiple independent users to have concurrent
access to a central repository of information.
It does this by:
1. Centralizing files
2. Eliminating duplicate data & redundant development
3. Providing an accurate single-source for data-based business decisions

Central Data
Repository

DBMS
543

1. IMS - Product Architecture - 20,000 Foot View


IMS provides both data base and online processing

Logging and
IMS Systems Software Recovery

I
M
S IMS DB IMS DC/TM
Database Transaction
Your
Manager Manager
PGM

DL/I Message
Databases Queues
544

1. IMS - Batch Application Processing - 10,000 Foot View


An IMS batch application runs in a standard z/OS address space, and interfaces to IMS
databases using DL/I - Data Language One. Not to be confused with (you guessed it) DB2
Roman Numeral I

z/OS

Input/Output Files
Your COBOL/IMS
QSAM
Application
VSAM

IMS
Data
Base
545

2. IMS Data Bases: The Hierarchical Model of Data


The IMS DB data model stores business data in a hierarchy of related records called
Segments
• Pointers within the segments create hierarchical relationships Segment
among the segments by storing physical addresses of related
PARTS Type
(parent/child) segments

• In the design shown here:


• A Part segment contains a set of Suppliers
for that specific part
• Each Supplier segment contains: SUPPLIERS Segment
Type
• That specific Supplier's Addresses
• That specific Supplier's Purchase Orders -

PURCHASE Segment
Segment
Type
ADDRESSES Type
ORDERS
546

Analogy: 2. Hierarchical v. Relational Data Models


• Segment Type ➔ DB2 Table …or… a COBOL Group Data Item
• Relationship ➔ Foreign/Primary Key between DB2 Tables
• Segment data stored in an IMS Data Base ➔ Row in a DB2 Table
Fdsfs
PARTNO SUPPLIER
Sfffffffffff Fdsddddddddddddd Fdsdsdsff Relationships among DB2 tables are PARTS
cccccccccc Fdsssssssssssssssss Ds created on-the-fly, by WHERE
Fdsfdsds sffffffsddddddd Fdsfdsf clauses in SQL Table Joins Pointer
sssssss ccccccccccc ssssssssssssssssssss

Foreign Key Value


SUPPLIER ADDRESS PURCHASE ORDER
Sfffffffffff

cccccccccc
Fdsdddddddddddd

Fdsssssssssssssssss
Fdsdsdsff

Ds SUPPLIERS
Fdsfdsds sffffffsddddddd Fdsfdsf

sssssss ccccccccccc ssssssssssssssssssss Pointers


Foreign Key Values
Aaaaaaaaa Fdsfs
ADDRESS

PURCHASE
DATE Fdsfs
PURCHASE ORDER
Sfffffffffff Fdsdddddddddddd Fdsdsdsff
ddd

ADDRESSES
Sfffffffffff Fdsddddddddddddd Fdsdsdsff
cccccccccc Fdsssssssssssssssss Ds
cccccccccc Fdssssssssssssssssss Ds
ss

Fdsfdsds sffffffsddddddd Fdsfdsf


Fdsfdsds

sssssss
sffffffsddddddd

ccccccccccc
Fdsfdsf

sssssssssssssssssss
ORDERS
sssssss ccccccccccc ssssssssssssssssssss
547

2. Before IMS: Data - Fixed Record QSAM or VSAM File

240 Bytes

Group Fields ➔EMPLOYEE SALARY ADDRESS TAXES DEDUCT


(44 bytes) (15 bytes) (100 bytes) (21 bytes) (60 bytes)

Elementary Fields ➔ EMP NO. 6 GROSS-SAL 6 ADDR FIT 6 TYPE 2


EMP NAME 30 SALARY-CLS 3 LINE(S) FICA 5 AMT 5
DEPT 2 AUTH DATE 6 25 x 4 STATE 5 BAL 5
DATE HIRE 6 LOCAL 5 x 5
548

2. Enter IMS: Data + Relationships Among Data


01 EMPLOYEE-DATA.
EMP NO. 6 02 EMPLOYEE OCCURS DEPENDING ON
EMPLOYEE EMP NAME 30 03 EMPNO PIC X(06).
DEPT 2 03 EMPNO PIC X(30).
(44 bytes) 03 DEPT PIC X(02).
DATE HIRED 6 03 HIREDTE PIC X(06).
03 MONTHLYSAL OCCURS DEPENDING ON
04 GROSS PIC 9(06).
04 SALCLASS PIC X(03).
04 AUTHDATE PIC X(06).
04 TAXES OCCURS DEPENDING ON
GROSS SALARY 6 ADDR 05 FIT PIC 9(06).
MONTHLYSAL SALARY CLASS 3 ADDRESS 05 FICA PIC 9(05).
LINE(S) 05 STATE-T PIC 9(05).
(15 bytes) AUTH DATE 6 (25 bytes) 0-n 05 LOCAL-T PIC 9(05).
04 DEDUCT OCCURS DEPENDING ON
05 DEDUCT-T PIC X(02).
Pointers store relationships among data 05 DEDUCT-AMT PIC 9(05).
05 BALANCE PIC 9(05).
03 ADDR OCCURS DEPENDING ON
04 ADDR-L1 PIC X(25).
04 ADDR-L2 PIC X(25).
FIT 6
TYPE 2 04 ADDR-L3 PIC X(25).
TAXES FICA 5 DEDUCT 04 ADDR-L4 PIC X(25).
AMT 5
(21 bytes) STATE 5 (12 bytes) BAL 5
LOCAL 5 Comparable COBOL Data Structure
Segments have parents and children
• Parent/Child segments are related
2. DL/I Data Bases - Rules & Terminology • Child segments are accessed thru their
Parent segment
• The Root segment has no Parent
Sequential processing thru an IMS Database
A Record proceeds
Level 1 1. Top ➔ Bottom
2. Left ➔ Right
3. At the lowest level; Front ➔ Back
Twins
CHILD SEGMENT
E1 Segments have Twins
• Multiple segments of the same type
Siblings • C1 is accessed as follows: A, B, C, C1
Level 2 B E J Segment pointers are maintained by IMS
when the segments in the Database are
C1
Twins CHILD SEGMENT Twins G1 Added/Deleted/Updated
CHILD SEGMENT

Level 3 C F G K L
Siblings

Why all this theory? Because your DL/I coding must take into consideration "positioning" within
the hierarchy of Data Base segments for sequential; retrieval, update, add and delete access.
549
DL/I Current Segment Status
DL/I Access - Database Positioning Call Position Returned Code
and Return/Status Codes GU A Blanks
GNbb A B Blanks
GNbb B C Blanks
GNbb C C1 Blanks
GNbb C1 E GA

A GNbb E F Blanks
GNbb F G GK
GNbb G G1 Blanks

CHILD SEGMENT
E1 GN G1 E1 GA

B E J
C1 G1
CHILD SEGMENT CHILD SEGMENT

C F G K L
550
3. Data Base Description Blocks: PSB/DBD/PCB
I/O for your COBOL program happens indirectly - through your program's DL/I Call statements to the IMS
systems software. A DL/I call utilizes a Program Specification Block (PSB) which is a container for one or more
Program Communication Blocks (PCB). Each PCB provides addressability to either a DL/I Data Base thru a
Data Base Descriptor (DBD) - or to an IMS Terminal/LTERM (not shown here).

Defining Data Base


Access DATA
P
PROGRAM PCB DBD BASE
S
B PCB DBD

DATA
BASE
Advantages of using Description Blocks:
1. Simplifies application program development
2. Provides security, integrity and consistency of a database
3. Facilitates changes to database 551
Like your COBOL program's
3. Database Description (DBD) record layout for the data in
a QSAM/VSAM file, a DBD
DBDLIB defines the structure, data
and relationships among
DBDGEN- the data of an IMS Database
MACRO**
PROCESS DBD The DBD Macro language - and your
LIB
database's specific DBD structure must be
understood before you begin programming
DBD NAME=EMPLOYEE,ACCESS=HDAM
DATASET DD1=EMPLDATA
SEGM NAME=EMPLOYEE,BYTES=44,PARENT=0
INPUT FIELD NAME=(SERIAL,SEQ,U),BYTES=6,START=1
INPUT
STATEMENTS FIELD NAME=FULNAM,BYTES=30,START=7
INPUT
STATEMENTS SEGM NAME=SALARY,BYTES=15,PARENT=EMPLOYEE
STATEMENTS
FIELD NAME=(SALCLASS,SEQ,U),BYTES=3,START=7 SALARY
SEGM NAME=TAXES,BYTES=21,PARENT=SALARY
SEGM NAME=DEDUCT,BYTES=12,PARENT=SALARY
FIELD NAME=(TYPE,SEQ,U),BYTES=2,START=1
SEGM NAME=ADDRESS,BYTES=26,PARENT=EMPLOYEE
FIELD NAME=(ADRSEQ,SEQ,U),BYTES=1,START=1
END

** Macro is a fancy name for a piece of Assembler code 552


553

3. Program Specification Block (PSB) DBDLIB

PSBLIB
DBD
PSBGEN DBDLIB
MACRO P PCB
Utility DBD
S
LIB B PCB
DBD

PCB TYPE=DB,DBDNAME=EMPLOYEE,PROCOPT=A,KEYLEN=11
SENSEG NAME=EMPLOYEE,PROCOPT=G
SENSEG NAME=SALARY,PARENT=EMPLOYEE,PROCOPT=GR
SENSEG NAME=TAXES,PARENT=SALARY PCB Macros must be
INPUT
INPUT SENSEG NAME=DEDUCT,PARENT=SALARY understood before you
STATEMENTS
INPUT
STATEMENTS PCB TYPE=DB,DBDNAME=PROJECT,PROCOPT=G,KEYLEN=22 can begin programming
STATEMENTS SENSEG NAME=PROJECT COBOL & DL/I Calls
:
PSBGEN LANG=COBOL,PSBNAME=EMPLPROJ
END

PSBs often define a subset of the segments in a database your program can access (SENSEG) -
Segments specific to your program's needs - isolating your code from database changes
554

3. PCBs, DBDs and WORKING-STORAGE COBOL Definitions


PCB TYPE=DB,DBDNAME=EMPLOYEE,PROCOPT=A,KEYLEN=11 ...
SENSEG NAME=EMPLOYEE,PROCOPT=G COPY Member COBEMPL:
SENSEG NAME=SALARY,PARENT=EMPLOYEE,PROCOPT=GR 01 EMPLOYEE.
SENSEG NAME=TAXES,PARENT=SALARY
05 SERIAL-NUM PIC X(06 ).
SENSEG NAME=DEDUCT,PARENT=SALARY
PCB TYPE=DB,DBDNAME=PROJECT,PROCOPT=G,KEYLEN=22 05 EMP-NAME PIC X(30).
SENSEG NAME=PROJECT 05 DEPT PIC X(02).
: 05 HIREDATE PIC X(06).
PSBGEN LANG=COBOL,PSBNAME=EMPLPROJ COPY Member COBSAL:
END 01 SALARY.
DBD NAME=EMPLOYEE,ACCESS=HDAM 05 SALARAY PIC X(06).
DATASET DD1=EMPLDATA 05 SALCLASS PIC X(03).
SEGM NAME=EMPLOYEE,BYTES=44,PARENT=0 05 AUTHDATE PIC X(06).
FIELD NAME=(SERIAL,SEQ,U),BYTES=6,START=1 COPY Member COBTAXES:
FIELD NAME=FULNAM,BYTES=30,START=7
01 TAX-DATA.
SEGM NAME=SALARY,BYTES=15,PARENT=EMPLOYEE
FIELD NAME=(SALCLASS,SEQ,U),BYTES=3,START=7
05 FIT PIC X(06).
SEGM NAME=TAXES,BYTES=21,PARENT=SALARY 05 FICA PIC X(05).
SEGM NAME=DEDUCT,BYTES=12,PARENT=SALARY 05 STATE-TX PIC X(05).
FIELD NAME=(TYPE,SEQ,U),BYTES=2,START=1 05 LOCAL-TX PIC X(04).
SEGM NAME=ADDRESS,BYTES=26,PARENT=EMPLOYEE COPY Member COBDEDUCT:
FIELD NAME=(ADRSEQ,SEQ,U),BYTES=1,START=1 01 DEDUCTION.
END
05 DEDUCT-TYPE PIC X(02).
05 DEDUCT-AMT PIC X(05).
Note that it is not necessary to define all the data in an IMS SEGM as a FIELD in the DBD. 05 DEDUCT-BAL PIC X(05).
Only the SEGM FIELDS you intend to search on. ...
555

4. DL/I (Language) - From 20,000 Feet


DL/I is a complex data access language. It interfaces with IMS Systems Software as well as specific
hierarchical database models and record layouts. There are dozens of access options, functions
and different styles of coding. Net: You will need a class to do DL/I justice

DL/I FUNCTIONALITY…
4. COBOL Program - DL/I Access
COBOL programs access IMS using CALL statements that
include DL/I Commands:
• There are dozens of CALL variations
• DL/I calls tie programs to a specific DL/I database structure
Unlike Embedded SQL (DB2), DL/I data access logic is embedded
(hard-coded) into a program's procedural structure in the PROCEDURE DIVISION:
• PERFORM/VARYING/Inline PERFORM/etc.
• This means that you need to interweave COBOL business logic and DL/I data access calls to get to
specific database segments
• Recall that one of the goals of modern design is to separate the Data Access Layer from the
Business Layer

When accessing an IMS database for anything except the initial database
LOAD, you will need to understand the "position" within the database your
DL/I access is currently on.
556
4. COBOL Program - DL/I Access Position
Position refers to what segment (not segment type - segment occurrence) IMS has
established for your program's access based on what it was previously asked to do.
When your program begins there is no position in the database. Thereafter:
1. An unqualified GU Call establishes position on the first Root segment in the database
• A qualified GU establishes position on the first segment that matches the SSA qualifications
• GHU establishes a lock ("Hold") on a specific segment prior to DLET or REPL
2. GN establishes position on the next segment in hierarchy order - as determined by the current IMS position in
the database
• GHN follows the same locking protocol as GHU - but with forward sequential segment access
• Qualified GN calls establish position on segments that match the SSA -- moving forward in the
database from the current position
3. GNP returns the segment under the current Parent as established by Position within the database
• Qualified GNP calls return segments moving forward in the database from the current position - under
the current Parent
4. ISRT - Insert a new segment under the current parent as established by position. You are responsible to fill in
all key fields prior to ISRT
5. DLET - Deletes the most recent "held" (using GHU, GHN, GHNP, etc.) segment returned
6. REPL - Updates or replaces the most recent "held" segment returned
557
4. COBOL Call - DL/I Command Functions
01 DLI-FUNCTIONS. *> A PIC X(4) field
GU ➔ Access a unique segment in an IMS database. GHU ➔ Access a unique segment w/update intent
05 DLI-GU PIC X(4) VALUE 'GU '.
05 DLI-GHU PIC X(4) VALUE 'GHU '.
** GN ➔ Access the next segment in an IMS database. GHN ➔ Access the next segment w/update intent
05 DLI-GN PIC X(4) VALUE 'GN '.
05 DLI-GHN PIC X(4) VALUE 'GHN '.
** GNP ➔ Access the next segment in an IMS database under the current parent segment
05 DLI-GNP PIC X(4) VALUE 'GNP '.
05 DLI-GHNP PIC X(4) VALUE 'GHNP'.
** ISRT - Insert a new segment into the database. ** DLET Delete the current (Held) segment in the database
** REPL Replace the current (Held) segment in the database
05 DLI-ISRT PIC X(4) VALUE 'ISRT'.
05 DLI-DLET PIC X(4) VALUE 'DLET'.
05 DLI-REPL PIC X(4) VALUE 'REPL'.
** Dependent on current position within the database 558
DL/I Current Segment Status
DL/I Access - Database Positioning Call Position Returned Code
and Return/Status Codes GU A Blanks
GNbb A B Blanks
GNbb B C Blanks
GNbb C C1 Blanks
GNbb C1 E GA

A GNbb E F Blanks
GNbb F G GK
GNbb G G1 Blanks

CHILD SEGMENT
E1 GN G1 E1 GA

B E J
C1 G1
CHILD SEGMENT CHILD SEGMENT

C F G K L
559
4. DL/I Calls - Segment Search Arguments (SSAs)
SSAs may be used to "qualify" a call in two ways:
1. Unqualified SSA to identify only the segment type

Byte 9
SEGMENT NAME b

8 1

Example: Get all EMPLOYEE segments


within a database

GN EMPLOYEEb
4. DL/I Calls - Qualified Segment Search Arguments
2. Qualified SSAs identify specific occurrences of segments

SEARCH REL COMPARATIVE


SEGMENT NAME ( )
FIELD OPERATOR VALUE

8 1 8 2 1-255
b= or EQ, = or NE
b> or GT, >= or GE
b< or LT, <= or LE

Example: Get the EMPLOYEE segment


with SERIAL 123456

GU EMPLOYEE(SERIALbb=b123456)
562

4. SSA and DL/I Status (Return) Codes


015800 01 SSA-EMPLSEG.
015900 05 EMPLSEG-SEG-NAME PIC X(8) VALUE 'EMPLSEG'.
Segment Search Arguments:
016000 05 EMPLSEG-COMM-ASTR PIC X VALUE '*'. • Optional parameters used to search an
016100 05 EMPLSEG-COMM-CODE PIC X(3) VALUE '---'. IMS database
016200 05 EMPLSEG-L-PAREN PIC X VALUE '('.
016300 05 EMPLSEG-KEY-FLD PIC X(8) VALUE 'EMPLKEY'.
• But required in the case of certain
016400 05 EMPLSEG-OPERATOR-1 PIC XX VALUE ' ='. DL/I class
016500 05 EMPLSEG-KEY PIC X(23) VALUE SPACES. • Like a WHERE clause in SQL
016600 05 EMPLSEG-R-PAREN PIC X VALUE ')'.

DL/I Database Access STATUS CODES: LINKAGE SECTION.


01 EMPLOYEE-PCB-MASK.
05 EMP-DBD-NAME PIC X(8).
GU Call 05 EMP-SEGMENT-LEVEL PIC XX.
'GE' - Segment not found 05 EMP-STATUS-CODE PIC XX.
'bb' - Successful call 05 EMP-PROC-OPTIONS PIC X(4).
GN Call 05 FILLER PIC S9(5) BINARY.
05 EMP-SEGMENT-NAME PIC X(8).
For Unqualified Calls Only: 05 EMP-KEY-LENGTH PIC S9(5) BINARY.
'GA' - Crossed hierarchic boundary to a higher level 05 EMP-NUMB-SENS-SEGS PIC S9(5) BINARY.
'GK' - Different segment type at the same level 05 EMP-KEY PIC X(11).

'GB' - End of database reached


After each DL/I call you will check the
'GE' - Segment not found
'bb' - Successful call Database Segment STATUS-CODE
5. Application Program - Structure
PCB AREA LINKAGE SECTION

RETURN INFO FROM DL/I 3


I/O AREA DATA AREA - WORKING STORAGE SECTION

SEGMENTS TO / FROM DATABASE 4

PROGRAM ENTRY PROGRAM AREA


1
CALLS TO DL/I
(GET
2
INSERT
REPLACE
DELETE)

PROCESSING TERMINATION
5
Creates a "COMMIT" event

DL/I
© Copyright IBM Corporation 2008 DL/I MODULES AREA
564

5. IMS DB - Application Program Elements - Big Picture


IDENTIFICATION DIVISION. z/OS Address Space z/OS Address Space
...
ENVIRONMENT DIVISION.
SELECT ASSIGN QSAM/VSAM FILES
...
IMS (DFSRRC00)
DATA DIVISION.
LINKAGE
... PSB PSBLIB
WORKING-STORAGE SECTION. PSB (Physical)
COPY COBEMPL. Note: PSB & DBD Libraries
01 IO-AREA PIC X(100). are specified in the Run JCL
01 SSA-EMPL PIC X(40). PCB
LINKAGE SECTION Logical Database
view
DBD DBDLIB
01 EMPL-PCB. (Physical)
...
PROCEDURE DIVISION.
ENTRY 'DLITCBL' USING EMPL-PCB. DL/I Action Modules
...
CALL 'CBTDLI' USING 'GU', EMPLPCB, IO-AREA, SSA-EMPL.

Data Language Interface


EVALUATE RC HDAM HIDAM HISAM HSAM
CALL
WHEN SPACES ...
WHEN 'GE' ...
Link-edited into
WHEN OTHER ... Load module Database Types and Access Methods
565

5. COBOL Program DL/I Access


Areas of interest:
1. Your program's ENTRY Statement
2. "PCB Masks" in the LINKAGE SECTION
3. I/O Areas
4. Segment Search Arguments
5. DL/I Functions
6. DL/I Return Code Evaluation

1. ENTRY 'DLITCBL' USING PCB01, PCB02… is used to pass control from IMS to your program
• First executable statement
• The PCB order in the ENTRY statement must match the order of PCB definitions in the PSBGEN

2. PCB Masks - Control blocks that establish addressability to specific DBDs


• See previous slides/topics

3. I/O Areas - A Data Division (WORKING-STORAGE SECTION) variable that is location used to read/write
database segments:
• Either a "General I/O Area" - big enough to contain the largest database segment
• A specific I/O Area - one for each segment type being accessed
566

COBOL Program DL/I Access


IDENTIFICATION DIVISION.
PROGRAM-ID. EMPIMS.
A small sample DL/I program - including all of DATA DIVISION.
the elements discussed: WORKING-STORAGE SECTION.
01 DLI-FUNCTIONS.
1. DL/I Command Calls 1.
05 DLI-GU PIC X(4) VALUE 'GU '.
05 DLI-GN PIC X(4) VALUE 'GN '.
2. Segment I/O Area 05 DLI-REPL PIC X(4) VALUE 'REPL'.

3. PCB-Mask 2. 01 SEGMENT-I-O-AREA PIC X(1000).


LINKAGE SECTION.
01 EMPLOYEE-PCB-MASK.
4. Entry statement
3.
05 EMP-DBD-NAME PIC X(8).
5. Call to DL/I 05 EMP-SEGMENT-LEVEL
05 EMP-STATUS-CODE
PIC XX.
PIC XX.
05 EMP-PROC-OPTIONS PIC X(4).
05 FILLER PIC S9(5) BINARY.
05 EMP-SEGMENT-NAME PIC X(8).
05 EMP-KEY-LENGTH PIC S9(5) BINARY.
05 EMP-NUMB-SENS-SEGS PIC S9(5) BINARY.
05 EMP-KEY PIC X(11).
PROCEDURE DIVISION.
4. ENTRY 'DLITCBL' USING EMPLOYEE-PCB-MASK.
110-GET-EMPLOYEE-SEGMENT.
* Unqual GU. Return 1st root segment on database
CALL 'CBLTDLI' USING DLI-GU,
5. EMPLOYEE-PCB-MASK, SEGMENT-I-O-AREA.
IF EMP-STATUS-CODE = SPACES
* Continue to process data
GOBACK.
DL/I and the Linkage Editor
Static Calls to DL/I must be resolved by the Linkage Editor
z/OS
Compile/Link JCL
DL/I CONTROLLER
(DFSRRC00)
LINK

APPLICATION PROGRAM 'ANYPROG'


CALL 'CBLTDLI’

DL/I LANGUAGE INTERFACE (DFSLI000)


'CBLTDLI'

CALL
© Copyright IBM Corporation 2008

DL/I ACTION MODULES


IMS Pros & Cons
Pro Con
If designed well to fit the business needs, IMS data access is This comes at the expense of model-flexibility.
as fast and efficient as possible • Can you read upwards?
• Yes - but only using qualified 'GU'
• Backwards?
• Ditto
• What happens when you must add a new TYPE of segment in the
middle of an IMS hierarchy?
• Database
• Control Blocks
• Application Programs
Designed to act as an enterprise's "system of record" Even in its salad days, I doubt that a single shop ever created
an "enterprise"-level data base
• Data Redundancy
Powerful Database Access Language The word "powerful" in tech-marketing literature is a red
flag. Synonyms include: Complex, Arcane, Difficult
IMS and 3GLs (COBOL, PL/I, Assembler) are the means in Because you must design/code your program around the
which to build out IMS Database Applications structure of an IMS data base, your code becomes sclerotic

568
UNIT COBOL for z/OS - Module 23

Online Applications - Overview


• Architecture
• Online Application Event Sequence
• CICS Commands
• Conversational Program
• Pseudo Conversational Program

CICS Glossary of Terms: https://www.ibm.com/support/knowledgecenter/SSGMCP_5.1.0/com.ibm.cics.ts.glossary.doc/glossary.html#gloss_A__x2013002


IMS Glossary of Terms: https://www.ibm.com/support/knowledgecenter/en/SSEPH2_14.1.0/com.ibm.ims.glossary.doc/ims_glossary.htm
569
Online Transaction Processing
If you are angling for a job in a CICS or IMS DC/TM shop - or for work in an online area
in your shop, we strongly recommend that you do two things:
1. Read through white papers/book & watch the videos in the links below
2. Take a hands-on CICS or IMS application programming course

Tutorials & White Papers


https://en.wikipedia.org/wiki/IBM_Information_Management_System -- IMS Wikipedia
https://en.wikipedia.org/wiki/CICS -- CICS Wikipedia
https://www.youtube.com/watch?v=stiHn3VdDb0 -- IMS Zowe/API
https://www.tutorialspoint.com/cics/index.htm -- CICS
https://www.youtube.com/watch?v=uTVhx398SQQ -- CICS Tutorial
https://www.youtube.com/watch?v=j22Kx13-Tss -- IMS Tutorial
https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zmidtrmg/zmiddle_13.htm -- IBM K.C. Intro to CICS
https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.imsintro4db.doc.intro/ip0ind0011003634.htm -- IBM K.C. Intro to IMS

http://www.redbooks.ibm.com/redbooks/pdfs/sg248067.pdf -- CICS PDF 570


Online Transaction Processing
Online transaction processing (OLTP) is transaction
processing that occurs interactively; it requires:
• Immediate response time - or as close as to immediate as possible
• Continuous availability of the transaction interface to the end user
• Security
• Data integrity

Online transactions are familiar to many people.


Some examples include:
• ATM transactions such as deposits, withdrawals, inquiries, and transfers
• Supermarket payments with debit or credit cards
• Buying merchandise over the Internet

An online system (CICS and IMS TM) has many of the


characteristics of an operating system:
• Managing and dispatching tasks
• Controlling user access authority to system resources
• Managing the use of memory
• Managing and controlling simultaneous access to data files
• Providing device independence. 571
"Online" …vs… "Batch"
• Online systems provide online access to applications that process business transactions in "real-time"
• Credit cards and ATMs, Airline, hotel reservations
• Batch systems are launched by Jobs that are submitted (by you or a scheduling product). Upon launch, Jobs
are prioritized, scheduled, executed and managed by JES - the Job Entry Subsystem

Online Systems–TP Region(s) Batch Region(s)


Online application users
JCL JOBs

JES
Online IDz - ZOD
Online
Online
Applications z/OS Job Scheduler
TSO/ISPF
Applications
Applications z14 Batch
Batch
Batch
Online Region Supervisor Jobs Offline
Job
Files and CICS or IMS TM Jobs Files and
Databases Databases
Internal
Tables Control
(GENs) Blocks
573

Online Systems/Batch Systems - Comparison


Batch System Online (CICS/IMS TM) System
Input data includes; files and databases. Input data from a variety of user interface/front-ends: 3270 data
And potentially small parameter (PARM) stream (BMS/MFS), JSP/JSF, iPhone, Web Services, 4GLs such as: Visual Basic,
data used to control the job run PowerBuilder, etc.
Output data includes; System of Record Output is a user screen - and/or updated data source; VSAM file, DL/I database,
Data File; QSAM/VSAM, DL/I, DB2, etc. DB2 tables - but typically not the system of record (often referred t as "data
Report (print) files collection")
JOBS run in under an hour Online user interactions (Screens) complete in seconds
Primary goal is data processing Primary goal is user response time - to this end, many programs contain
throughput include COBOL GO TO (instead of PERFORM). This is especially in older code,
where you will occasionally find "fall thru"
Almost all JOBS (and programs) are Online transactions are entered and scheduled by the online Supervisor
scheduled software based on user/customer-demand
Large programs Small(er) programs
Each batch program data/processing Many online applications provide more of a pattern-based/cookie cut design.
requirement is unique Which gave rise to program generators such as; TELON, CSP, Netron Cap, etc.
• Menu, Inquiry, Data Update, etc.
574

Online Transaction Events - Terms and Concepts

5. User reads message - evaluates


1. User launches Transaction 3. User fills in U.I. launches Transaction business decision and responds
• Type Trancode, hit  • Trancode + Data • (new) Trancode + Data

Online System "Region Supervisor"- CICS or IMS TM


2. Online Supervisor 4. Online Supervisor 6. Online Supervisor
• Validates Trancode • Schedules program associated with Trancode. • Validates Trancode
• Begins a "Task" • The program evaluates user data - and responds back - • Schedules program associated
• Schedules program sometimes from the same program, but often by "message with (new) Trancode
associated with Trancode switching" (CICS XCTL). Which starts" a new transaction • Program evaluates data - updates
• Application Returns U.I. to user that gets scheduled by the Online Supervisor to processes files and responds to the user
• End Transaction data - and respond back to the user • End Transaction
• Temporary/Transaction-specific data can be retained in a
work-in-progress file called the COMMAREA(CICS) or SPA

CICS IMS Control SPA


Tables Blocks (ACB) COMMAREA
575

Online - Terms & Concepts


Transaction
A transaction is a piece of processing initiated by a single request. This is usually from an end user at a terminal, but might also be made from a Web page, from a remote
workstation program, from an application in another CICS system, or triggered automatically at a predefined time.

A CICS transaction is given a 4-character name, which is defined in the program control table (PCT). Like EXEC PGM= in
batch applications
An IMS TM transaction is a 1-8 character name, which is defined in the ACBGEN

Application program
A single transaction consists of one or more application programs that, when run, carry out the processing needed. You describe each transaction type to CICS with a
transaction resource definition. This definition gives the transaction type a name (the transaction identifier or TRANSID) and tells CICS several things about the work to be
done, such as what program to invoke first and what kind of authentication is required throughout the execution of the transaction.

You run a transaction by submitting its TRANSID to CICS. CICS uses the information recorded in the TRANSACTION definition to establish the correct execution environment
and start the first program.

Unit of work
The term transaction is now used extensively in the IT industry to describe a unit of recovery or what CICS calls a unit of work. This is typically a complete
operation that is recoverable; it can be committed or backed out as an entirety as a result of a programmed command or system failure. In many cases, the
scope of a CICS transaction is also a single unit of work, but you should be aware of the difference in meaning when reading non-CICS publications.

Task
You will also see the word task used extensively in CICS publications. This word also has a specific meaning in CICS. When CICS receives a request to run a
transaction, it starts a new task that is associated with this one instance of the execution of the transaction–that is, one execution of a transaction, with a
particular set of data, usually on behalf of a particular user at a particular terminal. You can also consider it analogous to a thread. When the transaction
completes, the task is terminated.
NEXT ORDER
NAME JOHN DOE
ADDRESS 123 MAPLE
MESSAGE REGION CONTROL REGION
Conversational
CHIC ILL
ACCT 12-3456-789
60999
Processing
ORDER ENTRY
TIME 1 PROGRAM

ORDER 98765 IMS TM provides a "Scratch Pad Area (SPA)


ITEM QTY DESC between schedulings of "conversational" programs.
1 THING 2 BLUE This allows programs to carry task-specific, non-
2 TIME 2 persistent data throughout a transaction
3

IMS SCRATCH PAD AREA


ORDER ENTRY
PROGRAM
ORDER 98765 12-3456-789
ITEM PRICE SHIP 98765
1 10.00 .50
SUB 10.00 CICS DFHCOMMAREA
TAX .50 TIME 3
SHIP .50
TOTAL 11.0 0 CICS has a similar feature called the COMMAREA

ORDER ENTRY
PROGRAM
NEXT ORDER
NAME
TIME 4
ADDRESS

ACCT
576
TRAN,EMP12345 PROCEDURE DIVISION.
CICS INITIALIZATION-ROUTINE. CICS Commands -
REGION …
EXEC CICS RECEIVE
Conversational Transaction
Schedule END-EXEC.
3270-TERMINAL Program …
Start Process Data

Considerations
NAME…………
Task
POSITION… EXEC CICS SEND 1. Processor speeds are considerably
PHONE…
MAP ('ABC123R') faster than terminal transmission
FROM (WS-MAPDATA)
END-EXEC.
times
3270-TERMINAL … 2. Which are considerably faster than
__ Program waits for user response __ user response times
NAME: T WATSON
POSITION: CEO …
PHONE: 7865
LOCATION: NWERE RETURN-FROM-USER. 3. This is especially true if users have to
EXEC CICS RECEIVE MAP think about the entry or have to
END-EXEC. enter many characters of input.

3270-TERMINAL Process Data 4. Consequently, conversational
NAME: T WATSON
… transactions tie up storage and
POSITION: CEO EXEC CICS SEND
PHONE: 7865 other resources for much longer
LOCATION: NWERE MAP ('XYZ123')
FROM (WS-MAPDATA) than non-conversational
END-EXEC.… transactions.
3270-TERMINAL
End Task
577
TRN1,EMP12345 CICS PROCEDURE DIVISION.
CICS Commands -
REGION INITIALIZATION-ROUTINE. Pseudo-Conversational Transaction

EXEC CICS RECEIVE
Schedule
INTO(WS-INPUT) NAME…………
TRN1 LENGTH(WS-INPUT-LENGTH) POSITION…
3270-TERMINAL Program ➔ END-EXEC. PHONE…

Task …
NAME………… Process Data
POSITION… …
PHONE… EXEC CICS 3270-TERMINAL
SEND MAP ('ADMENU')
CICS
PROCEDURE DIVISION.
MAPSET('CDATMAP') REGION
TRN2,MGRXYZ INITIAIZATION-ROUTINE.
MAPONLY …
3270-TERMINAL ERASE Schedule
End Task EXEC CICS RECEIVE
END-EXEC. TRN2
END-EXEC.
Program ➔ …
EXEC CICS RETURN Task
TRANID('TRN2') 3270-TERMINAL Process Data
COMMAREA (WS-COMMAREA) …
LENGTH (WS-COMMAREA-LENGTH) EXEC CICS SEND
DEPT…………
END-EXEC. LOCATION……… 'INFO ON MGRXYZ'
BUDGET……… END-EXEC.

EXEC CICS RETURN


COMMAREA End Task END-EXEC.
CICS makes available a "scratch pad - or data area" in CICS 3270-TERMINAL
storage that allows programs participating in a task to share
work-in-progress data. In COBOL the COMMAREA (variable)
must be named: DFHCOMMAREA 578
PROCEDURE DIVISION. 579
/FOR EMP001
/FORMAT SCREEN ENTRY 'DLITCBL'
USING IO-PCB, IMS Online - Message Switch
ALT-IOPCB, DB-PCB. PROCEDURE DIVISION.
GET-NEXT-TRAN. ENTRY 'DLITCBL'
IMS USING IO-PCB,
3270-TERMINAL CALL 'CBLTDLI' USING
MPR DB-PCB1, DB-PCB2.
Fill out Screen 'GU', IOPCB, NAME; SMITH IMS
IO-AREA. POSITION: MGR
PHONE: 9-0903 MPR ...
NAME………… IF NO-MORE-TRANS ? NBR EMPLOYEES
GET-NEXT-TRAN.
POSITION… Schedule CALL 'CBLTDLI' USING
PHONE…
GOBACK. Schedule
TRN1 'GU', IOPCB,
Process Data TRN2
Program ➔ MFSMID-DATA.
CALL 'CBLTDLI' 3270-TERMINAL Program ➔
IF NO-MORE-TRANS

Reply to user
USING 'ISRT'
3270-TERMINAL GOBACK.
IO-PCB,
...
IO-AREA, NAME: SMITH
Process Data
NAME; SMITH
MFSMOD-NAME. POSITION:
POSITION: MGR
PHONE: 9-0903
NBR EMPLOEES: 4
...
? NBR EMPLOYEES
CALL 'DLITCBL'

Redirect to
next Trans
CALL 'CBLTDLI'
USING 'CHNG' USING 'ISRT'
ALT-IOPCB. IO-PCB, IO-AREA
3270-TERMINAL 3270-TERMINAL End TRN2 MFSMOD-NAME.
CALL 'CBLTDLI' ...
End TRN1 USING 'ISRT' GO TO GET-NEXT-TRAN.
IO-PCB,
The IMS Trancode can be IO-AREA,
These two calls (CHNG and ISRT) are called a "Message
embedded defined as part MFSMOD-NAME.
... Switch". Data can be passed between programs using; Screen
of the MFS screen definition values (including hidden screem values) and an IMS SPA
ID DIVISION.
PROGRAM-ID. CICSPSEU.
DATA DIVISION.
WORKING-STORAGE SECTION.
CICS - COBOL Commands
01 WS-USER-DATA-IN.
05 WS-TRANCODE PIC X(04).
The
05 FILLER PIC X(01).
Points:
05 WS-EMPL-IN PIC X(12). • There are > 100 unique
01 WS-USER-DATA-OUT. CICS Commands
05 FILLER PIC X(20) VALUE "EMPLOYEE ID: ".
05 WS-EMPL-OUT PIC X(12). • You will only need a
01 WS-DATA-LTH PIC 9(04) COMP. subset of them in any
LINKAGE SECTION.
01 DFHCOMMAREA.
program
05 COM-TRAN-EXEC-COUNT PIC 9999. • After each CICS Call you
05 COM-AREA-TRAN-PROGRAM. will check a Return Code
... Fields & values specific to the program's processing requirements
PROCEDURE DIVISION. (much like a DB2
MOVE 17 TO WS-DATA-LTH. SQLCODE)
EXEC CICS
RECEIVE INTO (WS-USER-DATA-IN)
LENGTH (WS-DATA-LTH)
END-EXEC.
MOVE WS-EMPL-IN TO <search field>
... Read DB2, VSAM file or DL/I Data Base using EXEC CICS
… Return results to user
EXEC CICS SEND
FROM (WS-USER-DATA-OUT)
LENGTH (34)
END-EXEC.
EXEC CICS RETURN
END-EXEC.
EXEC CICS RETURN END-EXEC. 580
581

CICS Build - Precompile Step


While IMS DB/DC uses a
CALL statement - which is
consumable by the
COBOL Compiler, the
CICS Commands (like the
Embedded SQL statements)
require pre-processing…
a pre-compiler step prior
to the COBOL Compile in
the Build JCL
or Plan
The pre-compiler turns
EXEC CICS statements
such as these ➔
into CALL … USING
CICS - BMS Maps
While a great many User Interface platforms to CICS
applications are (today); iPhone, Web-based, Java-based,
etc. There are still quite a few 3270 data-stream screens.
In CICS these screens are created using BMS (Basic
Mapping Support)

BMS maps (screens) are created using


assembler macros that generate the
3270-screen appearance and behavior:
• Layout
• Colors
• PF-Keys
• Input/Output
• Messages, etc.
582
IMS - MFS Screens (MFS Maps)
Like its CICS/BMS relative, there are many of the same User Interface
technologies to IMS TM transactions. And there are still quite a few
3270 data-stream screens. In IMS these screens are created using
MFS (Message Format Services)

MFS maps/screens are created using


assembler macros that generate the
3270-screen appearance and behavior:
• Layout
• Colors
• PF-Keys
• Input/Output
• Messages, etc.
583
Online Programming Restrictions - Statements not allowed in CICS or IMS DC programs
ENVIRONMENT DIVISION.
• CONFIGURATION SECTION
• INPUT-OUTPUT SECTION
DATA DIVISION.
• FILE SECTION
PROCEDURE DIVISION.
• ACCEPT/DISPLAY
• OPEN/CLOSE
• QSAM READ/WRITE
• VSAM READ/WRITE is
acceptable
• STOP RUN
584
System Tables, Programs and Control Blocks - CICS
Creating and maintaining the System z/OS
Tables is the responsibility of CICS IMS TM Transaction: ABCD
(or IMS) administrators or of z/OS ACBGEN
Systems Programmers • PSBGEN
AOR AOR
• DBDGEN
CICS Application Owning Region Program Processing Table

Programs Tran Code CICS Program


• Program Control: PCP A001 CICSPGM1
• File Control: FCP
• Terminal: TCP A002 CICSPGM2
• Task Control: KCP
ABCD A001
ABCD CICSPGM3
• Temp Storage: TSP
• Transient Data: TDP
• Storage Control: SCP
• Interval Control: ICP
• Journal Control: JCP Program Control Table

Tables DFHRPL LOAD MODULE LOCATION


• Processing Program Table: PCT LOADLIB LOAD MODULE A001 Address Space
• File Control Table: FCT
• Terminal Control Table: TCT A001 A001 A002 In Storage
• Program Control Table: PCT A002 A002 ABCD Disk Pack
• Temp Storage Table: TST
• Destination Control Table: DCT ABCD ABCD 585
IMS Message Processing Program Architecture
z/OS
CONTROL MESSAGE MESSAGE
LOG
REGION PROCESSING PROCESSING
REGION REGION
LOGGING

APPLICATION APPLICATION
COMMUNIC-
PROGRAM PROGRAM
ATION z/OS

MESSAGE
DATA QUEUE
BASES

DATA
LANGUAGE/1
UNIT COBOL for z/OS - Module 24
Final Exam:
• Application design/Program standards
• Team development
• Roles and responsibilities
• Project Lifecycle and source control
• Build
• Test and Test data creation
• Economy of scale
• Subprograms
• Control Break Reporting and file sort
• Maintenance and production support
• Documentation and Code Review
• File I/O
• Individual (not team) requirements
587
588
COBOL Program Big Picture - Topics in Module 24
Identification Name the executable Program-ID. PAYROL03.

Statements that connect the SELECT <internal file name> ASSIGN TO JCL-DDNAME
program to Indexed and
Environment FILE SECTION - FD
Sequential data sets. Standalone and Data Hierarchy variable definitions
Binary Data: COMP, COMP-3, DISPLAY EBCDIC values
REDEFINES
Variable declarations - Fields 88 Named condition
Signed Numeric PIC
that contain values to be
FILLER
Data processed in the program's VALUE
PROCEDURE DIVISION Output/Report Formatting: Z, $, * Suppression, Comma/Decimal Point, BLANK WHEN ZERO

IF/ELSE; How IF tests are evaluated: PIC X fields, PIC 9 fields


Compound IF, Nested IF, EVALUATE
Executable statements that
Signed Conditions, Class Conditions
process the variable values in MOVE: PIC X MOVE behavior, PIC 9 MOVE behavior
the DATA DIVISION Compute/ADD/SUBTRACT/DIVIDE ROUNDED, ON SIZE ERROR
Procedure
DISPLAY, GOBACK
Code Paragraph
PERFORM Paragraph UNTIL <condition>
OPEN <Filename>, READ <Filename> AT END, WRITE <Recordname>, CLOSE <Filename>
INITIALIZE
Counters, Accumulators, Flags
z/OS ABENDS
Reference Modification, Figurative Constants • Understanding
Intrinsic Functions: Date, Math, Analytics, Text Manipulation • Safeguards
COBOL String Handling Functions: UNSTRING, STRING • Resolutions

COBOL Reusable Code Libraries


• Concepts
Coding Standards
• Quality

Divisions •

Create
Maintain


Consistency
Compliance
Final Exam Specifications - 1 of 2
You've been made a part of a 4-person team responsible to; Design, Develop, Test, Deploy and Maintain (and
support) a small batch COBOL application - for the used-car dealership down the block - "Destiny Auto Parts"
• The application reads a sorted QSAM data file: PARTSUPP - Each record in the file contains
information about a single part, it's suppliers, the supplier's addresses and purchase orders.
Supplier Addresses are in a table inside the record as are Purchase Order records- (see the
PARTSUPP record layout on slide 583)
• The application edits the PARTSUPP input file - utilizing a series of subroutines - one for each
05-level group in the PARTSUPP copybook. Errors found in the input record are written to an
error-file.
• Good records are written to four separate QSAM files - passed to downstream processing:
1. PARTS - a file of part information
2. SUPPLIERS - a file that contains information on the Suppliers for a given Part
3. ADDRESS - a file that details 3 different addresses for each Supplier
4. PURCHASE - a file contains from 3 Purchase Orders cut to a Supplier - for a given Part

• A report is written out for each of the good records that pass the edit criteria
• DISPLAY statements can be used for one-off purposes
* For example, if the program should ABEND because of a bad numeric data in the input file
589
Final Exam Specifications - 2 of 2
After you've finished testing your finished app you will turn in the code and test results.
Then you'll add one bug somewhere in the code and hand your programs, all test data and the JCL the build
your programs over to another team. Which will have to find & fix the bug. Then report back on how long it took
them and how easy it was to read your code.
The bug must be a logic bug - and not a bug that ABENDs upon running the test data that produced the report
shown at then of this Module.
Examples of possible bugs to introduce might include:
• Empty input file (with your code forgetting to check)
• Table handling error:
• Zeroth subscript and/or Subscript out of range
• Didn't sort file and use a SEARCH ALL
• Missing numeric-validations for input data that participates in arithmetic statements - and causes a S0C7 S0CB
when records with certain values are introduced
• Truncation
• Misunderstanding of use Intrinsic Functions
• Failed to CLOSE output files, so reports or other outputs are missing records
• Note that, depending on the Compiler directives CLOSE will also flush buffers
• Incorrect computations - especially due to misunderstanding of COBOL default operator precedence
• Failure to initialize WORKING-STORAGE fields
• Parameter length mismatch between Calling and Called programs
590
Project Team/Application Development
You will need to meet over Skype - via any other means of group discussion (including Slack) - and
decide the following roles:
Programmer/Analyst(2):
• Code COBOL - primary
• Document program code
• Analyze maintenance requests
• Support applications - including bug fixes
Tester:
• Create test data
• Create the error messages for invalid data
• Create the testing plan and lead a discussion with the team on how testing will go
• Create JCL to Debug and Run the application
• Run/Debug and analyze test results
• Back-up COBOL maintenance and support applications - including bug fixes
Tech-Lead:
• Project planning, milestones, schedule and lead meeting/discussions, etc.
• Setup Source Management on Git
• Interpret specs and lead the team in the design of the application
• Create a list of all the resources necessary for creating/debugging the application? Programs, JCL, Copybooks, Data Files, etc.
• Write high-level specifications for Programmer/Analysts … I/O design, etc.
• Create application development standards:
• Programming and Code reviews
• Overall development approach and project plan
• Documentation standards (keep it simple here)
• Back-up COBOL programming
• Buy coffee and pizza for the team
591
Specifications - Job Flow
STEP1; Sort the PARTSUPP file on PARTNO

STEP2; Execute the Part/Suppliers program - reading PARTSUPP - and splitting the data into four output data files, an error-file. a
report file and SYSOUT - for DISPLAY of program statistics and potential problems (ABENDs, etc.)

Purchase PARTSUPP PartSupp


Orders PARTEDIT
Report
Parts

SUPPEDIT
Part- Called
Batch SORT
JCL PARTSUPP Suppliers Programs
ADDREDIT

Suppliers POEDIT
Job
Addresses ERRORFILE
Statistics 592
593

Edits for the Parts/Supplier/Addresses/Purchase-Order Data


05 PARTS:
• Required fields*** PART-NUMBER/PART-NAME/VEHICLE-MAKE, VEHICLE-MODEL VEHICLE-YEAR
• VEHICLE-MAKE must be one of the listed 88-level fields
• VEHICLE-YEAR must be between 1990 and 2019
• WEEKS-LEAD-TIME must be numeric and between 1 and 4

05 SUPPLIERS
• Required fields: SUPPLIER-CODE, SUPPLIER-TYPE, SUPPLIER-NAME, SUPPLIER-PERF
• SUPPLIER-TYPE, SUPPLIER-RATING, SUPPLIER-STATUS must be one of the listed 88-level values
• SUPPLIER-ACT-DATE - Optional but if a value exists in the field ensure that the date is valid
• If SUPPLIER-TYPE is SUBCONTRACTOR SUPPLIER-RATING must be Highest Quality
• SUPPLIER-STATUS - must be one of the listed 88-level fields

05 SUPP-ADDRESS - three occurrences


• Required fields: ADDRESS-1, CITY, ADDR-STATE and ZIP-CODE
• ADDRESS-TYPE must be one of the 88-level fields
• ZIP-CODE and ADDR-STATE must match in the STATEZIP file (next slide)

05 PURCHASE-ORDER - three occurrences


• Required fields: PO-NUMBER, BUYER-CODE, ORDER-,DATE, QUANTITY
• QUANTITY must be between 0 and 999,999
• If QUANTITY is > 0, UNIT-PRICE must be > 0.
• UNIT-PRICE must be between $1 and $1,000,000.00 *** Required fields means "cannot be blank"
• ORDER-DATE must be a valid date
• DELIVERY-DATE is optional but if there is data, it must be a valid date and the date must be later than
ORDER-DATE
Alaska AK 99501 99950
Alabama AL 35004 36925
Address State/Zip Code Edits Arkansas
Arkansas
AR
AR
71601
75502
72959
75502
You will create a one-dim COBOL table out of this STATEZIP file ➔ Arizona AZ 85001 86556
California CA 90001 96162
• Note that there are many more entries than shown here Colorado CO 80001 81658
• DDS0001.LEARN.STATE.ADDRESS.ZIP Connecticut
Connecticut
CT
CT
06001
06401
06389
06928
Dist of Colum DC 20001 20039
Address records must have a valid State Abbreviation/Zip Code Dist of Colum DC 20042 20599
Dist of Colum DC 20799 20799
combination: Delaware DE 19701 19980
Florida FL 32004 34997
• Example: Georgia GA 30001 31999
Georgia GA 39901 39901
• The zip code for AK must be between 99501 and 99950 Hawaii HI 96701 96898
• The zip code for DC must be between: Iowa IA 50001 52809
Iowa IA 68119 68120
• 20001 ➔ 20039 Idaho ID 83201 83876
• 20042 ➔ 20599 Illinoi IL 60001 62999
Indiana IN 46001 47997
• 20799 ➔ 20799 (Rhetorical question…who lives here?) Kansas KS 66002 67954
Kentucky KY 40003 42788
Note that there are several states with multiple valid Zip Code entries - Louisiana LA 70001 71232
Louisiana LA 71234 71497
thus multiple rows in the file. Question - would it be better to handle Massachusetts MA 01001 02791
this with a Table SEARCH - or PERFORM VARYING operation? Massachusetts MA 05501 05544
Maryland MD 20331 20331
594 Low Zip High Zip
Edited Records - Disposition
If the record passes all the tests in the subprogram:
• The subroutine should send back a return code of zero
• The PARTSUPP (calling program);
• Moves the record data to the associated output file:
• PARTS
• SUPPLIERS
• ADDRESSES
• PURCHASE ORDERS
• Writes the output file
• Writes the existing PARTSUPP file

If the record has any errors:


• The subroutine sends back a return-code of 8
• The PARTSUPP driver program writes the record to the error-file and does
not write the record to the "good record" output file(s)
• If there are < 4 errors:
• The bad record must include error messages in the output file
• Meaning that your output file record layout needs additional space for the
error message(s) that accompany the invalid data fields in the record
• If there are > 3 errors:
• The bad record is written to the output file with a single message that the
record is completely invalid
595
DDS0001.LEARN.COBOL(CDAT2)

Call to 'CEEDAYS'
Date Handling Routines
• Every shop will have one or more date handling routines
(utility programs) - that do date:
• Validation
• Formatting
• Date math (calculate 90-days from the current-
date, etc.)

• IBM provides an "LE" (Language Environment) program called:


CEEDAYS that can do much of the above.

Here's an example of date validation/checking ➔


1. How do you turn this into a called subroutine?
2. If you're working on zserveros please use this program for input
date value edits

If you're working on your own TSO system you might be able to use
'CEEDAYS' - or you can use your own Date utility
IBM Example: https://www.ibm.com/support/knowledgecenter/SSLTBW_2.4.0/com.ibm.zos.v2r4.ceea200/datmul5.htm 596
597

Output file record layouts: DDS0001.COBOL.COPYLIB


PURCHRDS ADRESSES

Write output files using these record layouts. Data in the "good records"
from the PARTSUPP input file will be moved into these records
field-for-field.

SUPLIERS PARTS
You may notice that
the size and/or types
of these output file
record and field
layouts aren't the
same as the
PARTSUPP input file.

You can either modify


the record layout(s) or
program around the
discrepancy.
Report
The file will be sorted on PARTNO. The report should be produced as follows: For each PARTNO
……
Part Name Weeks Lead Time Vehicle Make Supplier Name Supplier Rating
============ =============== ============= ============= =============

FRAMMIS 3 VOLKSWAGON BILL'S FRIENDLY PARTS 88-Level-Quality

Order Address: XXXXXXXXXXXXXXX


Sched Address: XXXXXXXXXXXXXXX
Remit Address: XXXXXXXXXXXXXXX

Total # Purchase Orders: nn  Total number of "good" Purchase Orders for this part
Total Price Purchase Orders: nnnn  Total in the UNIT PRICE fields for good Purchase Orders
Total Quantity in Purchase Orders: $$,$$$,$$9.99  Total in the QUANTITY fields for all "good" Purchase Orders

One of the questions that must be addressed is; where does the data for this report come from?
Since the Part/Supplier program will be creating the "good record" output file, your options are:
• Store the records in an internal COBOL table - in the Part/Supplier driver program
• Write & run another program that creates the above report later in the same batch job stream
• For this you'll need another output data set, created in the JCL
598
Development Suggestions
Re-watch: Report generation:
• Except this time, along with paragraphs you need a higher-level design picture, one that includes drivers & subroutines
Flowchart out the:
• JCL Run Job
• Application - in terms of modules and paragraphs
• Don't forget
Understand every paragraph, statement and variable in the program you're writing - and how each relates back
to the specs. Document the programs as you enter the code:
• Program-level documentation - what the program does
• Paragraph-level documentation - basically pseudo-code
• Specific inline comments - as needed to clarify complex logic
Develop/Document/Test top-down;
• Obtain existing (working) "boiler-plate" code from one of the programs you've already coded;
• ID and ENVIRONMENT DIVISION.
• DATA DIVISION FDs
• PROCEDURE DIVISION;
• OPEN/READ/WRITE/CLOSE
• Housekeeping
• Table loading
• Data validation/Error-handling routines
• Document and Create stub paragraphs
• Compile/Link/COBUCLD stub paragraphs
• Add one scenario at a time - Compile/Link/COBUCLD that and only that scenario
• Test with data that exercises to the specs and beyond
• Force S0C7s, Divide by Zero, Arithmetic Overflow, etc. 599
Individual (not the team approach) Final Exam Specs
Many of you will not be able to - or simply do not want to work in a
team setting
If you don't want to do a team-based final exam, here are your final
exam specifications:
1. Write and test the PARTSUPP (driver) program
2. Only focus on edits and file processing operations for two subroutines;
• PARTS data
• SUPP-ADDRESS data
3. Complete the Control Break Report
4. Create a single bug in the code
Additionally:
• You can "borrow" test data for the PARTSUPP input file from one of the teams
• You can utilize the "skeleton programs" provided by Dave Stagg in this work
600
Top Down Development
First? Read this: http://faculty.salina.k-state.edu/tmertz/Java/200programdesignandtesting/02topdownandbottomupprogramming.pdf
Then…. Step 1:
• After reading and then re-reading the specifications, break the required functionality down into a model consisting of units of functionality.
You can do this with paper/pencil - this might make it easier to visualize the model - plus you can erase (thus the pencil!) and refine the
flow - as your understanding of what's needed deepens over time
The units of functionality in your model will become paragraphs and called programs
• Create programs using the well-named-paragraphs - with one verb in each: DISPLAY <paragraph-name>.
Tie the paragraphs together with PERFORM statements and CALLS (note that the CALLS don't need to pass parameters in Step 1)
Build and Debug the program - Make sure that the execution flow matches your model design
Step 2:
• Transcribe the model (units of functionality) into comments at the top of each paragraph - where they become pseudocode for the paragraph
• The "block of logic should be no more than 10 lines long
• Code boilerplate paragraphs such as: File I/O (OPEN/READ/WRITE/CLOSE), variable Initialization/housekeeping, ABEND Routines
• Add the parameters to the CALLING/CALLED programs.
• Move temporary "stub" values to the parameters prior to the CALL. And in the called programs DISPLAY the values upon ENTRY
• Debug the programs, watching the flow and checking the CALLED/CALLING parameters. Note that for File I/O you'll need JCL DD statements
Step 3 → Step n
• Code COBOL detailed logic for each use case (Edit PART, Edit SUPPLIER, WRITE ERROR, etc.). Isolate the routines - cod and test one at a time.
• In the case of highly complex logic put a break point on the code, run to the break point, and iterate over the logic - changing variable values
to test different paths thru the routine.
• If there are paragraphs or programs that haven't been written, stub out (comment out) the branch to paragraph or program
• Debug the program use case with real data 601
UNIT COBOL for z/OS - Module 25
COBOL Jobs:
• What you know
• What you don't know
• The tools

This module presents unstructured thoughts about competing for jobs in the COBOL business
application space. There are no guarantees implied or otherwise in this material.

602
What you know and what don't you know
If you've finished all the labs/quizzes you know:
• Entry Level "batch" COBOL
• z/OS background: EBCDIC, Compile/Link/Go process
• Language Syntax and deep-dive on language elements
• COBOL programming best practices:
• Code analysis, Business spec analysis, Program design, Coding standards, Modular design, Reusable code
• Program Testing and ABEND resolution
• Trivial JCL
• ISPF - to whatever degree you've worked with it
• Eclipse editing tools - assuming you've used ZOD or IDz

What don't you have: Blue: You can pick up this technology using
YouTube, books and articles. And you can
• JCL and MVS Utilities - DFSORT, IDCAMS, IEBGENER, IEBCOPY practice learning/coding using zTrial
• VSAM Red: You will need a class to master this material
• CICS
Green: You can pick up the foundation of the
• IMS technology without a class - but cannot use zTrial
• DB2/SQL - Interactive SQL, Embedded SQL, Data Modeling for this
• Experience with large COBOL programs and systems
Source Management Systems: CA-Endevor, Serena Changeman, Git, CA-PANVALET,
CA-LIBRARIAN, SCLM, Home Grown Library Systems (PDS)
603
The tools for job searches
There are basically five tools:
1. Networking - for job openings
• LinkedIn
• Personal connections - made thru classes, business
2. The internet
• Monster.com, Indeed.com, glassdoor.com, etc.
• Other search engines
3. Degree
• 4-year, 2-year - Comp Sci degree not necessary for COBOL
• H.S.
• Prior work experience
4. Resume and Cover Letter
• Quality
• Personal
• Technical
5. Interviewing Skills - Interview Q&A sites on the web
• Selling yourself - answer the interviewer's unspoken question: "How does this make me look good?"
• Articulate
• Technical 604
The tools - if you don't have a degree
Become a known quantity:
• Proof of technical abilities
• COBOL:
• Language
• Deep Dive on data types & other concepts from class:
• Hex
• Sort
• etc.
• Program design
• Structured/Analytic thinking
• Linear/Serial thinking ability
• Presence on the Inter Webs:
• Blogs and White Papers
• Interning at companies
605
Miscellaneous Thoughts - 1 of 2
• Need to find something that is uniquely & compellingly you - about COBOL
business application work
• VS Code and IDz Snippets. I'll connect you to IBM team.
• Create Snippets/Templates for; COBOL, PL/I, JCL, SQL
• Create YouTube videos/Vlogs/Blogs, etc.
• DevOps + COBOL:
• Git
• DBB
• You like Production Support?
• Discuss a systematic use of tools to analyze MVS Ret. Codes and/or bad data problems
• You like testing? COBOL lecture on Y.T. Testing would be huge.
• An approach to testing that is YOURS and unique to COBOL would be huge.
• IDz Code Review Rules
• COBOL team development concept using Git
• Team creates a Y.T. video
606
Miscellaneous Thoughts - 2 of 2
• Focus on Maturity
• Understanding of the real-world of work/expectations
• Privilege of working,
• Team player.
• Attention to detail.
• Indefatigable, uncompromising approach to get the job done right.

Your COBOL knowledge is above Entry Level

Choose a vertical
• Medical is your thing,
• Create a DB2 medical data model and write programs
• Y.T. videos on Medical business programming
• Like tech?
• "Inside COBOL" series on YouTube

• Good at speaking
• Teach COBOL

607
608

Useful web-sites for further study


• Throughout the material in this PDF
• Google searches
• Multiple areas:
• Technical
• IBM Knowledge Center
• Job searches
• Business
• The company you're planning to interview with
• Including recruiters
Additional materials
• Books
• Used (always)
• IBM Redbooks (free)
• Your Library
• Free books online

609
Additional materials
• Courses - free & paid
• Khan Academy
• YouTube
• Google Searches

• Forums

• User Communities & User Groups

• Don't forget about zTrial


• Lots of different related zTrials

610

You might also like