Explained to handle VARCHAR data in COBOL. These ideas are very popular and really useful for all DB2 and COBOL developers. In COBOL, you need to use 49 level to get VARCHAR data. Three ways I have explained to handle padded spaces populated in data field.
COBOL 49 Level for VARCHAR
Example below shows to handle VARCHAR field at 49 level in COBOL
01 SNAME. 49 SNAME-LENGTH PIC S9(4) COMP. 49 SNAME-TEXT PIC X(100).
SNAME-LENGTH contains the number of bytes in SNAME-TEXT when display the SNAME field. When the data in SNAME_TEXT is less than 100 bytes trailing spaces will be added. To use SNAME_TEXT filed in your COBOL program, first you need to remove padded spaces.
- SNAME-TEXT should be the same length as defined for the column (VARCHAR(100)).
- Before moving a value into SNAME-TEXT, you need to move spaces to this field. Otherwise, junk data mixed up with actual value.
- For example, If the SNAME column contains Blake, the SNAME-LENGTH field will contains 5, the first five bytes of SNAME-TEXT will contain Blake, and the remaining 95 bytes will contain whatever was there beforCe the move of data from the column to the host variable.
Tips to Write Record from COBOL to DB2
To insert or update a record from COBOL 49 level field to DB2, you need to make sure that the padded blanks are removed. Else, these padded Blanks stored in VARCHAR column of DB2 Table.
In COBOL, if you move data into Alpha-Numeric field, the PIC(X(n)) field padded with spaces when data length is less than the field size.Ideas to handle VARCHAR in COBOL
3 Methods to Remove Padded Spaces
- 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.
Use the following COBOL statement:
DELIMITED BY ' '
COUNT IN SNAME-LENGTH.
This logic gives actual string length value .
- POSSTR scalar function can be used 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.
:SNAME-LENGTH contains 10 (there are 10 bytes in ERIC CLARK before trailing blanks)
The Bottom Line
Be careful while using UNSTRING and POSSTR techniques. It assumes that two blanks are not embedded in a character string. For example, if the string is ‘EricbbClark’, ‘Clark’ will be lost.