14

我正在处理一个在“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:缺少右括号”

4

2 回答 2

16

案例可能会帮助您:

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

于 2013-03-14T00:26:10.117 回答
6

你不能像那样使用 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;
于 2013-03-13T20:56:33.337 回答