3

I have learned that subtracting two dates in Db2 results in a number which is to be interpreted as an interval:

SELECT current_date - '1943-02-25' FROM SYSIBM.DUAL;
--      820020: 82 years, 0 months, 20 days

In this case, I can use substring() and right() to pull it apart:

WITH cte(age) AS (
    SELECT current_date - '1943-02-25' FROM SYSIBM.DUAL
)
SELECT left(age,2) AS yyyy, substr(age,3,2) AS mm, right(age,2) AS dd
FROM cte;

The only problem is if the age is more than 99 years, then it’s the first three or four digits for the years, and the months component starts further down.

If I were to use a regular expression, I would have something like this:

^(\d{2,4})(\d{2})(\d{2})$

I know that Db2 has a regexp_substr() aka regexp_extract() function but I can’t see how the above expression can be used. Everything I’ve read uses a simple expression like o. and nothing with a variable number of characters.

What is the way to extract a variable number of characters for the year and month? Do I use regexp_substr() or something else?

I’m running Db2 12 in a Docker Linux container.

1
  • Start from the right-hand side of the string. Looks like the two rightmost digits are the days, and the two digits to the left of that are the months, and the remaining digits to the left (whether it is one digit, or two, three, or however many) are the years. Commented Mar 17 at 1:25

2 Answers 2

3

Is there any reason why you can't use the EXTRACT() function here:

WITH cte(age) AS (
    SELECT current_date - '1943-02-25'
    FROM SYSIBM.DUAL
)

SELECT
    EXTRACT(YEAR FROM age) AS yyyy,
    EXTRACT(MONTH FROM age) AS mm,
    EXTRACT(DAY FROM age) AS dd
FROM cte;
Sign up to request clarification or add additional context in comments.

2 Comments

I had no idea that extract() would work with durations as well, since it just looked like a number to me. Here’s the reference: ibm.com/docs/en/db2/11.5?topic=functions-extract . Thanks.
This doesn't work on a little bit older db2 as described here.
1

A solution with just a number of simple math expressions.

SELECT 
  age
, int(age)/10000 AS yyyy
, (int(age) - int(age)/10000*10000)/100 AS mm
, int(age) % 100 AS dd
FROM (VALUES current_date - '1943-02-25') T(age)

The result is:

AGE YYYY MM DD
820020 82 0 20

fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.