0% found this document useful (0 votes)
10 views45 pages

Important Mainframe Questions

The document outlines common SQL error codes in DB2, their causes, and resolutions, including codes like -904 for resource unavailability and -811 for multiple rows returned. It also provides COBOL programming examples for accessing various VSAM file types and handling file errors. Additionally, it explains the COBOL OCCURS clause for defining arrays.

Uploaded by

srb120397
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views45 pages

Important Mainframe Questions

The document outlines common SQL error codes in DB2, their causes, and resolutions, including codes like -904 for resource unavailability and -811 for multiple rows returned. It also provides COBOL programming examples for accessing various VSAM file types and handling file errors. Additionally, it explains the COBOL OCCURS clause for defining arrays.

Uploaded by

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

Important mainframe questions –

SQL Code -904 is a common DB2 error indicating that a resource required for the
operation is unavailable.

Common Causes:
1. Table space is unavailable: The table space might be in a utility state, in use, or stopped.
2. Lock issues: Another transaction may have locked the resource.
3. Disk space issues: Insufficient disk space for the table space or index.
4. Resource stopped: The table space or index might not be started.
5. Incorrect configuration: The resource might not be correctly defined or accessible.

SQL Code -811 occurs in DB2 when a query retrieves more than one row, but the context of
the query or the way it's written expects only one row.

SQL Code +100 in DB2 indicates that a query executed successfully but no rows matched the
criteria specified in the SQL statement. This is not an error but rather a warning.

1. Check for Empty Results:

 Verify that your query criteria are correct.


 Run the query without filters to check if any data exists in the table.

2. Handle the +100 Warning in the Application Logic:

 For programs using SQL, handle the warning code to avoid unexpected behavior.

SQL Code -305 in DB2 occurs when a NULL value is encountered, but the program or query
does not handle it appropriately.

Causes of SQL Code -305:

1. Null Data Without an Indicator Variable:


o A column in the result set or an expression evaluates to NULL, and the application does not
provide an indicator variable to handle it.
o For example, fetching a NULL value into a host variable without an indicator.
2. Host Variable Constraints:
o The host variable does not accommodate NULLs, and there is no alternative logic to process them.
SQL Code -803 in DB2 indicates that a query attempted to insert or update a row, but this
operation would result in a duplicate value in a column or combination of columns defined as
a unique key or primary key.

Causes of SQL Code -803:

1. Duplicate Key Violation:


o The value being inserted or updated already exists in a column or combination of columns that
have a UNIQUE constraint or PRIMARY KEY constraint.
2. Index Violation:
o The error may involve a specific unique index on a table, as indicated in the error message.
3. Incorrect Application Logic:
o The program or application may be attempting to insert duplicate rows unintentionally.

Statement to fetch first 10 rows from a table –

DB2 –

SELECT *

FROM TABLE_NAME

FETCH FIRST 10 ROWS ONLY;

SQL-

SELECT *

FROM TABLE_NAME

LIMIT 10;

Here are the different types of PERFORM statements in COBOL (often used with DB2
programs), explained briefly:

1. PERFORM UNTIL

 Executes a block of code repeatedly until a specified condition is true.


 Example:

PERFORM FETCH-CURSOR UNTIL SQLCODE = +100.


 Use: Loops until a condition, like fetching rows from a DB2 cursor.

2. PERFORM TIMES

 Executes a block of code a specific number of times.


 Example:

PERFORM DISPLAY-DETAILS 5 TIMES.

 Use: When the number of iterations is known beforehand.

3. PERFORM THRU

 Executes a series of paragraphs in sequence.


 Example:

PERFORM INIT-PROCESS THRU FINAL-CLEANUP.

 Use: To execute multiple related paragraphs in a defined order.

4. PERFORM INLINE

 Executes a block of code written directly within the PERFORM statement.


 Example:

PERFORM

DISPLAY "Processing row."

END-PERFORM.

 Use: For single-use or short operations that don’t require modular paragraphs.

5. PERFORM VARYING

 Executes a block of code repeatedly while incrementing or decrementing a variable.


 Example:

PERFORM DISPLAY-ROWS

VARYING I FROM 1 BY 1 UNTIL I > 10.

 Use: Useful for loops with variable-controlled iterations, like iterating over table rows.

UNSTRING FUNCTION TO FETCH DATA IN COBOL –


PROCEDURE DIVISION.

UNSTRING Input-String

DELIMITED BY '|'

INTO Field1 Field2 Field3 Field4

END-UNSTRING.

DISPLAY "Field1: " Field1

DISPLAY "Field2: " Field2

DISPLAY "Field3: " Field3

DISPLAY "Field4: " Field4.

STOP RUN.

STRING FUNCTION TO FETCH DATA IN COBOL –

PROCEDURE DIVISION.

STRING Field1 DELIMITED BY SPACE

Field2 DELIMITED BY SPACE

Field3 DELIMITED BY SPACE

INTO Output-String

END-STRING.

DISPLAY "Output-String: " Output-String.

STOP RUN.

PROCEDURE DIVISION.
STRING Field1 DELIMITED BY SPACE

'|' DELIMITED BY SIZE

Field2 DELIMITED BY SPACE

'|' DELIMITED BY SIZE

Field3 DELIMITED BY SPACE

'|' DELIMITED BY SIZE

Field4 DELIMITED BY SPACE

INTO Output-String

END-STRING.

DISPLAY "Output-String: " Output-String.

STOP RUN.

VSAM FILES –

In COBOL, the four types of VSAM (Virtual Storage Access Method) files are:

1. KSDS (Key Sequenced Data Set): A VSAM file that is indexed by a key and maintains records in
sequential order based on that key.
2. RRDS (Relative Record Data Set): A VSAM file in which records are accessed by their relative
position (record number) rather than a key.
3. ESDS (Entry Sequenced Data Set): A VSAM file where records are added sequentially, and they
are accessed by their physical position in the file.
4. LDS (Linear Data Set): A type of VSAM file that holds a linear sequence of data, not accessible by
any key, index, or record number.
VSAM
Access Method Record Access Key Usage File Structure Usage
Type

Random and Key-based, Stores records that require


KSDS Indexed Required
Sequential Indexed fast access by key

Indexed by Random access by Not Fixed-length Stores records accessed by


RRDS
Relative Record relative position required records their relative position

Not Stores records added


ESDS Sequential Sequential Entry-based
required sequentially

Stores unstructured data in a


Not linear form
LDS Sequential Sequential Linear storage
required

Here’s a short explanation and COBOL code examples for creating and accessing all four types
of VSAM files:

1. KSDS (Key Sequenced Data Set)

Creation (IDCAMS):

