3 Popular Ways to Handle DB2 VARCHAR Field in COBOL

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 instanceIf 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.


Remove Padded spaces – Method -3

Use scalar function (POSSTR) to determine the position in a string of another string:

SQL Query with POSSTR


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.’

Related Posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.

Comments are closed.