COBOL Course - Modules 1 Thru 12 - CICS
COBOL Course - Modules 1 Thru 12 - CICS
COBOL Course - Modules 1 Thru 12 - CICS
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.
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
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
• 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
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
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…
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
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
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?
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
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
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 Books
• A few COBOL and z/OS books on the web
• Have not found an absolute ton of quality
• 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://en.wikipedia.org/wiki/System_software - Systems Software (technical deep-dive - over and above what's necessary for this class)
• 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
• 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
• 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 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
Important note: If given the choice Save the download file (select: Save not Open)
Workshop: Install ZOD on Windows using P2 - 3 of 3
• 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
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.
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
• 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.
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
Mainframe Resources
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
- 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.
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:
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
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:
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
You can also select the bottom window border. Left-click and hold + drag to make the window's height larger
• 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
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:
• Perspective >
• Reset Perspective…
• At the prompt, click Yes
65
Create a new file by Copy/Pasting an existing file
▪ 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)
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.)
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…
72
MVS File Filters - for copying files that are not yours
1. Right-Click on MVS Files and select: New > Filter…
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
7. When the job finishes you should get a 0000 completion code ➔
• Expand the Job
• Open GO:RUN:SYSOUT
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
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
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)
82
SET AUTOMONITOR ON LOG
UNIT COBOL for z/OS - Module 3
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
4. B Area: Cols 12 ➔ 72
Used to code COBOL instructions:
DISPLAY
MOVE
GOBACK
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
Division
Paragraph
Division
Section
Data Definition
Statements
Division
Procedural
Statements
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.
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
• 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
• 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.
• Comments
• PROCEDURE DIVISION Keywords:
• MOVE
• IF/ELSE
• COMPUTE
• DISPLAY
97
The JCL JOB Statement //DDNAME DD DSN=ABCD
• The JOB statement is the first control statement in a job. It marks the beginning of a //JOBNM JOB 504,SMIIH
• 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 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.
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
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
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
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
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 ***
• 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"
• 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
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
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
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
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
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
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
Tutorial: https://www.youtube.com/watch?v=3EmmoUK4JIE
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
z/OS
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
File Records
113234$E£56§78{"#@/投JKJNN靠匚$£§{"erfghhj90-#@1/投IIK靠匚
Sequential File Processing Keywords
113234$E£56§78{"#@/投JKJNN靠匚$£§{"erfghhj90-#@1/投IIK靠匚
113234$E£56§78{"#@/投JKJNN靠匚$£§{"erfghhj90-#@1/投IIK靠匚
READ FILE To
COBOL
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)
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INTERNAL-FILE-NAME ASSIGN TO DDNAME.
SELECT INTERNAL-FILE-NAME ASSIGN TO DDNAME.
DSN=DDS0001.LEARN.DATA,
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.
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
1.
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
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
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.
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:
• 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
• 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
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
156
Sequence, Selection and Iteration - Logic Patterns
DO
Loop
Sequence of instructions
Statement 1 Statement 2 Statement 3
…then… …then…
Iteration Statement
("Priming Read")
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
• GOBACK 160
PAYROL02 - Sample Structured
Sequential File Pattern
The structure of PAYROL02
• 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
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.
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
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
(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
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
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
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
PROCEDURE DIVISION.
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.
• GIVING can be specified: ADD VAR1 TO VAR2 GIVING VAR3 - the total is stored in VAR3
• 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 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
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
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)
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
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
195
Nothing to hand in
196
Nothing to hand in
197
Nothing to hand in
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
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
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.
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 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
• 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.
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.
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.
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 ➔
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.
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
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.
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.
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.
class you will use a lot less., Space Space Space Space
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
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
• 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
Press <Enter>
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)
• 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
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
• 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
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.
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
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
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
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.
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
• 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-0: Conflict between record length specifications (program vs. JCL vs. dataset label)
S001-5: Logic error (either forgot to close file, or end-of-file-switch not set, overwritten or ignored)
Defensive Programming:
3. Select File and verify LRECL from the Properties View 263
S001: Record Length/Block Size - Discrepancy
Defensive Programming:
2.
5.
4. 1.
3.
264
S013: Conflicting DCB Parameters
265
S013: Block Size - Discrepancy
Defensive Programming:
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:
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
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
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
- 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
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
- (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
• 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.
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
• http://www.jsayles.com/tech/cobol/ABEND.htm
• http://ibmmainframes.com/references/a29.html
• http://faculty.madisoncollege.edu/schmidt/mainframe/abendcodes.html
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
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
• They are considered a "Best Practice" for COBOL coding - as they explicitly
define the extent of the keyword operation.
.
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.
• 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.
297
298
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.
• 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.
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
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)
Coding Styles -
Tools
• IDz and ZOD provide
automated code
formatting
capabilities:
• Source ➔ Format
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
• 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).
• 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
Sample
Data
318
Mid-Term Exam Spec: 2 of 5 - Business Logic
• 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
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
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…
*** 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)
• 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:
…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.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
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)
This is an UPPERCASE
rendering of the literal
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
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.
Usage guidelines:
https://www.ibm.com/support/knowledgecenter/SS6SG3_4.2.0/com.ibm.entcobol.doc_4.2/PGandLR/tasks/tpbeg18.htm
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
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) ")".
• 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
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
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
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).
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
>--+-------------------------------------------------------------------------------------+-->
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.
• 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.
.------------------------------------------------------------------------------------.
5. INSPECT |
|
V
.-------------------------------------------------------------. |
|
V
.------------------.
V |
||
||
>----identifier-2--FOR----+-CHARACTERS----+--------------+-+------------------------+-+-+-><
The INSPECT statement examines |
|
'-| phrase 1 |-' |
.----------------------------------------. |
characters or groups of characters in a |
|
|
V
.------------------. | |
V |||
|--+-BEFORE-+--+---------+--+-identifier-4-+--------------------|
'-AFTER--' '-INITIAL-' '-literal-2----'
STRING
'(' TEL-NBR(1:3) ') ' TEL-NBR(4:3) '-' TEL-NBR(7:4)
DELIMITED BY SIZE
INTO CUST-PHONE.
END-STRING.
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
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
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
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.
01 EMPLOYEE-RECORD
05 EMPLOYEE-NAME 05 EMPLOYEE-PHONES
00000000001111111112222222222333333333344444444445555555555
12345678901234567890123456789012345678901234567890123456789
365
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
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
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
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.
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:
• 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.
• 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
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.
EMPFILE Records
COBOL Table Declaration
EMPLOYEE-NAME
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
Divisions •
•
Create
Maintain
•
•
Consistency
Compliance
Nothing to hand in 377
• 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)
380
Nothing to hand in
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
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
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).
• 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.
PROCEDURE DIVISION.
SET TX-IDX TO 1.
• SET statement
SEARCH SALES-TAX-ITEM
• Sequential Search
AT END PERFORM 700-INVALID-TAX-ID
• 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.
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
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
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
396
Optional Workshop 16.2c - Maintenance on Editing/Validation Program
Formatted
Phone# New Output Fields in the report
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
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
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
STUDENT-GRADES
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).
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 ***
• 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:
BR R BR R BR R
DD record D record DD record D record DD record D record …
WW W WW W WW W
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
Divisions •
•
Create
Maintain
•
•
Consistency
Compliance
Nothing to hand in
Browse
DDS0001.LEARN.STUDENT.COURSES -
and visually map the repeating data
areas of each record to the DATA
DIVISION layout (…STUDENT-TABLE…)
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
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
• 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
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
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) ➔
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"
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**
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
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.
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
Not End-of-File ➔
431
ENVIRONMENT DIVISION.
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
Divisions •
•
Create
Maintain
•
•
Consistency
Compliance
Nothing to hand in
436
Nothing to hand in
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.
Field Billing
DATEV
Verification
2. Called "Utilities"
• Date routines
• Complex edits
• Calculations or routines - that changes frequently
• Non-business, but software-application requirements:
• Auditing/Balancing
• Logging
• Security/Validation
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
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.
CLMPAID
CALL 'SUBROGATION' USING WS-POLNO
WS-CLAIMNO, WS-CLAIM-AMT
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
• 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
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.
3. Data -
• QSAM, VSAM, DL/I, DB2 QSAM VSAM DB2 DL/I
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
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
461
Nothing to hand in 462
463
Nothing to hand in
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
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#
Standard Defaults
Some also like: PF4 . . . CANCEL
475
ISPF =1 1.
** "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
482
ISPF =3.8 - Outlist
Alternative to SDSF
Requires:
• JOBNAME
• MSGCLASS
• JOBID
• Wildcards work
• Use tso st Command Line
Command to obtain
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
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
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
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
DB2 Tables
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.
TABLESPACE
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
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 ➔
Window
Show View ➔ Other…
Data Source Explorer ➔
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
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
Primary Key
Foreign Key
Primary Key
Foreign Key
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
521
Elements and Infrastructure - Non-operational SQL Statements
DATA DIVISION.
…
WORKING-STORAGE SECTION EXEC SQL INCLUDE PAYROLL END-EXEC.
• DCLGEN copybook
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.
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.
• Grant/Privileges L
• Meta-Data
G
ALTER TABLE PAYROLL ADD CONSTRAINT NBR PRIMARY KEY E
(NBR);
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
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
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…
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
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 also that you may use two or more of the above options
Nothing to hand in 536
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
You will have access to the DSN81101 tables from the DALLASB system
Nothing to hand in 538
IMS https://en.wikipedia.org/wiki/IBM_Information_Management_System
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
Divisions •
•
Create
Maintain
•
•
Consistency
Compliance
541
Central Data
Repository
DBMS
543
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
z/OS
Input/Output Files
Your COBOL/IMS
QSAM
Application
VSAM
IMS
Data
Base
545
PURCHASE Segment
Segment
Type
ADDRESSES Type
ORDERS
546
cccccccccc
Fdsdddddddddddd
Fdsssssssssssssssss
Fdsdsdsff
Ds SUPPLIERS
Fdsfdsds sffffffsddddddd Fdsfdsf
PURCHASE
DATE Fdsfs
PURCHASE ORDER
Sfffffffffff Fdsdddddddddddd Fdsdsdsff
ddd
ADDRESSES
Sfffffffffff Fdsddddddddddddd Fdsdsdsff
cccccccccc Fdsssssssssssssssss Ds
cccccccccc Fdssssssssssssssssss Ds
ss
sssssss
sffffffsddddddd
ccccccccccc
Fdsfdsf
sssssssssssssssssss
ORDERS
sssssss ccccccccccc ssssssssssssssssssss
547
240 Bytes
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).
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
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
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
GN EMPLOYEEb
4. DL/I Calls - Qualified Segment Search Arguments
2. Qualified SSAs identify specific occurrences of segments
8 1 8 2 1-255
b= or EQ, = or NE
b> or GT, >= or GE
b< or LT, <= or LE
GU EMPLOYEE(SERIALbb=b123456)
562
PROCESSING TERMINATION
5
Creates a "COMMIT" event
DL/I
© Copyright IBM Corporation 2008 DL/I MODULES AREA
564
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
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
CALL
© Copyright IBM Corporation 2008
568
UNIT COBOL for z/OS - Module 23
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
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 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.
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
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
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.)
SUPPEDIT
Part- Called
Batch SORT
JCL PARTSUPP Suppliers Programs
ADDREDIT
Suppliers POEDIT
Job
Addresses ERRORFILE
Statistics 592
593
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
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.)
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
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.
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.
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
609
Additional materials
• Courses - free & paid
• Khan Academy
• YouTube
• Google Searches
• Forums
610