LPAD(
TRANSLATE(
REPLACE( TRANSLATE(MISC1_KEY || MISC2_KEY, ' ', X'00'),
' ', ''),
'', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
3, '0') AS TERRITORY,
The query has four steps, working from the inside out:
- Combine the two columns together and replace and null values with a space, X'00' is the hex code for null.
- Remove any spaces from the column, originally I wanted to do this with the next TRANSLATE step, but for some reason the spaces seem to be ignored with TRANSLATE
- Remove any alpha characters, the column also sometimes contained state abbreviations. It would be nice if we could use something like ^[0..9], but DB2 doesn't support that, and on z/OS it doesn't even support hex ranges.
- Finally pad the number with leading zeros to make it three bytes long.
It's quite a few steps, but the end result is a consistent three byte code. Especially useful when used with a CTE or a sub-select.
Post a Comment