//CREATE-KSDS JOB
//STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=A
//SYSIN DD *
DEFINE CLUSTER(
NAME(MY.KSDS.FILE)
RECSZ(100)
KEYS(10 0)
DATA(MY.KSDS.DATA)
INDEX(MY.KSDS.INDEX)
SHAREOPTIONS(3,3)
)
/*

Access (COBOL):

FD KSDSFile.
01 KSDS-Record.
05 Key PIC X(10).
05 Data PIC X(90).

FILE-CONTROL.
SELECT KSDSFile ASSIGN TO 'MY.KSDS.FILE'
ORGANIZATION IS INDEXED
ACCESS MODE IS RANDOM
RECORD KEY IS Key
FILE STATUS IS WS-FileStatus.

PROCEDURE DIVISION.
OPEN INPUT KSDSFile.
READ KSDSFile INTO KSDS-Record.
CLOSE KSDSFile.

2. RRDS (Relative Record Data Set)

Creation (IDCAMS):

//CREATE-RRDS JOB
//STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=A
//SYSIN DD *
DEFINE CLUSTER(
NAME(MY.RRDS.FILE)
RECSZ(100)
DATA(MY.RRDS.DATA)
INDEX(MY.RRDS.INDEX)
SHAREOPTIONS(3,3)
)
/*

Access (COBOL):

FD RRDSFile.
01 RRDS-Record.
05 Data PIC X(100).

FILE-CONTROL.
SELECT RRDSFile ASSIGN TO 'MY.RRDS.FILE'
ORGANIZATION IS RELATIVE
ACCESS MODE IS RANDOM
RECORD KEY IS WS-RecordNumber
FILE STATUS IS WS-FileStatus.

PROCEDURE DIVISION.
OPEN INPUT RRDSFile.
READ RRDSFile INTO RRDS-Record.
CLOSE RRDSFile.

3. ESDS (Entry Sequenced Data Set)

Creation (IDCAMS):

//CREATE-ESDS JOB
//STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=A
//SYSIN DD *
DEFINE CLUSTER(
NAME(MY.ESDS.FILE)
RECSZ(100)
DATA(MY.ESDS.DATA)
SHAREOPTIONS(3,3)
)
/*

Access (COBOL):

FD ESDSFile.
01 ESDS-Record.
05 Data PIC X(100).

FILE-CONTROL.
SELECT ESDSFile ASSIGN TO 'MY.ESDS.FILE'
ORGANIZATION IS SEQUENTIAL
ACCESS MODE IS SEQUENTIAL
FILE STATUS IS WS-FileStatus.

PROCEDURE DIVISION.
OPEN INPUT ESDSFile.
READ ESDSFile INTO ESDS-Record.
CLOSE ESDSFile.

4. LDS (Linear Data Set)

Creation (IDCAMS):

//CREATE-LDS JOB
//STEP1 EXEC PGM=IDCAMS
//SYSPRINT DD SYSOUT=A
//SYSIN DD *
DEFINE NONINDEXED
NAME(MY.LDS.FILE)
RECSZ(100)
DATA(MY.LDS.DATA)
SHAREOPTIONS(3,3)
)
/*

Access (COBOL):

FD LDSFile.
01 LDS-Record.
05 Data PIC X(100).

FILE-CONTROL.
SELECT LDSFile ASSIGN TO 'MY.LDS.FILE'
ORGANIZATION IS LINEAR
ACCESS MODE IS SEQUENTIAL
FILE STATUS IS WS-FileStatus.

PROCEDURE DIVISION.
OPEN INPUT LDSFile.
READ LDSFile INTO LDS-Record.
CLOSE LDSFile.
COBOL Program to Read a Flat File
IDENTIFICATION DIVISION.
PROGRAM-ID. ReadFlatFile.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT FlatFile ASSIGN TO 'MY.FLAT.FILE'
ORGANIZATION IS SEQUENTIAL
ACCESS MODE IS SEQUENTIAL
FILE STATUS IS FileStatus.

DATA DIVISION.
FILE SECTION.
FD FlatFile.
01 FlatFile-Record PIC X(80).

WORKING-STORAGE SECTION.
01 EOF-Flag PIC X VALUE 'N'.
01 FileStatus PIC 9(2).
01 WS-EOF PIC X VALUE 'N'.

PROCEDURE DIVISION.
OPEN INPUT FlatFile.

PERFORM UNTIL WS-EOF = 'Y'


READ FlatFile INTO FlatFile-Record
AT END
MOVE 'Y' TO WS-EOF
NOT AT END
DISPLAY "Record: " FlatFile-Record
END-READ
END-PERFORM.

CLOSE FlatFile.

STOP RUN.

FILE ERRORS AND ITS RESOLUTION-


Common COBOL File Errors and Resolutions
Error
Error Description Resolution
Code

00 Successful operation No action needed. The operation completed successfully.

Duplicate key found (for Verify the logic; ensure the key is unique when inserting a new
02
KSDS) record.

Read attempted on an Initialize the file with records before reading, or handle the empty
04
empty file file case.

Check for AT END condition and handle it appropriately in the


10 End of file reached
program logic.

Ensure the key value exists in the dataset before attempting


21 Invalid key (for KSDS/RRDS)
access.

Avoid inserting a record with a key that already exists; handle


22 Duplicate key (for KSDS)
duplicates in the logic.

Record not found (for Ensure the key exists in the dataset or handle INVALID KEY
23
KSDS/RRDS) condition gracefully.

Open the file using OPEN before performing read/write


30 File is not open
operations.

Ensure the file exists in the specified location or correct the file
35 File not found
path in the program.

File is open in the wrong Open the file in the correct mode (e.g., INPUT, OUTPUT) based on
37
mode the operation.

Ensure the program file layout matches the dataset definition


39 File attribute mismatch
(e.g., record length).

41 File already open Avoid multiple OPEN operations on the same file in the program.

Ensure no other process is using the file; use SHAREOPTIONS to


43 File is locked
allow concurrent access.

File not open for Check the OPEN statement; ensure the correct access mode
46
input/output (INPUT/OUTPUT/EXTEND/IO).

47 Read attempted on a file not Open the file in INPUT or I-O mode before performing read
Error
Error Description Resolution
Code

opened operations.

Write attempted on a file Open the file in OUTPUT or I-O mode before performing write
48
not opened operations.

Delete attempted on a file


49 Open the file in I-O mode before performing delete operations.
not opened

Logic error (e.g., invalid Check program logic, especially record definitions, and correct
92
record length) mismatched lengths.

Ensure the ASSIGN clause in the ENVIRONMENT DIVISION


93 File not assigned
correctly references the file.

Increase the file size allocation or handle record overflow


94 File size limit exceeded
conditions.

DB2 File errors and its resolution –

Common DB2 Errors and Resolutions


SQLCODE Error Description Resolution

No action needed; the query or operation completed


0 Successful execution
successfully.

No rows found or end of cursor Handle the condition using program logic; check if no rows
+100
reached is valid for your operation.

Shorten the string or increase the target column size in the


-102 String exceeds maximum length
schema.

Invalid date, time, or timestamp Verify and correct the date/time value format before
-180
format executing the query.

Object not found (e.g., table, view, Ensure the object exists in the schema or correct the object
-204
index) name in the query.

Verify column names in the query match the table


-206 Column name not found
definition.
SQLCODE Error Description Resolution

Null value fetched into a non- Allow NULLs or use COALESCE to provide default values for
-305
nullable host variable NULL.

Decimal or numeric conversion Check data type compatibility and ensure values fit the
-310
error target column’s precision/scale.

Null value not allowed for a Ensure the column is populated or modify the table to
-407
column allow NULL values.

Verify that the parent record exists before inserting or


-530 Foreign key constraint violation
updating child records.

Deletion violates a referential Delete dependent child records first, or cascade deletes
-532
constraint using the foreign key definition.

Grant necessary privileges or check access rights for the


-551 Insufficient privileges
operation.

Ensure the data is unique for unique/indexed columns


-803 Duplicate key violation
before inserting/updating.

Bind the package correctly to the database or verify the


-805 DBRM/Package not found
plan and package definitions.

More than one row returned in a Use a FETCH FIRST 1 ROW ONLY clause or rewrite the
-811
singleton SELECT query to return only one row.

Timestamp mismatch between


-818 Rebind the program to synchronize timestamps.
program and DBRM

Verify resource availability and resolve issues like


-904 Resource unavailable
tablespace full or locked objects.

Review locking strategy, ensure transactions


-911 Deadlock or timeout
commit/rollback promptly, or retry the operation.

Deadlock or timeout Retry the transaction and investigate locking contention in


-913
(uncommitted dependency) the system.

Contact the DB2 administrator to grant appropriate access


-922 Authorization required
privileges.

-927 Program not precompiled with Ensure the COBOL program is precompiled and compiled
SQLCODE Error Description Resolution

DB2 correctly with the DB2 precompiler.

OCCURS IN COBOL –

Defining and Accessing OCCURS in COBOL

01 STUDENT-MARKS.
05 MARKS PIC 9(3) OCCURS 5 TIMES.

 MARKS: An array that can store 5 elements, each 3 digits wide.

Accessing OCCURS

 Sequential Access Use an index or a loop to access each element.


 PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 5
 DISPLAY "MARKS(" IDX "): " MARKS(IDX)
 END-PERFORM.

 Direct Access Access specific elements directly using subscripts.


 MOVE 100 TO MARKS(1).
 DISPLAY MARKS(1).

Complete Example

IDENTIFICATION DIVISION.
PROGRAM-ID. OccursExample.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 STUDENT-MARKS.
05 MARKS PIC 9(3) OCCURS 5 TIMES.
01 IDX PIC 9 VALUE 1.

PROCEDURE DIVISION.
PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 5
MOVE IDX * 10 TO MARKS(IDX)
END-PERFORM.

DISPLAY "Marks: "


PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 5
DISPLAY MARKS(IDX)
END-PERFORM.
STOP RUN.

REDEFINES in COBOL

The REDEFINES clause allows a single storage area in memory to be referenced by different data
definitions, enabling multiple views of the same data.

Definition
01 EMPLOYEE-RECORD.
05 EMP-NAME PIC X(20).
05 EMP-DETAILS REDEFINES EMP-NAME.
10 FIRST-NAME PIC X(10).
10 LAST-NAME PIC X(10).

 EMP-NAME: The full name stored as a single field.


 EMP-DETAILS: Allows the same data to be accessed as FIRST-NAME and LAST-NAME.

Access

 Access Original Definition


 MOVE "JohnSmith " TO EMP-NAME.
 DISPLAY EMP-NAME. * Output: JohnSmith

 Access Redefined Fields


 DISPLAY FIRST-NAME. * Output: John
 DISPLAY LAST-NAME. * Output: Smith

Use Cases

 Memory Optimization: Share memory for multiple purposes.


 Data Transformation: Treat data in different formats (e.g., numeric, alphanumeric).

Key Points

 One Storage Area: Both original and redefined fields share the same memory.
 Sequential Access: You can switch between the views seamlessly.
INSPECT in COBOL

The INSPECT statement is used for examining and modifying strings in COBOL. It can count,
replace, or convert characters in a string.

Syntax
INSPECT string TALLYING or REPLACING options.

Access and Examples

1. Counting Characters

INSPECT STRING TALLYING COUNT FOR ALL 'A'.

 Counts occurrences of 'A' in STRING and stores in COUNT.

2. Replacing Characters

INSPECT STRING REPLACING ALL 'A' BY 'B'.

 Replaces all occurrences of 'A' with 'B' in STRING.

3. Replacing First Occurrence

INSPECT STRING REPLACING FIRST 'A' BY 'B'.

 Replaces the first occurrence of 'A' with 'B'.

Key Points

1. TALLYING: Counts specific characters.


2. REPLACING: Modifies specific characters.
3. Flexible: Works with ALL or FIRST occurrences.

CURSORS IN DB2 –
Cursors in DB2

A cursor in DB2 is a database object used to retrieve multiple rows from a query one at a time in
a sequential manner.

Definition

 Declare: Defines the SQL query to fetch rows.


 EXEC SQL
 DECLARE CURSOR_NAME CURSOR FOR SELECT COLUMN1, COLUMN2 FROM
TABLE_NAME
 END-EXEC.

 Open: Executes the query and positions the cursor before the first row.
 EXEC SQL
 OPEN CURSOR_NAME
 END-EXEC.

 Fetch: Retrieves rows one by one into host variables.


 EXEC SQL
 FETCH CURSOR_NAME INTO :HOST-VAR1, :HOST-VAR2
 END-EXEC.

 Close: Releases the resources used by the cursor.


 EXEC SQL
 CLOSE CURSOR_NAME
 END-EXEC.

Access in COBOL DB2 Program

Example

IDENTIFICATION DIVISION.
PROGRAM-ID. CursorExample.

ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 HOST-VAR1 PIC X(20).
01 HOST-VAR2 PIC 9(4).
01 SQLCODE PIC S9(9) COMP.

EXEC SQL INCLUDE SQLCA END-EXEC.

PROCEDURE DIVISION.
EXEC SQL
DECLARE CURSOR1 CURSOR FOR
SELECT EMP_NAME, EMP_AGE FROM EMPLOYEE_TABLE
END-EXEC.

EXEC SQL
OPEN CURSOR1
END-EXEC.

PERFORM UNTIL SQLCODE NOT = 0


EXEC SQL
FETCH CURSOR1 INTO :HOST-VAR1, :HOST-VAR2
END-EXEC

IF SQLCODE = 0
DISPLAY "NAME: " HOST-VAR1
DISPLAY "AGE: " HOST-VAR2
END-IF
END-PERFORM.

EXEC SQL
CLOSE CURSOR1
END-EXEC.

STOP RUN.

1. Declare the cursor with the DECLARE statement.


2. Open the cursor using OPEN.
3. Fetch rows sequentially with FETCH.
4. Close the cursor to release resources.

1. Use SQLCODE to handle end-of-data (SQLCODE = +100).


2. Host variables (:HOST-VARS) must match the columns' data types.
3. Use PERFORM UNTIL for iterative row processing.

COBOL-DB2 Program: Read Records from a File and Insert into a DB2 Table
IDENTIFICATION DIVISION.
PROGRAM-ID. FileToDB2.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INFILE ASSIGN TO 'INPUTFILE.DAT'
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD INFILE.
01 INFILE-RECORD.
05 EMP-ID PIC 9(5).
05 EMP-NAME PIC X(20).
05 EMP-SALARY PIC 9(7).

WORKING-STORAGE SECTION.
01 WS-EMP-ID PIC 9(5).
01 WS-EMP-NAME PIC X(20).
01 WS-EMP-SALARY PIC 9(7).
01 SQLCODE PIC S9(9) COMP.
01 END-OF-FILE PIC X VALUE 'N'.

EXEC SQL INCLUDE SQLCA END-EXEC.

PROCEDURE DIVISION.
MAIN-PARA.
PERFORM INIT-PARA.
PERFORM UNTIL END-OF-FILE = 'Y'
PERFORM READ-FILE-PARA
IF END-OF-FILE NOT = 'Y'
PERFORM DB2-INSERT-PARA
END-IF
END-PERFORM.
PERFORM CLOSE-PARA.
STOP RUN.

INIT-PARA.
OPEN INPUT INFILE.

READ-FILE-PARA.
READ INFILE INTO INFILE-RECORD
AT END
MOVE 'Y' TO END-OF-FILE
END-READ.

MOVE EMP-ID TO WS-EMP-ID.


MOVE EMP-NAME TO WS-EMP-NAME.
MOVE EMP-SALARY TO WS-EMP-SALARY.

DB2-INSERT-PARA.
EXEC SQL
INSERT INTO EMPLOYEE_TABLE (EMP_ID, EMP_NAME, EMP_SALARY)
VALUES (:WS-EMP-ID, :WS-EMP-NAME, :WS-EMP-SALARY)
END-EXEC.

IF SQLCODE NOT = 0
DISPLAY "DB2 INSERT ERROR: " SQLCODE
END-IF.

CLOSE-PARA.
CLOSE INFILE.
1. File Handling:
o INFILE is defined as a line sequential file for reading.
o Records are read into INFILE-RECORD and mapped to WS- fields.

2. DB2 Insert Operation:


o The INSERT statement adds each record into the EMPLOYEE_TABLE.
o Host variables (WS-EMP-ID, etc.) are used to pass file data to DB2.

3. Control Flow:
o The PERFORM loop reads records until the end of the file (END-OF-FILE = 'Y').
o Each record is processed by READ-FILE-PARA and inserted by DB2-INSERT-PARA.

4. Error Handling:
o The program checks SQLCODE after each DB2 operation to ensure successful execution.

10001John Smith 050000


10002Jane Doe 060000
10003Alice Brown 070000

 Ensure that the DB2 table structure matches the INSERT statement fields.
 Handle file and database errors to ensure data integrity.
 Use the SQLCODE to identify DB2 execution issues (0 = success, -nnn = errors).

MATCHING RECORD FROM TWO FILES –


Procedure Division Explanation
PROCEDURE DIVISION.
MAIN-PARA.
PERFORM INIT-PARA. * Open files and read the first record from
both input files.
PERFORM MATCH-PARA UNTIL * Loop until the end of any file is reached.
EOF-FILE1 = 'Y' OR EOF-FILE2 = 'Y'.
PERFORM CLOSE-PARA. * Close all files.
STOP RUN.

INIT-PARA.
OPEN INPUT FILE1 FILE2 * Open both input files for reading.
OUTPUT OUTFILE. * Open output file for writing.
READ FILE1 INTO FILE1-RECORD * Read the first record from FILE1.
AT END MOVE 'Y' TO EOF-FILE1. * Mark EOF if no record is found.
READ FILE2 INTO FILE2-RECORD * Read the first record from FILE2.
AT END MOVE 'Y' TO EOF-FILE2. * Mark EOF if no record is found.

MATCH-PARA.
IF FILE1-ID = FILE2-ID * Check if IDs from both files match.
MOVE FILE1-ID TO OUT-ID * Copy matching data to output record.
MOVE FILE1-NAME TO OUT-NAME
WRITE OUTFILE-RECORD * Write the matching record to the output
file.
READ FILE1 INTO FILE1-RECORD * Read next record from both files.
AT END MOVE 'Y' TO EOF-FILE1
READ FILE2 INTO FILE2-RECORD
AT END MOVE 'Y' TO EOF-FILE2
ELSE IF FILE1-ID < FILE2-ID * If FILE1-ID is smaller, read next from
FILE1.
READ FILE1 INTO FILE1-RECORD
AT END MOVE 'Y' TO EOF-FILE1
ELSE * Otherwise, read next from FILE2.
READ FILE2 INTO FILE2-RECORD
AT END MOVE 'Y' TO EOF-FILE2
END-IF.

CLOSE-PARA.
CLOSE FILE1 FILE2 OUTFILE. * Close all files after processing.

1. INIT-PARA:
o Opens the files and reads the first record from each input file.
2. MATCH-PARA:
o Compares FILE1-ID and FILE2-ID:
 If IDs match, writes the record to the output file and reads the next records
from both input files.
 If IDs differ, advances the file with the smaller ID.
3. CLOSE-PARA:
o Closes all files to complete processing.

 Ensure input files are sorted by IDs.


 Efficient matching with minimal reads ensures high performance.
 Stops processing gracefully when any file reaches its end.

COBOL FILE COUNT CODE -

COBOL Program to Write the Number of Records in a File

This program reads a file and counts the number of records, then writes the count to an output
file.

IDENTIFICATION DIVISION.
PROGRAM-ID. RecordCount.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INFILE ASSIGN TO 'INPUTFILE.DAT'
ORGANIZATION IS LINE SEQUENTIAL.
SELECT OUTFILE ASSIGN TO 'RECORDCOUNT.TXT'
ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD INFILE.
01 INFILE-RECORD.
05 RECORD-DATA PIC X(100). * Adjust size as per record structure.

FD OUTFILE.
01 OUTFILE-RECORD.
05 RECORD-COUNT PIC 9(5).

WORKING-STORAGE SECTION.
01 RECORD-COUNTER PIC 9(5) VALUE 0.
01 EOF-FILE PIC X VALUE 'N'.

PROCEDURE DIVISION.
MAIN-PARA.
PERFORM INIT-PARA.
PERFORM COUNT-RECORDS UNTIL EOF-FILE = 'Y'.
PERFORM WRITE-COUNT.
PERFORM CLOSE-PARA.
STOP RUN.

INIT-PARA.
OPEN INPUT INFILE.
OPEN OUTPUT OUTFILE.
MOVE 0 TO RECORD-COUNTER.
COUNT-RECORDS.
READ INFILE INTO INFILE-RECORD
AT END MOVE 'Y' TO EOF-FILE
END-READ.

IF EOF-FILE NOT = 'Y'


ADD 1 TO RECORD-COUNTER
END-IF.

WRITE-COUNT.
MOVE RECORD-COUNTER TO RECORD-COUNT.
WRITE OUTFILE-RECORD.

CLOSE-PARA.
CLOSE INFILE OUTFILE.

1. File Handling:
o INFILE: Input file being read.
o OUTFILE: Output file where the record count is written.

2. Counting Logic:
o The program reads the input file record by record.
o For each record read, the RECORD-COUNTER is incremented.

3. Writing Count:
o After all records are processed, the total count (RECORD-COUNTER) is written to the
output file.

4. Control Flow:
o The program loops until the end of the input file (EOF-FILE = 'Y'), incrementing the
counter on each read.
o The record count is written once all records are counted.

Key Point

 EOF Handling: The end of the file is detected by checking the AT END condition in the READ
statement.
 Count Writing: After counting, the RECORD-COUNTER is moved to the OUTFILE-RECORD and
written to the output file.

JCL SORT CARDS –


//JOBNAME JOB (ACCT),'NAME',CLASS=A,MSGCLASS=A,NOTIFY=&SYSUID
//STEP1 EXEC PGM=SORT
//SORTIN1 DD DSN=INPUTFILE1,DISP=SHR
//SORTIN2 DD DSN=INPUTFILE2,DISP=SHR
//SORTOUT DD DSN=OUTFILE,DISP=(NEW,CATLG),SPACE=(CYL,(1,1))
//SYSOUT DD SYSOUT=*
//SYSIN DD *
SORT FIELDS=(1,5,CH,A) /* Sort on the first 5 characters */
JOINKEYS FILE=1,FIELDS=(1,5) /* Join on the first 5 characters
*/
JOINKEYS FILE=2,FIELDS=(1,5)
REFORMAT FIELDS=(1,5,11,20) /* Format output as required */
OPTION COPY /* Copy matching records to output
*/

