【问题标题】:SQL Case statement throwing missing keyword errorSQL Case语句抛出缺少关键字错误
【发布时间】:2023-03-20 19:10:01
【问题描述】:

我正在尝试这个查询:

Select * from users_t t
where
case when sysdate <= to_date('20130131', 'yyyymmdd')
then t.user_id=1254664
else t.user_id=1259753
End

为什么会出现“ORA-00905:缺少关键字”错误?

【问题讨论】:

    标签: sql oracle oracle10g oracle11g


    【解决方案1】:

    您需要一个比较运算符case 语句之外:

    Select * from users_t t
    where
    (case when sysdate <= to_date('20130131', 'yyyymmdd')
    then 254664
    else 1259753
    End) = t.user_id
    

    但是,您可以在不使用 case 语句的情况下编写此代码:

    select *
    from users_t t
    where ((sysdate <= to_date('20130131', 'yyyymmdd') and t.user_id = 254664) or
          ((sysdate > to_date('20130131', 'yyyymmdd') and t.user_id = 1259753)
    

    【讨论】:

      【解决方案2】:

      您的案例陈述不正确。

      SELECT * 
      FROM users_t t
      WHERE t.user_id = CASE WHEN SYSDATE <= TO_DATE('20130131', 'yyyymmdd')
                             THEN 1254664
                             ELSE 1259753
                        END
      

      这将完成你的任务。

      编辑:更好的格式。

      【讨论】:

        【解决方案3】:

        SQL 中的CASE 语句始终返回一个值。您需要将此CASE 声明等同于某事。阅读更多关于它的信息here

        您应该使用以下代码:

        Select * from users_t t
        where
        t.user_id = case
                         when sysdate <= to_date('20130131', 'yyyymmdd')
                         then 1254664
                         else 1259753
                    End
        

        【讨论】:

          【解决方案4】:

          这个错误的根本原因是Oracle SQL 中没有布尔数据类型。 (我个人认为这是一个巨大的错误。)

          返回一个条件是一个完全有效的想法,它甚至可以在 PL/SQL 中使用:

          declare
              v_test Boolean;
          begin
              v_test := case when 1=1 then 1=1 else 1=2 end;
          end;
          /
          

          【讨论】:

            猜你喜欢
            • 2015-04-17
            • 2020-01-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-01-12
            • 2020-08-14
            • 1970-01-01
            相关资源
            最近更新 更多