It seems like all you're really doing is finding out how many months are between BASE_YM
and DEFAULT_YM
, and making that a character type. I think the same result can be retrieved by doing some date math (and I'm guessing it'd be more efficient, because it wouldn't have to calculate up to 36 different TO_CHAR
calls) This whole statement would replace the CASE
. I tested similar logic on DB2 for Linux/Unix/Windows v.9.7, and z/OS v10:
SELECT
LPAD(
ABS(
MONTH(
TIMESTAMP_FORMAT(BASE_YM, 'YYYYMM') -
DEFAULT_YM
)
)
,2,'0')
FROM your_table
I added the extra spacing so that you could (hopefully) follow along a little easier. Basically, it just subtracts DEFAULT_YM
from the converted form of BASE_YM
. Then, I take the Absolute Value of the difference in months, and then convert it to a zero-padded character field.