We are generating a period dimension in a DB2 (7.2) warehouse using a bunch of auto-generated columns. Many of these columns require a formatted date string. But the DB2 date functions in question return integers, meaning that for a simple result of the form "CCYY-MM-DD", we're using the following:
CAST(YEAR(NATURAL_DATE) AS CHAR(4)) || '-' || RIGHT(DIGITS(MONTH(NATURAL_DATE)), 2) || '-' || RIGHT(DIGITS(DAY(NATURAL_DATE)), 2)(1) Is there a shorthand way to do this (say, similar to C's "format" function)?
(2) Is there a way of forcing a result's data type without using CAST?
Looks like you've found the correct way to do this. I have to ask, what data type is the NATURAL_DATE column? If it is a DB2 DATE data type, then you should be able to use CHAR(NATURAL_DATE,ISO) instead. This will return the date as a character expression in the format you require (ISO).
For More Information
- Dozens more answers to tough DB2 questions from Craig Mullins are available.
- The Best IBM DB2 Web Links: tips, tutorials, scripts, and more.
- Have a DB2 tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical DB2 questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
This was first published in November 2002