Here’re three methods to handle DB2’s VARCHAR data in COBOL. These are helpful for DB2-COBOL developers. In COBOL, you need level 49 to receive VARCHAR data. The below methods explain how to handle VARCHAR data.
COBOL 49 Level for VARCHAR
COBOL Logic 49 level
01 SNAME. 49 SNAME-LENGTH PIC S9(4) COMP. 49 SNAME-TEXT PIC X(100).
SNAME-LENGTH contains the length of SNAME-TEXT. You can see this when displaying the SNAME field.
When the data in SNAME_TEXT is less than 100 bytes trailing spaces will be added. To use the SNAME_TEXT field in your COBOL program, first, you must remove padded spaces.
SNAME-TEXT should be the same length as that of Table column size (VARCHAR(100)).
Before moving data to SNAME-TEXT, you must move spaces to it. Otherwise, junk data is mixed up with actual value.
For instance, If the SNAME column contains Blanks, the SNAME-LENGTH will be 95, the first five bytes of SNAME-TEXT will contain Blank, and the remaining 95 bytes will have the same data before the moving column to the host variable.
How to write COBOL to DB2
To insert/update a record from COBOL 49 level to DB2, you must take care of padded blanks. Else, these padded Blanks will pass to the VARCHAR column of the DB2 Table.
In COBOL, for instance, you try to move data to the Alpha-Numeric field, the PIC(X(n)) field padded with spaces when data length is less than the field size.
How to remove padded spaces: Here’re 3 methods
Remove Padded spaces – Method-1
Assign each character of the value to an array, count the number of trailing blanks, and subtract the value from the total length of the string.
Remove Padded spaces – Method-2
Use UNSTRING to get Length. This logic gives actual string length value.
UNSTRING SNAME-TEXT DELIMITED BY ' ' COUNT IN SNAME-LENGTH.
Remove Padded spaces – Method -3
Use scalar function (POSSTR) to determine the position in a string of another string:
SQL Query with POSSTR
EXEC SQL SET :SNAME-LENGTH = POSSTR('ERIC CLARK, ', ') - 1 END-EXEC.
The host-variable SNAME-LENGTH contains 10 (since there are 10 bytes in ERIC CLARK before trailing blanks)
The Bottom Line
While using UNSTRING and POSSTR functions since they ignore blank character-string. For instance, in the ‘EricbbClark’, you’ll lose the ‘Clark.’