2011-06-06 92 views
0

的Oracle SQL Developer抱怨下一個SQL但我似乎無法找到原因:Oracle 10g中簡單的查詢錯誤

IF to_number(to_char(sysdate, 'HH24')) > 6 THEN 
    IF to_number(to_char(sysdate, 'HH24')) < 9 THEN 
    SELECT 1 FROM dual; 
    ELSE 
    SELECT (CASE WHEN result = 'SUCCESS' THEN 1 ELSE 0 END) FROM t_job WHERE to_char(start_time, 'yyyy/mm/dd') = to_char(sysdate, 'yyyy/mm/dd'); 
    END IF; 
ELSE 
    SELECT (CASE WHEN result = 'SUCCESS' THEN 1 ELSE 0 END) FROM t_job WHERE to_char(start_time, 'yyyy/mm/dd') = to_char(sysdate, 'yyyy/mm/dd'); 
END IF; 

什麼是在提供的查詢錯誤了嗎?

錯誤報告:

Error starting at line 7 in command: 
ELSE 
Error report: 
Unknown Command 
(CASEWHENRESULT='SUCCESS'THEN1ELSE0END) 
--------------------------------------- 
1          


Error starting at line 9 in command: 
END IF 
Error report: 
Unknown Command 
+0

它究竟如何抱怨? ) – 2011-06-06 15:11:59

+0

@be現在在這裏,已經添加,只是意識到它的缺失:) – 2011-06-06 15:12:27

回答

3

有幾個問題與您的代碼(這是PL/SQL,而不僅僅是SQL):

1)你缺少周圍的beginend塊。

2)你select的需要一個into條款

嘗試:

DECLARE 
    l_result number; 
BEGIN 
    IF to_number(to_char(sysdate, 'HH24')) > 6 THEN 
    IF to_number(to_char(sysdate, 'HH24')) < 9 THEN 
     SELECT 1 INTO l_result FROM dual; 
    ELSE 
     SELECT (CASE WHEN result = 'SUCCESS' THEN 1 ELSE 0 END) 
     INTO l_result 
     FROM t_job WHERE to_char(start_time, 'yyyy/mm/dd') = to_char(sysdate, 'yyyy/mm/dd'); 
    END IF; 
    ELSE 
     SELECT (CASE WHEN result = 'SUCCESS' THEN 1 ELSE 0 END) 
     INTO l_result 
     FROM t_job WHERE to_char(start_time, 'yyyy/mm/dd') = to_char(sysdate, 'yyyy/mm/dd'); 
    END IF; 
    dbms_output.put_line('result is '||l_result); 
END; 
+0

'to_char(start_time,'yyyy/mm/dd')= to_char(sysdate,'yyyy/mm/dd')'聽起來像一個壞習慣我也是 – 2011-06-06 15:17:53

+0

而不是'to_char(start_time,'yyyy/mm/dd')= to_char(sysdate,'yyyy/mm/dd')''我會爲'trunc(start_time)= trunc(sysdate) – 2011-06-06 15:18:58

+0

@Tonu安德魯斯,這是原始變種,但它是如何影響性能? – 2011-06-06 15:20:46

2

因爲這是一個PL/SQL塊,你的SELECT語句需要選擇數據到一些局部變量或他們將需要在遊標中使用。您想要的方法取決於T_JOB中有多少行可能與您指定的條件匹配。假設所有三個語句將只返回1行中,你可以做這樣的事情(簡化,以避免重複相同的查詢兩次代碼)

DECLARE 
    l_some_local_variable PLS_INTEGER; 
BEGIN 
    IF(to_number(to_char(sysdate, 'HH24')) > 6 and 
     to_number(to_char(sysdate, 'HH24')) < 9) 
    THEN 
    SELECT 1 
     INTO l_some_local_variable 
     FROM dual; 
    ELSE 
    SELECT (CASE WHEN result = 'SUCCESS' 
       THEN 1 
       ELSE 0 
      END) 
     INTO l_some_local_variable 
     FROM t_job 
    WHERE trunc(start_time) = trunc(sysdate); 
    END IF; 
END; 

當然,一旦你在你的局部變量填充數據,您需要實際上做了一些有價值的事情。可能,您可能想要創建一個返回局部變量的函數,而不是像我這裏所做的那樣使用匿名PL/SQL塊。

+0

你的答案很好,但託尼安德魯斯是第一個。不過,非常感謝。 :) – 2011-06-06 15:38:25