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
460 views
in Technique[技术] by (71.8m points)

sql - issue with to_date function with sysdate

I saw this question so I've one doubt regarding this question: I am getting different result with the same date on the following query.

SELECT TO_CHAR(to_date(sysdate, 'DD-MON-yy'), 'DAY'),
  TO_CHAR(to_date(sysdate, 'DD-MON-yyyy'), 'DAY'),
  TO_CHAR(to_date(sysdate, 'DD-MON-rr'), 'DAY'),
  TO_CHAR(to_date(sysdate, 'DD-MON-rrrr'), 'DAY')
FROM dual;

output as column-wise:

TUESDAY SUNDAY TUESDAY TUESDAY

please help me, Thanks in advance.

EDIT

I wrote a simple procedure which passing date for finding the day given below:

SET serveroutput ON;
CREATE OR REPLACE
    PROCEDURE simple_test
      (
        date_in         IN VARCHAR2)
                        IS
      v_date DATE       := to_date(date_in,'dd-mon-yyyy');
      v_day VARCHAR2(10):=TO_CHAR(v_date,'day');
    BEGIN
       dbms_output.put_line('the day of given date is '||v_day);
    END;
    /

EXEC simple_test(sysdate);

anonymous block completed
the day of given date is sunday  

EXEC simple_test('01-JAN-2013');

anonymous block completed
the day of given date is tuesday  

why does this happened?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I want to explain why you get different results.

See this sqlfiddle

As it is already said, sysdate is seen as DATE type and you are doing an implicit conversion when

select to_date(sysdate, format) from dual;

because first parameter of to_date should be varchar type the system does:

select to_date(to_char(sysdate), format) from dual;

because your implicit date format is 'DD-MON-YY', your query goes into:

SELECT TO_CHAR(to_date('01-JAN-13', 'DD-MON-yy'), 'DAY'),
  TO_CHAR(to_date('01-JAN-13', 'DD-MON-yyyy'), 'DAY'),
  TO_CHAR(to_date('01-JAN-13', 'DD-MON-rr'), 'DAY'),
  TO_CHAR(to_date('01-JAN-13', 'DD-MON-rrrr'), 'DAY')
FROM dual;

the second to_date, because yyyy is a full thousands year format, goes to '01-JAN-0013' which is 13AD and probably is SUNDAY :)


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

...