Search code examples
sqldb2ibm-midrange

Legacy DB2 SQL query concatination simplification


We have a DB2 database installed on an AS/400 system. (Yes, it's been rebranded a few ways by IBM)

You can see the redundancy when I do my concatenation on the string pieces.

I've seen some solutions but bear in mind that many don't seem to work since our database is a fairly old non standard version of DB2. Is there a way to reduce the redundancy on the CHAR(19000000 + a10) calculation? It works, but it hits a conversion many more times than it needs to.

SELECT DISTINCT pdk01.a00 AS POLICY, 
                    pdk01.b27_mins_name AS "INS NAME", 
                    substr(CHAR(19000000 + a10), 1, 4) || '/' || substr(CHAR(19000000 + a10), 5, 2) || '/' || substr(CHAR(19000000 + a10), 7, 2) as "Orig Eff Date",                    
                    substr(CHAR(19000000 + a09), 1, 4) || '/' || substr(CHAR(19000000 + a09), 5, 2) || '/' || substr(CHAR(19000000 + a09), 7, 2) AS "Expire Date", 
                    pdk01.a21_mtotal_prem AS PREMIUM 
    FROM   mudata.pdk01 AS PDK01 
           INNER JOIN mudata.pdk04 AS PDK04 
                   ON pdk01.a00_m1_pol_num = pdk04.a00_m4_pol_num 
    WHERE  pdk01.a11_mnext_act_code <> 'P' 
           AND pdk04.b83 = '91342' 
    ORDER  BY pdk01.a00 asc;

Solution

  • Starting at v6.1, you can use the TIMESTAMP_FORMAT function to turn a character string into a timestamp, and from there into just about any format you choose. Here is how to turn a character string containing 180205 (YYMMDD) into a timestamp.

    TIMESTAMP_FORMAT(field, 'YYMMDD')
    

    To change that into just a date field, you could do it this way:

    DATE(TIMESTAMP_FORMAT(field, 'YYMMDD'))
    

    To change it into a character field with separators do this:

    CHAR(DATE(TIMESTAMP_FORMAT(field, 'YYMMDD')), ISO)
    

    Of course ISO uses - instead of / as a separator, so you need to replace those with:

    REPLACE(CHAR(DATE(TIMESTAMP_FORMAT(field, 'YYMMDD')), ISO), '-', '/')
    

    If your version is older than v6.1, well you will just have to deal with the consequences of having a 12+ year old operating system.