【问题标题】:If statement within Where clauseWhere 子句中的 if 语句
【发布时间】:2013-03-02 00:45:15
【问题描述】:

我正在处理一个在“WHERE”子句中包含“IF”语句的查询。但是 PL\SQL Developer 在执行时给出了一些错误。谁能帮我正确查询?这是查询:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE IF status_flag = STATUS_ACTIVE then t.status = 'A'
       IF status_flag = STATUS_INACTIVE then t.status = 'T'
       IF source_flag = SOURCE_FUNCTION then t.business_unit = 'production'
       IF source_flag = SOURCE_USER then t.business_unit = 'users'
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

我收到错误“ORA-00920:无效的关系运算符”。

status_flag = STATUS_ACTIVE 周围放置括号会导致错误“ORA-00907:缺少右括号”

【问题讨论】:

    标签: oracle plsql plsqldeveloper


    【解决方案1】:

    你不能这样使用 IF。你可以用 AND 和 OR 做你想做的事:

    SELECT t.first_name,
           t.last_name,
           t.employid,
           t.status
      FROM employeetable t
     WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
         OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
         OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
         OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
       AND t.first_name LIKE firstname
       AND t.last_name  LIKE lastname
       AND t.employid   LIKE employeeid;
    

    【讨论】:

      【解决方案2】:

      CASE 可能会帮助你:

      SELECT t.first_name,
             t.last_name,
             t.employid,
             t.status
        FROM employeetable t
       WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
                              WHEN status_flag = STATUS_INACTIVE THEN 'T'
                              ELSE null END)
         AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
                                     WHEN source_flag = SOURCE_USER THEN 'users'
                                     ELSE null END)
         AND t.first_name LIKE firstname
         AND t.last_name LIKE lastname
         AND t.employid LIKE employeeid;
      

      CASE statement 评估多个条件以生成单个值。因此,在第一次使用中,我检查 status_flag 的值,根据它的值返回“A”、“T”或 null,并将其与 t.status 进行比较。我使用第二个 CASE 语句对 business_unit 列执行相同的操作。

      【讨论】:

      • @DCookie,如何在 IF 语句中添加 WHERE 子句条件?
      • 案例:t.status = null 不适用于 t.status 实际上为空的情况。 Null 很奇怪。
      • @defactodeity 检查是否为 null -- t.status 为 null
      • 它对我不起作用。当我尝试这样做时,我得到一个错误 (ORA-00920)。错误是在THEN 关键字上触发的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多