1

i am having problems with converting a varchar(yyyymmdd) to date(yyyymmdd).

i have a procedure with a parameter (pdate varchar2, yyyymmdd format) which needed to be converted to date type in yyyymmdd format as well. so far i tried.

vdate date;

 vdate := (to_date(SUBSTR(pdate,1,4)+SUBSTR(pdate,5,2)+SUBSTR(pdate,7,2), 'yyyymmdd'));

this threw a error of ORA-01840: input value not long enough for date format.

any help would be appreciated.

3
  • What is the value of a pdate that is failing? change + to || Consider: SELECT (SUBSTR('20170101',1,4)||SUBSTR('20170101',5,2)||SUBSTR('20170101',7,2)) , to_date(SUBSTR('20170101',1,4)||SUBSTR('20170101',5,2)||SUBSTR('20170101',7,2),'YYYYMMDD') , To_date('20170101','YYYYDDMM') from dual; Commented Aug 31, 2017 at 14:41
  • 3
    you just need to_date(pdate, 'yyyymmdd'), assuming that your pdate contains the full set of information. In fact, I'm pretty sure you can get rid of your procedure and just use the to_date() function! Commented Aug 31, 2017 at 14:42
  • 2
    The reason your attempt is failing, as has been pointed out, is that concatenation is done with || in Oracle, not with +. What you are doing is that you are extracting the year, month and date, as strings (four digits, two digits, two digits). Then you add them. Behind the scenes, Oracle converts them to NUMBER and adds them. Then you apply to_date() which takes a varchar2 input, so Oracle - again behind the scenes - converts the result of the addition to a four-character string. Which is not long enough to become a date (and it would be a wrong one anyway!) Commented Aug 31, 2017 at 16:08

2 Answers 2

2

Just use a to_date

select to_date(MyDate, 'yyyymmdd')
from mytable

Test with:

select to_date('20170831','yyyymmdd')
from dual

Also, to concatenate in Oracle, use a double pipe ||

select 'Chicken'||'Food'
from dual
Sign up to request clarification or add additional context in comments.

Comments

2

If pdate has other characters after yyyymmdd, and yyyymmdd is in the beginning of the whole text, you can just use

SELECT TO_DATE(SUBSTR(pdate,1,8), 'yyyymmdd')
  FROM yourtable;

Example

SELECT TO_DATE(SUBSTR('20170831 10:30am',1,8), 'yyyymmdd')
  FROM dual;

Otherwise, you can directly use TO_DATE() as suggested by most that replied

1 Comment

This should be the accepted answer as far as PL/SQL oracle syntax is concerned. Kudos.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.