The below example shows how 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 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 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 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.
There are three alternatives for determining the number of characters before trailing blanks.
- 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:
UNSTRING SNAME-TEXT DELIMITED BY ‘ ‘ COUNT IN SNAME-LENGTH. [here, it gives actual string length value]
- POSSTR scalar function can be used to determine the position in a string of another string:
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) 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.