//STEP2 EXEC PGM=SORT


//SORTIN1 DD DSN=INPUTFILE1,DISP=SHR
//SORTIN2 DD DSN=INPUTFILE2,DISP=SHR
//SORTOUT DD DSN=UNMATCHEDFILE,DISP=(NEW,CATLG),SPACE=(CYL,(1,1))
//SYSOUT DD SYSOUT=*
//SYSIN DD *
SORT FIELDS=(1,5,CH,A) /* Sort on the first 5 characters */
JOINKEYS FILE=1,FIELDS=(1,5) /* Join on the first 5 characters
*/
JOINKEYS FILE=2,FIELDS=(1,5)
REFORMAT FIELDS=(1,5,11,20) /* Format output as required */
OPTION OMIT=(6,1) /* Remove matched records */
OPTION COPY /* Copy unmatched records to output
*/

GROUP BY and ORDER BY in DB2

1. GROUP BY:

 Purpose: Used to group rows that have the same values in specified columns. It is often
used with aggregate functions (COUNT, SUM, AVG, MIN, MAX) to perform operations on each
group of rows.

 Syntax:
 SELECT column1, aggregate_function(column2)
 FROM table
 WHERE condition
 GROUP BY column1;

 Example:
 SELECT department, COUNT(*) AS num_employees
 FROM employees
 GROUP BY department;

