简体   繁体   中英

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.

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM