Converting Character Data to Numeric in Query/400

Article ID: 16664

Query/400 does not provide a native method for converting character data to numeric, but with the following hack, the conversion is possible. I have a character field (four digits) that's used for generic purposes in a particular database file. Although the field's format is character, the field sometimes represents numeric data. To perform math operations on such data in Query, you must first convert the field to numeric. By using the MICROSECOND keyword in the Define Result Fields section of Query, you can convert the character data to a numeric field for later use in calculations.

For example, create a field called TIMESTAMP using Query's Define Result Fields panel, specifying

'1988-12-25-17.30.00.00' || CHARFIELD4

in the panel's Expression column. The field CHARFIELD4 in this example represents a four-digit character field containing the characters 0 (zero) through 9 (nine).

Next, use the MICROSECOND keyword on the TIMESTAMP field to create a numeric copy of CHARFIELD4's character data. Here's what the Define Result Fields panel will look like:

Field     Expression                           Column Heading Len Dec
TIMESTAMP '1988-12-25-17.30.00.00' || CHARFIELD4               26
NUMERIC6  MICROSECOND(TIMESTAMP)                                6   0

The MICROSECOND keyword takes the six rightmost digits in the TIMESTAMP field and converts them to numeric. In the example, the character field is only four digits long, so 00 is concatenated with the character field to create a valid timestamp with six digits of milliseconds.

If a given character field is larger than six digits, you'll need to break down the above process into multiple steps and perform a math operation on the individual numeric components to combine them.

The above iSeries NEWS tip is from Rich Tieslau.

ProVIP Sponsors

ProVIP Sponsors