Db2 – how to get list of months between two dates in db2

db2

I have two dates start and end date i need find list of months between two dates.for example, 01-12-2015 as start date and 01-02-2015 as end date i need result to be as , January. I am using IBM db2. another thing i need to find these using select query i have no access to create function or procedures.

Best Answer

Your date format is ambiguous but given your expected answer is January, I'll assume your start date is 2015-01-02 and end date is 2015-01-12. The following recursive query should do what you need:

WITH months(i, d) AS (
    VALUES (1, DATE('2015-01-02'))

    UNION ALL

    SELECT i + 1, d + 1 MONTH
      FROM months
     WHERE i < 10000
       AND d + 1 MONTH <= DATE('2015-01-12')
)
SELECT monthname(d)
  FROM months

The "i" term in the recursive element is simply there to suppress the "possibly infinite" warning that occurs otherwise. If you're not bothered by the warning, you could just remove it.

This will work on DB2 for LUW and I think it'll work on DB2 for z/OS but that'll depend on whether they've finally added support for VALUES or not; if they haven't just use SELECT foo FROM SYSIBM.SYSDUMMY1 in the base case instead).