Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

sql - How to extract month number from date in Oracle

I have ID_BB_SECURITY column where the date value is stored in this column for example '20190801'.

I want to get month number from this field for example for August date i want to get 8.

I tried below query but it throws an error 'literal does not match':

select to_number(to_date(ID_BB_SECURITY),'mm') from BT_EXPORT

I am not sure if i have to ignore null values so as to avoid the error

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the value is a number or string then you can convert it to a date with an appropriate mask - which is what you are missing, and what is causing the error you are getting (as it's using your session's NLS_DATE_FORMAT setting, which apparently does not match the format of the data; but which you should not rely on anyway, as @MTO said in comments):

to_date(ID_BB_SECURITY, 'YYYYMMDD')

and then extract the month number from that:

select extract(month from to_date(ID_BB_SECURITY, 'YYYYMMDD')) from BT_EXPORT

Or you could just use a substring:

select to_number(substr(ID_BB_SECURITY, 5, 2)) from BT_EXPORT;

Those assume a fixed consistent format, which is always a risky assumption when using the wrong data type. Ans if it's a number they are doing an implicit conversion from number to string, which you could turn into an explicit conversion for greater clarity.

If it's already a date - as it should be, of course - then you don't need the conversion:

select extract(month from ID_BB_SECURITY) from BT_EXPORT

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...