How can I add leading zeros to dates in Oracle?

二次信任 提交于 2019-12-10 12:42:16

问题


I need to add leading zeros to a number if it is less than two digits and combine two such numbers into single one without space between them.

My Attempt:

select ( extract (year from t.Dt)
         || to_char(extract (month from t.Dt),'09')
         || to_char(extract (day from t.Dt),'09') ) as dayid 
  from ATM_FACTS t;

Result:

So, my problem is how can I remove the space in between month-year and month-day. I used

select ( extract (year from t.Dt)
         || to_number(to_char(extract (month from t.Dt),'09'))
         || to_number(to_char(extract (day from t.Dt),'09')) ) as dayid 
  from ATM_FACTS t;

but the leading zeros disappear.


回答1:


It doesn't look like you want to add leading zero's, it looks like you're not converting your date to a character in exactly the way you want. The datetime format model of TO_CHAR() is extremely powerful, make full use of it.

select to_char(dt, 'yyyymmdd') as dayid
  from atm_facts

To actually answer your question you can use a number format model with TO_CHAR() to pad with leading 's.

For instance, the following returns 006

select to_char(6, 'fm009') from dual;

You can use the format model modifier fm, mentioned in the docs above, to remove leading spaces if necessary.




回答2:


Is t.Dt a DATE? You can format them in one single to_char statement:

to_char(t.Dt, 'YYYYMMDD')


来源:https://stackoverflow.com/questions/16585608/how-can-i-add-leading-zeros-to-dates-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!