3 popular Ways to Handle DB2 VARCHAR Field in COBOL

The  following are the three ways you can handle DB2 VARCHAR field in COBOL. These are very popular and good handy guide for all DB2  and COBOL developer.


The below example shows how to handle VARCHAR field at 49 level in COBOL:

  49 SNAME-TEXT PIC X(100).
 :SNAME-LENGTH contains the number of bytes in :SNAME-TEXT when selecting SNAME.

SNAME-TEXT should be the same length as defined for the column (VARCHAR(100)).

Before moving a value into SNAME-TEXT, need to move spaces into this field. Otherwise, junk data mixed up with actual value.

For exampleIf 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 before the move of data from the column to the host variable.

  • For UPDATE and INSERT statements, the program must calculate SNAME-LENGTH, if it is not known. Otherwise, trailing blanks store in the VARCHAR column.

Personal Development Category (English)640x480

There are three alternatives for determining the number of characters before trailing blanks.

  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.
  2. Use the following COBOL statement:
    UNSTRING SNAME-TEXT DELIMITED BY ‘ ‘ COUNT IN SNAME-LENGTH. [here, it gives actual string length value]
  3. POSSTR scalar function can be used to determine the position in a string of another string:
POSSTR('ERIC CLARK, ', ') - 1 

:SNAME-LENGTH contains 10 (there are 10 bytes in ERIC CLARK before trailing blanks)
       with the use of UNSTRING and POSSTR.

Note: Be careful while using these two techniques. Since, it assumes that two blanks are not embedded in a character string. For example, if the string is ‘EricbbClark’, ‘Clark’ will be lost.


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.