Important Mainframe Questions
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.
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.
DB2 –
SELECT *
FROM TABLE_NAME
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
2. PERFORM TIMES
3. PERFORM THRU
4. PERFORM INLINE
PERFORM
END-PERFORM.
Use: For single-use or short operations that don’t require modular paragraphs.
5. PERFORM VARYING
PERFORM DISPLAY-ROWS
Use: Useful for loops with variable-controlled iterations, like iterating over table rows.
UNSTRING Input-String
DELIMITED BY '|'
END-UNSTRING.
STOP RUN.
PROCEDURE DIVISION.
INTO Output-String
END-STRING.
STOP RUN.
PROCEDURE DIVISION.
STRING Field1 DELIMITED BY SPACE
INTO Output-String
END-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
Here’s a short explanation and COBOL code examples for creating and accessing all four types
of VSAM files:
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.
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.
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.
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.
CLOSE FlatFile.
STOP RUN.
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.
Record not found (for Ensure the key exists in the dataset or handle INVALID KEY
23
KSDS/RRDS) condition gracefully.
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.
41 File already open Avoid multiple OPEN operations on the same file in the program.
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.
Logic error (e.g., invalid Check program logic, especially record definitions, and correct
92
record length) mismatched lengths.
No rows found or end of cursor Handle the condition using program logic; check if no rows
+100
reached is valid for your operation.
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.
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.
Deletion violates a referential Delete dependent child records first, or cascade deletes
-532
constraint using the foreign key definition.
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.
-927 Program not precompiled with Ensure the COBOL program is precompiled and compiled
SQLCODE Error Description Resolution
OCCURS IN COBOL –
01 STUDENT-MARKS.
05 MARKS PIC 9(3) OCCURS 5 TIMES.
Accessing OCCURS
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.
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).
Access
Use Cases
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.
1. Counting Characters
2. Replacing Characters
Key Points
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
Open: Executes the query and positions the cursor before the first row.
EXEC SQL
OPEN CURSOR_NAME
END-EXEC.
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.
PROCEDURE DIVISION.
EXEC SQL
DECLARE CURSOR1 CURSOR FOR
SELECT EMP_NAME, EMP_AGE FROM EMPLOYEE_TABLE
END-EXEC.
EXEC SQL
OPEN CURSOR1
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.
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'.
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.
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.
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.
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).
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.
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.
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.
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;
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.
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:
This query groups employees by department, counts them, and sorts the departments by the
number of employees in descending order.
Key Points:
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:
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.
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:
Example:
Let’s assume you have a table EMPLOYEES with the following structure:
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.
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:
Example:
Let’s say you want to unload data from the EMPLOYEES table and sort it by SALARY:
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.
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.
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.
You can also pass data from JCL to COBOL via a DD statement by associating files or datasets
that the COBOL program can read.
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.
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.
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.
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.
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.
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:
Key Points:
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:
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.
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.
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:
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
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
2. COUNT()
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
4. HAVING
5. SUM()
6. AVG()
7. MAX()
8. MIN()
Example:
SELECT MIN(SALARY) FROM EMPLOYEE;
Explanation: Finds the lowest salary in the employee table.
9. ORDER BY
10. COALESCE()
11. CONCAT()
12. UPPER()
13. LOWER()
Feature Index Scan Table Scan
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.
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.
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:
Example:
LINKAGE SECTION.
01 INPUT-VALUE PIC X(10).
01 RECORD-COUNT PIC 9(5).
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.
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.
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.
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
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
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:
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.
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
DISPLAY 'After CALL (BY REFERENCE): ' EMPLOYEE-NAME ' ' EMPLOYEE-
SALARY.
* Display the values after the call to see the modified data
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
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.
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
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.
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.
If the called program modifies the values, they will be reflected in the calling program:
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:
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.
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.