This query counts the number of employees in each department.

2. ORDER BY:

 Purpose: Used to sort the result set of a query by one or more columns. The default
sorting order is ascending (ASC), but it can be changed to descending (DESC).

 Syntax:
 SELECT column1, column2
 FROM table
 ORDER BY column1 [ASC|DESC];

 Example:
 SELECT employee_id, salary
 FROM employees
 ORDER BY salary DESC;

This query retrieves the employee ID and salary from the employees table, sorted by
salary in descending order.

Using GROUP BY and ORDER BY Together:

You can combine both clauses in a single query. For example, grouping the employees by
department and then ordering the result by the number of employees in each department:

SELECT department, COUNT(*) AS num_employees


FROM employees
GROUP BY department
ORDER BY num_employees DESC;

This query groups employees by department, counts them, and sorts the departments by the
number of employees in descending order.

Key Points:

 GROUP BY: Aggregates data into groups based on specified columns.


 ORDER BY: Sorts the result set based on specified columns.
Inner Join Query with GROUP BY Example

Here is an example of an INNER JOIN query that retrieves employee names and numbers from
the first table (employees) and employee numbers and salaries from the second table
(salaries), while using GROUP BY to group the results by employee name:

SELECT e.employee_name, e.employee_number, SUM(s.salary) AS total_salary


