2013-03-13 136 views
5

我正在使用包含“WHERE”子句中的“IF”语句的查询。但PL \ SQL Developer在执行时会出现一些错误。任何人都可以请帮助我正确的查询?以下是查询:如果在Where子句中的语句

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:invalid relational operator”。

配售括号status_flag = STATUS_ACTIVE导致错误“ORA-00907:缺少右括号”

回答

9

案件可能帮助你:

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列做同样的事情。

+0

谢谢!这真的有帮助 – user2100620 2013-03-14 13:49:43

+0

@DCookie,如何在IF语句中添加WHERE子句条件? – masT 2014-06-19 12:12:09

+0

案例:'t.status = null'在t.status实际上为null的情况下不起作用。空很奇怪。 – defactodeity 2014-12-18 06:57:00

3

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; 
+0

而不是使用AND和OR,如果我使用CASE怎么办? 'WHERE CASE 当status_flag = STATUS_ACTIVE然后t.status = 'A' 当status_flag = STATUS_INACTIVE然后t.status = 'T' 当source_flag = SOURCE_FUNCTION然后t.business_unit = '生产' 当source_flag = SOURCE_USER然后t.business_unit = '用户' END 和t.first_name LIKE姓 和t.last_name LIKE姓氏 和t.employid LIKE雇员;' 我得到错误 “ORA-00905:缺少关键字”。在那种情况下我做错了什么? – user2100620 2013-03-13 21:01:48

+0

看到我的答案。你越来越近了。 – DCookie 2013-03-14 00:27:36