2013-03-13 169 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