1

以下のクエリの 7 行目で次のエラーが発生するのはなぜですか?

Error: ORA-01861: literal does not match format string

Query:

01: SELECT hour
02: FROM (WITH all_hours AS
03:             (SELECT TO_DATE ('2000-01-01', 'yyyy-mm-dd') 
04:                      + NUMTODSINTERVAL (LEVEL - 1, 'hour') hour
05:              FROM DUAL
06:              CONNECT BY LEVEL <= 1000000)
07:      SELECT TO_CHAR (h.hour, 'yyyy-mm-dd hh:mi am') hour
08:      FROM all_hours h
09:      GROUP BY h.hour)
10: WHERE hour BETWEEN TO_DATE ('2009-11-10 01:00 am', 'yyyy-mm-dd hh:mi am')
11:                AND TO_DATE ('2009-11-10 01:00 am', 'yyyy-mm-dd hh:mi am')
4

2 に答える 2

6

うーん、7 行目ではありません。問題は、あるレベルの「時間」が文字列 (to_char) に変換されるのですが、その後は日付と比較され、暗黙の変換が常に機能するとは限りません。修正されたクエリ:

SELECT hour
FROM (WITH all_hours AS
            (
            SELECT TO_DATE ('2000-01-01', 'yyyy-mm-dd') 
                     + NUMTODSINTERVAL (LEVEL - 1, 'hour') hour
             FROM DUAL
             CONNECT BY LEVEL <= 1000000
             )
     SELECT TO_CHAR (h.hour, 'yyyy-mm-dd hh:mi am') hour, h.hour as hourdate
     FROM all_hours h
     GROUP BY h.hour)
WHERE hourdate BETWEEN TO_DATE ('2009-11-10 01:00 am', 'yyyy-mm-dd hh:mi am')
               AND TO_DATE ('2009-11-10 01:00 am', 'yyyy-mm-dd hh:mi am')
于 2009-11-10T17:00:02.013 に答える
1

WHERE 句で DATE を CHAR と比較しています。これはうまくいくはずです:

SQL> SELECT TO_CHAR(hour, 'yyyy-mm-dd hh:mi am')
  2    FROM (WITH all_hours AS (SELECT TO_DATE('2000-01-01', 'yyyy-mm-dd')
  3                              + NUMTODSINTERVAL(LEVEL - 1, 'hour') hour
  4                               FROM DUAL
  5                             CONNECT BY LEVEL <= 1000000)
  6          SELECT hour FROM all_hours h GROUP BY h.hour)
  7   WHERE hour BETWEEN TO_DATE('2009-11-10 01:00 am', 'yyyy-mm-dd hh:mi am')
  8          AND TO_DATE('2009-11-10 01:00 am', 'yyyy-mm-dd hh:mi am')
  9  ;

TO_CHAR(HOUR,'YYYY-MM-DDHH:MIA
------------------------------
2009-11-10 01:00 am
于 2009-11-10T17:00:23.297 に答える