FROM employees e
INNER JOIN salaries s
ON e.employee_number = s.employee_number
GROUP BY e.employee_name, e.employee_number;

LOAD and UNLOAD in DB2 with SORT Example

In DB2, LOAD and UNLOAD utilities are used for managing large datasets in and out of DB2
tables, respectively. The SORT operation can be combined with these utilities to control the
order of the data being loaded or unloaded.

1. LOAD Utility in DB2:

The LOAD utility is used to insert data into DB2 tables from flat files or datasets. You can also
use it to sort data before loading it into a table.

Syntax:

LOAD DATA INDDDDN DDNAME INTO TABLE <table_name>


(COL1, COL2, COL3)
USING <control_file>
SORTED BY <column_name>;

Example:

Let’s assume you have a table EMPLOYEES with the following structure:

CREATE TABLE EMPLOYEES (


EMPLOYEE_ID INT,
EMPLOYEE_NAME VARCHAR(50),
SALARY DECIMAL(10, 2)
);

If you want to load data into this table and sort it by EMPLOYEE_ID:
//LOADSTEP EXEC PGM=LOAD
//SYSIN DD *
LOAD DATA INDDDDN DDNAME
INTO TABLE EMPLOYEES
(EMPLOYEE_ID, EMPLOYEE_NAME, SALARY)
USING CONTROL_FILE
SORTED BY EMPLOYEE_ID
/*
//DDNAME DD DSN=YOUR.DSN.DATA,DISP=SHR
//CONTROL_FILE DD DSN=YOUR.DSN.CONTROL, DISP=SHR

 LOAD DATA: Loads the data from the input file into the EMPLOYEES table.
 SORTED BY EMPLOYEE_ID: Sorts the data by EMPLOYEE_ID before loading it into the table.

2. UNLOAD Utility in DB2:

The UNLOAD utility extracts data from a DB2 table and writes it to a file. You can also use
sorting operations on the data being unloaded.

Syntax:

UNLOAD DATA FROM TABLE <table_name>


INTO <file_name>
SORTED BY <column_name>;

Example:

Let’s say you want to unload data from the EMPLOYEES table and sort it by SALARY:

//UNLOADSTEP EXEC PGM=UNLOAD


//SYSIN DD *
UNLOAD DATA FROM TABLE EMPLOYEES
INTO 'OUTPUT.FILE'
SORTED BY SALARY
/*
//OUTPUTFILE DD DSN=YOUR.OUTPUT.FILE, DISP=NEW

 UNLOAD DATA: Extracts data from the EMPLOYEES table.


 SORTED BY SALARY: Sorts the unloaded data by SALARY before writing it to the output file.

To pass data from JCL to COBOL, you typically use JCL parameters, DD (Data Definition)
statements, or SYSIN/SYSOUT for input/output data. Below is an example of how to pass data
from JCL to a COBOL program using parameters, and DD statements.
1. Passing Data Using JCL Parameters:

You can pass data to a COBOL program as parameters when the JCL job is executed. In
COBOL, the parameters are accessed through the PARM option in the EXEC statement.

JCL Example (Passing Parameters):

//JOBNAME JOB (ACCT),'COBOL-PARAM',CLASS=A,MSGCLASS=X


//STEP1 EXEC PGM=MYCOBOL, PARM='DATA1,DATA2'
//SYSOUT DD SYSOUT=*
//SYSIN DD *
(Any required input for COBOL, if needed)
//

COBOL Example (Accessing Parameters):

IDENTIFICATION DIVISION.
PROGRAM-ID. MYCOBOL.

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-PARAM1 PIC X(10).
01 WS-PARAM2 PIC X(10).

PROCEDURE DIVISION.
BEGIN.
MOVE 1ST PARAMETER TO WS-PARAM1
MOVE 2ND PARAMETER TO WS-PARAM2
DISPLAY 'Parameter 1: ' WS-PARAM1
DISPLAY 'Parameter 2: ' WS-PARAM2
STOP RUN.

END PROGRAM MYCOBOL.

Explanation:

 JCL: In the EXEC statement, PARM='DATA1,DATA2' passes the parameters DATA1 and DATA2
to the COBOL program.
 COBOL: The PARM values are automatically passed to the program through the JOB parameters.
The COBOL program accesses the parameters using SYSPARM system variables.

2. Passing Data Using DD Statement:

You can also pass data from JCL to COBOL via a DD statement by associating files or datasets
that the COBOL program can read.

JCL Example (Passing Data via DD):


//JOBNAME JOB (ACCT),'COBOL-FILE',CLASS=A,MSGCLASS=X
//STEP1 EXEC PGM=MYCOBOL
//INFILE DD DSN=INPUT.FILE, DISP=SHR
//SYSOUT DD SYSOUT=*
//SYSIN DD *
(Optional Input if needed for the COBOL program)
//

COBOL Example (Reading from a File Passed in JCL):

IDENTIFICATION DIVISION.
PROGRAM-ID. MYCOBOL.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IN-FILE ASSIGN TO 'INPUT.FILE'.

DATA DIVISION.
FILE SECTION.
FD IN-FILE.
01 IN-RECORD.
05 FIELD1 PIC X(10).
05 FIELD2 PIC X(10).

WORKING-STORAGE SECTION.
01 EOF-FLAG PIC X VALUE 'N'.

PROCEDURE DIVISION.
OPEN INPUT IN-FILE
READ-IN-FILE.
READ IN-FILE INTO IN-RECORD
AT END
MOVE 'Y' TO EOF-FLAG
NOT AT END
DISPLAY 'Field 1: ' FIELD1
DISPLAY 'Field 2: ' FIELD2
GO TO READ-IN-FILE
END-READ.
CLOSE IN-FILE.
STOP RUN.

Explanation:

 JCL: The DD statement associates the input dataset INPUT.FILE to the COBOL program’s
INFILE.
 COBOL: The COBOL program reads the file INPUT.FILE using the READ statement and
processes each record.
3. Passing Data via SYSIN (for Input Data):

For interactive or batch processing, you can pass data via SYSIN as input parameters that the
COBOL program will read.

JCL Example (Passing Data via SYSIN):

//JOBNAME JOB (ACCT),'COBOL-PARAM',CLASS=A,MSGCLASS=X


//STEP1 EXEC PGM=MYCOBOL
//SYSIN DD *
DATA1 DATA2
/*

COBOL Example (Reading from SYSIN):

IDENTIFICATION DIVISION.
PROGRAM-ID. MYCOBOL.

ENVIRONMENT DIVISION.

DATA DIVISION.
FILE SECTION.
FD SYSIN.
01 SYSIN-RECORD.
05 FIELD1 PIC X(10).
05 FIELD2 PIC X(10).

PROCEDURE DIVISION.
OPEN INPUT SYSIN
READ-SYSIN.
READ SYSIN INTO SYSIN-RECORD
AT END
DISPLAY 'End of Input'
NOT AT END
DISPLAY 'Field1: ' FIELD1
DISPLAY 'Field2: ' FIELD2
GO TO READ-SYSIN
END-READ.
CLOSE SYSIN.
STOP RUN.

Explanation:

 JCL: The SYSIN DD statement passes inline data to the COBOL program.
 COBOL: The program reads the data from SYSIN and processes the values.

Conclusion:

 JCL Parameters can be passed to COBOL via the PARM option in the EXEC statement.
 DD Statements can be used to pass file or dataset names to COBOL for reading or writing.
 SYSIN allows passing inline data directly to the COBOL program during execution.

These methods allow COBOL programs to access and manipulate data that is provided or
defined in JCL.

In COBOL, Linkage Section is used to pass data between different programs (such as between a
called subprogram and the main program). It allows the called program to access data that is
passed to it by the calling program. Data passed from one program to another through the
Linkage Section can be variables or records.

How Linkage Section Works:

 The Linkage Section is where the data passed from the calling program is defined.
 The calling program uses the CALL statement to invoke a subprogram and passes data through
the USING clause.
 The called program (subprogram) uses the Linkage Section to access the passed data.

Steps to Pass Data Using Linkage Section:

1. In the Calling Program: Define the data that will be passed to the called program in the CALL
statement using the USING clause.
2. In the Called Program: Define the Linkage Section to receive the data passed by the calling
program.

Example of Data Passing Using Linkage Section

Main Program (Calling Program):

IDENTIFICATION DIVISION.
PROGRAM-ID. MAINPROG.

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 EMP-ID PIC 9(5) VALUE 12345.
01 EMP-NAME PIC X(20) VALUE 'JOHN DOE'.

PROCEDURE DIVISION.
DISPLAY 'Calling Subprogram...'.
CALL 'SUBPROG' USING EMP-ID EMP-NAME.
STOP RUN.

Subprogram (Called Program):


IDENTIFICATION DIVISION.
PROGRAM-ID. SUBPROG.

ENVIRONMENT DIVISION.

DATA DIVISION.
LINKAGE SECTION.
01 LINK-EMP-ID PIC 9(5).
01 LINK-EMP-NAME PIC X(20).

PROCEDURE DIVISION.
DISPLAY 'Employee ID: ' LINK-EMP-ID.
DISPLAY 'Employee Name: ' LINK-EMP-NAME.
STOP RUN.

Explanation:

 Main Program (Calling Program):


o The EMP-ID and EMP-NAME fields are defined in the WORKING-STORAGE section.
o The CALL statement invokes the subprogram SUBPROG and passes EMP-ID and EMP-
NAME to it using the USING clause.

 Subprogram (Called Program):


o The subprogram defines the Linkage Section, where it declares LINK-EMP-ID and
LINK-EMP-NAME to receive the data passed by the calling program.
o It displays the values of LINK-EMP-ID and LINK-EMP-NAME which were passed from
the calling program.

Key Points:

 Linkage Section is used for data transfer between programs.


 The calling program uses the USING clause in the CALL statement to pass data.
 The called program defines the variables in the Linkage Section to receive the data.

This method is useful when data needs to be passed between different programs or modules
within a COBOL application.

COLLATE FUNCTION -

In DB2, the COLLATE function is used to specify the collation sequence for string comparisons or
sorting, but it also works in conjunction with null indicators to handle null values correctly
during sorting or comparisons.

When comparing or sorting data, null values are treated differently depending on the collation
sequence and the way null handling is specified in the query. The COLLATE function helps ensure
that these null values are processed as expected, particularly when performing complex queries
with string data.
Null Indicator and Collation:

 Null values in DB2 are considered unknown or not applicable.


 When using the COLLATE function, DB2 will still handle nulls based on its internal settings, but
you may want to explicitly manage null handling in certain queries.

Handling NULL with COLLATE:

If you're comparing a column to a value using COLLATE and the column has null values, you may
want to specify how to handle the nulls in the comparison. DB2 typically treats nulls as neither
equal to nor greater than any value. However, you can manage how nulls are ordered or
included in result sets using IS NULL or conditional handling.

Example 1: COLLATE with Null Values in WHERE Clause

Let's consider a case where you want to compare a column with nulls using a COLLATE function:

SELECT EMP_NAME
FROM EMPLOYEE
WHERE EMP_NAME COLLATE LATIN1 = 'JOHN DOE'
OR EMP_NAME IS NULL;

Explanation:

 In this example, we are using the COLLATE LATIN1 function to compare the EMP_NAME column
with the string 'JOHN DOE'.
 The OR EMP_NAME IS NULL ensures that records with a null EMP_NAME are also included in
the result set.
 The COLLATE LATIN1 ensures that the comparison respects the Latin1 collation rules, but it
will not return NULL values because null values are not equal to any string, even with a collation
sequence applied.

Example 2: COLLATE with ORDER BY and NULLS FIRST or LAST

You can also use the COLLATE function in the ORDER BY clause and explicitly control the
ordering of null values:

SELECT EMP_NAME
FROM EMPLOYEE
ORDER BY EMP_NAME COLLATE UNICODE NULLS FIRST;

Explanation:

 The COLLATE UNICODE ensures that the sorting respects the Unicode collation rules.
 NULLS FIRST explicitly places null values at the top of the result set, even when sorting the
data.
Nulls in Collation Context:

 Default Collation: If you do not specify a COLLATE function, DB2 typically uses the default
collation sequence for the database or column. The handling of nulls can differ depending on
this collation sequence.
 Custom Collation: When you specify a custom collation using COLLATE, DB2 follows the rules of
that specific collation for comparison, but the treatment of null values (whether they are
ordered first, last, or ignored) can be explicitly controlled using SQL clauses like NULLS FIRST
or NULLS LAST.

Conclusion:

The COLLATE function can be used with null indicators to control how null values are handled
during comparisons or sorting. While null values are treated as unknown by default, you can
specify how they should be ordered or included in your result set using SQL clauses like NULLS
FIRST or NULLS LAST. The COLLATE function itself does not directly affect the null values but
ensures that string comparisons and sorting are done according to the specified collation
sequence.

Index Scan vs. Table Scan in DB2

 Index Scan:
o When Used: When an index exists on the columns in the WHERE clause.
o How It Works: Scans the index to find row pointers, then fetches data.
o Efficiency: Faster for selective queries (fewer rows).
o Example:
o SELECT EMP_NAME FROM EMPLOYEE WHERE EMP_ID = 12345;

 Table Scan:
o When Used: When no index exists or the query scans a large portion of the table.
o How It Works: Scans the entire table row by row.
o Efficiency: Slower, used for queries involving most or all rows.
o Example:
o SELECT EMP_NAME FROM EMPLOYEE WHERE EMP_NAME = 'John Doe';

Key Differences:
Feature Index Scan Table Scan

When Used With indexed No index or


Feature Index Scan Table Scan

columns large dataset

Efficiency Faster Slower

WHERE SELECT *
Example EMP_ID = FROM
12345 EMPLOYEE

SQL QUERRIES-

Here are some frequently used DB2 SQL functions with examples
and one-line explanations:

1. DISTINCT

 Function: Removes duplicate values from a result set.


 Example:
 SELECT DISTINCT DEPARTMENT FROM EMPLOYEE;
 Explanation: Returns unique department names from the
employee table.

2. COUNT()

 Function: Returns the number of rows that match a condition.


 Example:
 SELECT COUNT(*) FROM EMPLOYEE WHERE DEPARTMENT =
'IT';
 Explanation: Counts the number of employees in the IT
department.

3. GROUP BY

 Function: Groups rows that have the same values into summary
rows.
 Example:
 SELECT DEPARTMENT, COUNT(*) FROM EMPLOYEE GROUP
BY DEPARTMENT;
 Explanation: Groups employees by department and counts the
Feature Index Scan Table Scan

number of employees in each department.

4. HAVING

 Function: Filters groups based on a condition (used with GROUP


BY).
 Example:
 SELECT DEPARTMENT, COUNT(*) FROM EMPLOYEE GROUP
BY DEPARTMENT HAVING COUNT(*) > 5;
 Explanation: Returns departments with more than 5 employees.

5. SUM()

 Function: Returns the total sum of a numeric column.


 Example:
 SELECT SUM(SALARY) FROM EMPLOYEE WHERE DEPARTMENT
= 'HR';
 Explanation: Calculates the total salary for the HR department.

6. AVG()

 Function: Returns the average value of a numeric column.


 Example:
 SELECT AVG(SALARY) FROM EMPLOYEE;
 Explanation: Computes the average salary of all employees.

7. MAX()

 Function: Returns the highest value in a column.


 Example:
 SELECT MAX(SALARY) FROM EMPLOYEE;
 Explanation: Finds the highest salary in the employee table.

8. MIN()

 Function: Returns the lowest value in a column.


Feature Index Scan Table Scan

 Example:
 SELECT MIN(SALARY) FROM EMPLOYEE;
 Explanation: Finds the lowest salary in the employee table.

9. ORDER BY

 Function: Sorts the result set based on specified column(s).


 Example:
 SELECT EMP_NAME, SALARY FROM EMPLOYEE ORDER BY
SALARY DESC;
 Explanation: Sorts employees by salary in descending order.

10. COALESCE()

 Function: Returns the first non-null value in a list of expressions.


 Example:
 SELECT COALESCE(MIDDLE_NAME, 'N/A') FROM
EMPLOYEE;
 Explanation: Returns the middle name or 'N/A' if it’s null.

11. CONCAT()

 Function: Combines two or more strings into one.


 Example:
 SELECT CONCAT(FIRST_NAME, ' ', LAST_NAME) FROM
EMPLOYEE;
 Explanation: Concatenates the first and last names of employees.

12. UPPER()

 Function: Converts a string to uppercase.


 Example:
 SELECT UPPER(EMP_NAME) FROM EMPLOYEE;
 Explanation: Converts employee names to uppercase.

13. LOWER()
Feature Index Scan Table Scan

 Function: Converts a string to lowercase.


 Example:
 SELECT LOWER(EMP_NAME) FROM EMPLOYEE;
 Explanation: Converts employee names to lowercase.

In COBOL-DB2, the RESTART parameter is used to control the


position of the cursor when restarting a DB2 program after an error
or after processing multiple rows.

Usage of RESTART Parameter:

 RESTART=YES: Indicates that the program should restart from the


first record after a commit or a rollback.
 RESTART=NO: Specifies that the program should continue
processing from the last valid position (default behavior).

Example:
EXEC SQL
DECLARE C1 CURSOR FOR CURSOR1
WITH HOLD
RESTART=YES
END-EXEC;

Explanation:

 When RESTART=YES, the cursor will restart from the first row
after each commit or rollback.
 RESTART=NO means the program continues where it left off
without restarting.

In COBOL, the RESTART parameter is used in the context of file handling, particularly for
restarting file processing from a specific point. It is typically used in SORT or MERGE
operations, allowing you to restart the processing after an error or from a specific record.

In the context of SORT/MERGE in COBOL:

1. RESTART Keyword:
o Purpose: Used in the SORT or MERGE statement to restart the processing of a file or
sort from a specified position.
o It helps to continue from the last checkpoint in case of failure or after processing some
records.

Example (SORT with RESTART):


SORT SORT-FILE
ON ASCENDING KEY SORT-KEY
USING INPUT-FILE
GIVING OUTPUT-FILE
RESTART

Explanation:

 The RESTART parameter is specified during SORT or MERGE operations to restart from a certain
point.
 It helps ensure that the sorting process continues from a valid point, especially after
encountering errors.

In COBOL, the Linkage Section is used to receive input data from other programs, typically
from JCL or other external sources. The data is passed via parameters or files to the COBOL
program. Here's how you can use the Linkage Section to receive input data:

Steps:

1. Define the parameters in the Linkage Section.


2. Pass the parameters from the calling program (JCL or another COBOL program).
3. Access the data within the program using the variables defined in the Linkage Section.

Example:

1. Defining the Linkage Section:

In the COBOL program, define the Linkage Section to receive data.

LINKAGE SECTION.
01 INPUT-VALUE PIC X(10).
01 RECORD-COUNT PIC 9(5).

2. Receiving Data from JCL:

In the calling JCL or calling program, pass the data.

For example, in JCL:

//STEP1 EXEC PGM=MYCOBOL


//MYIN DD DSN=INPUT.DATA,DISP=SHR

3. Accessing the Data in the Procedure Division:


You can now access the data in the Procedure Division using the variables defined in the
Linkage Section.

PROCEDURE DIVISION.
DISPLAY 'Input Value: ' INPUT-VALUE.
DISPLAY 'Record Count: ' RECORD-COUNT.

Explanation:

 The Linkage Section holds the parameters passed from another program or JCL.
 The variables defined in the Linkage Section receive the values that are passed when the
program is executed.
 The program can then access and use these values just like any other data item.

How Data is Passed:

 From JCL: Use DD statements (like MYIN DD) to pass files or data to the COBOL program.
 From another COBOL program: Use the CALL statement to invoke the program and pass
parameters via the Linkage Section.

In COBOL, to compare two files and write matched and unmatched records to separate output
files, you typically use SORT or manual comparison logic in the Procedure Division. Below is
a step-by-step explanation along with the control statements used to handle this.

Steps to Compare and Write Matched and Unmatched Records:

1. Define the Input and Output Files:


o One input file will contain records to be compared.
o Another input file will have the second set of records for comparison.
o Two output files: one for matched records and one for unmatched records.

2. Read the Records:


o Read both files and compare the records one by one.

3. Control Statements:
o Use IF or EVALUATE statements to check if the records match or not.
o Use WRITE statements to write matched or unmatched records to appropriate output
files.

Example: COBOL Code to Compare Two Files


IDENTIFICATION DIVISION.
PROGRAM-ID. CompareFiles.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT FILE1 ASSIGN TO 'INPUT1.DAT'.
SELECT FILE2 ASSIGN TO 'INPUT2.DAT'.
SELECT MATCHED-OUTPUT ASSIGN TO 'MATCHED.DAT'.
SELECT UNMATCHED-OUTPUT ASSIGN TO 'UNMATCHED.DAT'.

DATA DIVISION.
FILE SECTION.
FD FILE1.
01 FILE1-RECORD PIC X(100).

FD FILE2.
01 FILE2-RECORD PIC X(100).

FD MATCHED-OUTPUT.
01 MATCHED-RECORD PIC X(100).

FD UNMATCHED-OUTPUT.
01 UNMATCHED-RECORD PIC X(100).

WORKING-STORAGE SECTION.
01 END-OF-FILE1 PIC X VALUE 'N'.
01 END-OF-FILE2 PIC X VALUE 'N'.
01 MATCH-FLAG PIC X VALUE 'N'.

PROCEDURE DIVISION.
OPEN INPUT FILE1, FILE2
OPEN OUTPUT MATCHED-OUTPUT, UNMATCHED-OUTPUT

PERFORM COMPARE-RECORDS UNTIL END-OF-FILE1 = 'Y' OR END-OF-FILE2 = 'Y'

CLOSE FILE1, FILE2, MATCHED-OUTPUT, UNMATCHED-OUTPUT


STOP RUN.

COMPARE-RECORDS.
READ FILE1 INTO FILE1-RECORD
AT END
SET END-OF-FILE1 TO 'Y'
NOT AT END
READ FILE2 INTO FILE2-RECORD
AT END
SET END-OF-FILE2 TO 'Y'
NOT AT END
IF FILE1-RECORD = FILE2-RECORD
MOVE FILE1-RECORD TO MATCHED-RECORD
WRITE MATCHED-RECORD
ELSE
MOVE FILE1-RECORD TO UNMATCHED-RECORD
WRITE UNMATCHED-RECORD
MOVE FILE2-RECORD TO UNMATCHED-RECORD
WRITE UNMATCHED-RECORD
END-IF
END-READ
END-READ

Explanation of Control Statements:

 READ: Reads a record from the input files.


o The READ FILE1 INTO FILE1-RECORD reads a record from the first file.
o The READ FILE2 INTO FILE2-RECORD reads a record from the second file.
o The AT END clause sets the end-of-file flag (END-OF-FILE1 or END-OF-FILE2) to 'Y'
when the end of the file is reached.

 IF: Compares the records.


o IF FILE1-RECORD = FILE2-RECORD: Checks if the records from both files are equal
(matched).
o If matched, it writes the record to the matched output file using WRITE MATCHED-
RECORD.
o If unmatched, it writes the record to the unmatched output file using WRITE
UNMATCHED-RECORD.

 WRITE: Writes the matched or unmatched record to the respective output file.
 SET: Updates the status flags (END-OF-FILE1 and END-OF-FILE2) to indicate the end of
file.
 OPEN and CLOSE: Opens and closes the files (input and output files).

Key Points:

 The IF statement is used for the comparison between the two files.
 READ is used to read data from both files.
 The WRITE statement writes records based on whether they are matched or unmatched.
 The files are processed until either of the input files reaches the end, indicated by the respective
flags.

Example Output:

 Matched File: Contains records that exist in both input files.


 Unmatched File: Contains records that exist in only one of the input files.

This approach allows you to compare two files and manage matched and unmatched records
efficiently in COBOL.

Sure! Here's an extended version of the COBOL program with examples of both CALL BY
REFERENCE and CALL BY VALUE, along with detailed explanations.

1. Calling Program (Main Program)

In the calling program, you define the variables that will be passed to the second program. We'll
demonstrate both CALL BY REFERENCE (default) and CALL BY VALUE.

IDENTIFICATION DIVISION.
PROGRAM-ID. CALLING-PROGRAM. * Program name

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
* (If any file processing is needed, it can be declared here)
DATA DIVISION.
WORKING-STORAGE SECTION.
01 EMPLOYEE-NAME PIC X(20) VALUE 'John Doe'. * Employee name to be
passed
01 EMPLOYEE-SALARY PIC 9(5)V99 VALUE 50000.00. * Employee salary to
be passed

PROCEDURE DIVISION.
DISPLAY 'Before CALL (BY REFERENCE): ' EMPLOYEE-NAME ' ' EMPLOYEE-
SALARY.
* Display the initial values before calling the second program

* CALL BY REFERENCE (default)


CALL 'CALLED-PROGRAM' USING EMPLOYEE-NAME EMPLOYEE-SALARY.
* The CALL statement invokes the CALLED-PROGRAM and passes
* the EMPLOYEE-NAME and EMPLOYEE-SALARY variables by reference

DISPLAY 'After CALL (BY REFERENCE): ' EMPLOYEE-NAME ' ' EMPLOYEE-
SALARY.
* Display the values after the call to see the modified data

* CALL BY VALUE Example


CALL 'CALLED-PROGRAM' USING EMPLOYEE-NAME EMPLOYEE-SALARY BY VALUE.
* The CALL statement invokes the CALLED-PROGRAM and passes
* the EMPLOYEE-NAME and EMPLOYEE-SALARY variables by value (copy of
the value)

DISPLAY 'After CALL (BY VALUE): ' EMPLOYEE-NAME ' ' EMPLOYEE-
SALARY.
* Display the values after the call to see if they were modified by
the called program

STOP RUN. * End of the calling program

Explanation:

 The CALL BY REFERENCE (default) passes the address of the variables (EMPLOYEE-NAME and
EMPLOYEE-SALARY). Any changes made to these variables in the called program will affect the
calling program.
 The CALL BY VALUE example shows that a copy of the variables is passed. Therefore, any
changes made to the variables in the called program will not affect the original values in the
calling program.

2. Called Program (CALLED-PROGRAM)

In the called program, the Linkage Section receives the parameters passed from the calling
program.

IDENTIFICATION DIVISION.
PROGRAM-ID. CALLED-PROGRAM. * Program name
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
* (If any file processing is needed, it can be declared here)

DATA DIVISION.
LINKAGE SECTION.
01 LNK-EMPLOYEE-NAME PIC X(20). * Employee name received from the
calling program
01 LNK-EMPLOYEE-SALARY PIC 9(5)V99. * Employee salary received from
the calling program

PROCEDURE DIVISION.
DISPLAY 'Inside CALLED-PROGRAM: ' LNK-EMPLOYEE-NAME ' ' LNK-
EMPLOYEE-SALARY.
* Display the received data inside the called program before
modification

* Modify the received values


MOVE 'Jane Smith' TO LNK-EMPLOYEE-NAME.
* Update the employee name to 'Jane Smith'

ADD 5000 TO LNK-EMPLOYEE-SALARY.


* Increase the salary by 5000

DISPLAY 'After modification in CALLED-PROGRAM: ' LNK-EMPLOYEE-NAME


' ' LNK-EMPLOYEE-SALARY.
* Display the modified values inside the called program

EXIT PROGRAM. * End of the called program

Explanation:

 Linkage Section: The called program receives EMPLOYEE-NAME and EMPLOYEE-SALARY from
the calling program.
 The program modifies the values of these parameters, updates the name to "Jane Smith",
and increases the salary by 5000.
 The modified data is displayed inside the called program.

How CALL BY REFERENCE and CALL BY VALUE Work:

1. CALL BY REFERENCE (Default):


o The calling program passes the memory address (pointer) of the variables. Changes
made to the variables in the called program will reflect in the calling program.
o Example (Calling Program):
o CALL 'CALLED-PROGRAM' USING EMPLOYEE-NAME EMPLOYEE-SALARY.
o The called program can modify the variables passed. These modifications will directly
affect the variables in the calling program.

2. CALL BY VALUE:
o The calling program passes a copy of the variables to the called program. The called
program cannot modify the original variables; it can only modify the copy.
o Example (Calling Program):
o CALL 'CALLED-PROGRAM' USING EMPLOYEE-NAME EMPLOYEE-SALARY BY
VALUE.
o The called program will not be able to affect the original values of EMPLOYEE-NAME and
EMPLOYEE-SALARY in the calling program.

Expected Output for Both Cases:

1. CALL BY REFERENCE (Default):

If the called program modifies the values, they will be reflected in the calling program:

Calling Program Output:

Before CALL (BY REFERENCE): John Doe 50000.00


Inside CALLED-PROGRAM: John Doe 50000.00
After modification in CALLED-PROGRAM: Jane Smith 55000.00
After CALL (BY REFERENCE): Jane Smith 55000.00

 Since the data was passed by reference, the changes made in the called program (Jane Smith
and 55000.00) reflect in the calling program.

2. CALL BY VALUE:

If the called program modifies the values, it will not affect the calling program's original values:

Calling Program Output:

Before CALL (BY VALUE): John Doe 50000.00


Inside CALLED-PROGRAM: John Doe 50000.00
After modification in CALLED-PROGRAM: Jane Smith 55000.00
After CALL (BY VALUE): John Doe 50000.00

 Since the data was passed by value, the changes made in the called program (Jane Smith and
55000.00) do not affect the calling program. The original values (John Doe and 50000.00)
remain unchanged in the calling program.

Summary of Data Passing:

 CALL BY REFERENCE (default in COBOL): The calling program passes the memory address of the
variables. Any changes in the called program will directly affect the calling program's data.
 CALL BY VALUE: The calling program passes a copy of the variables. Changes made in the called
program will not affect the calling program’s data.

You might also like