带有case语法的where子句中的日期类型

时间:2013-07-26 00:52:30

标签: sql

SELECT *
  FROM orders do
 WHERE (CASE TO_CHAR(sysdate,'D')
        WHEN '1'    THEN do.create_date=sysdate
        WHEN '2'    THEN do.create_date BETWEEN sysdate-1 AND sysdate
        WHEN '3'    THEN do.create_date BETWEEN sysdate-2 AND sysdate
        WHEN '4'    THEN do.create_date BETWEEN sysdate-3 AND sysdate
        WHEN '5'    THEN do.create_date BETWEEN sysdate-4 AND sysdate
        WHEN '6'    THEN do.create_date BETWEEN sysdate-5 AND sysdate
        WHEN '7'    THEN do.create_date BETWEEN sysdate-6 AND sysdate
        END)

这有什么问题?我收到以下错误消息

Error Msg : 
ORA-00905: missing keyword
00905. 00000 -  "missing keyword"
*Cause:    
*Action:
Error at Line: 46 Column: 37

1 个答案:

答案 0 :(得分:1)

where语句返回一个值,而不是布尔值。也就是说,betweenwhen子句中没有意义。

这是表达条件的另一种方式:

select *
from orders do
where do.created_date between sysdate - (cast(to_char(sysdate,'D') as int) - 1) and sysdate;

如果您想使用between执行此操作,则可能是这样的:

select *
from orders do
where do.create_date between s
          (case to_char(sysdate,'D')
               WHEN '1'    THEN sysdate
               WHEN '2'    THEN sysdate-1
               WHEN '3'    THEN sysdate-2 
               WHEN '4'    THEN sysdate-3
               WHEN '5'    THEN sysdate-4
               WHEN '6'    THEN sysdate-5
               WHEN '7'    THEN sysdate-6
           END) and sysdate;