Sometimes it is necessary to validate packed decimal data before attempting to use it. For example, you may have received a flat file from another system. In this case, the record positions that are supposed to contain packed data should be validated before being loaded into a numeric field.
The packed decimal format uses half a byte to store each decimal digit. The sign is held in the final half byte: hex digit A, C, E, or F signifies a positive number; B or D a negative number. (The iSeries 400 natively uses only F or D to indicate sign, but it can interpret the other values.) If there is an even number of digits in the packed field, the first half byte will be unused, and will normally contain binary zeroes. The maximum length of an iSeries packed field is currently 30 digits, held in 16 bytes.
The first validation method, below, checks each byte of the test field. The final byte must take one of 60 possible valid values: x0A .. x0F, x1A ... x1F, ... x9A ... x9F. Each of the other bytes can take 100 possible values: x00 ... x09, x10 ... x19, ... x90 ... x99. The program overlays each byte with a one byte unsigned integer field, which is used as an index into one of two lookup tables. Note that the lookup tables are loaded first time in, and are declared as static so that they retain their value between calls to the subprocedure.
The second validation method uses SQL to...
To continue reading for free, register below or login
To read more you must become a member of Search400.com
');
// -->

identify records that contain invalid decimal data. The first step is to use SQL's HEX function to return a hexadecimal representation of a field or substring. Next we use the TRANSLATE function to translate all valid sign digits ('A'-'F') to 's'. Any valid packed decimal string should now have the form 'nn...s', where n is a numeric hex digit and s is a literal 's'. Finally, we use the LOCATE function to ensure that there is precisely one sign digit, and that it is at the end of the hex string.
The final SQL statement, checking for one field, takes the form shown below. (A substring from a flat file can be substituted for fld, if required.) This method is useful if you have only a small number of suspect packed fields, and it has the advantage of allowing interactive display of the invalid records.
Finally, we could combine these two approaches by writing an SQL UDF (User Defined Function) that invokes subprocedure IsValidPacked. This would make it less cumbersome to validate multiple fields in the same SQL statement.
Code
Validation Method 1: Lookup Table
Validation Method 2: SQL
select * from file
where not
locate('s', translate(hex(fld),'ssssss','ABCDEF')) = 2*length(fld)