如果在Where子句中声明

时间:2013-03-13 20:51:41

标签: oracle plsql plsqldeveloper

我正在处理一个查询,其中包含“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:缺少右括号”

2 个答案:

答案 0 :(得分:11)

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进行比较。我对business_unit列使用第二个CASE语句执行相同的操作。

答案 1 :(得分:4)

你不能像那样使用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;