Vicky
Vicky

Reputation: 17375

Formatting date in YYYYMM format in DB2

I am getting a date as a String from a table below in the format:

2014-09-02 

which is YYYY-MM-DD format.

The query is:

SELECT VALUE FROM MYSCHEMA.MYTABLE WHERE CODE = 'MYDATE'

I want to modify above query so that the result is:

201402

I tried this, but not getting in correct format:

select char(year(date(value))) || char(month(date(value))) from MYSCHEMA.MYTABLE WHERE CODE = 'MYDATE'

The result is coming as:

 1            
------------ 
2014       9 

I have db2 9.5 with me.

Upvotes: 1

Views: 37156

Answers (2)

bhamby
bhamby

Reputation: 15450

If you're actually getting a DATE data type (and even if you're not, in the ISO format you have there, DB2 should be smart enough to convert it automatically), then you can use the VARCHAR_FORMAT scalar function:

SELECT VARCHAR_FORMAT(VALUE, 'YYYYMM')
FROM MYSCHEMA.MYTABLE
WHERE CODE = 'MYDATE'

Upvotes: 8

Emily
Emily

Reputation: 385

If all your strings are going to be in the exact same format, why not just remove the dashes with REPLACE() and then grab a substring, like so:

SELECT SUBSTR(REPLACE(VALUE,'-',''),1,6) FROM MYSCHEMA.MYTABLE WHERE CODE='MY DATE'

Also, as Dan said, in your example you only selected the year and day, but I'm assuming from your code that you want the year and month.

Upvotes: 0

Related Questions