如果条件在案件内

时间:2013-01-26 14:31:27

标签: mysql sql oracle oracle11g

我正在将一些MySQL 5.0函数转换为Oracle 11g。

我需要在案例中放置一个IF但是会​​收到错误(缺少右括号) 这是我的代码

SELECT SUM(
    CASE PTIPO
      WHEN 0 THEN (SELECT IF(A.NT = 0) THEN A.VALOR ELSE 0 END IF FROM DUAL)
      WHEN 1 THEN (SELECT IF(A.NT = 1) THEN A.VALOR ELSE 0 END IF FROM DUAL)
      WHEN 2 THEN (SELECT IF(A.NT = 1) THEN A.VALOR ELSE -A.VALOR END IF FROM DUAL)
    END)
INTO nresp
FROM mov_caja a
JOIN enc_movp b ON a.docid = b.docid
JOIN c_caja c ON a.cajaid = c.cajaid
WHERE c.cajaid

2 个答案:

答案 0 :(得分:5)

IF / ELSE用于函数内部和准备好的语句中的流控制,而不是用于单个语句中的汇编条件。

真的,您只需要使用其他句法格式CASE将另一个CASE WHEN <condition> THEN <value>嵌套到内部:

SELECT SUM(
    CASE PTIPO
      WHEN 0 THEN (CASE WHEN (A.NT = 0) THEN A.VALOR ELSE 0 END)
      WHEN 1 THEN (CASE WHEN (A.NT = 1) THEN A.VALOR ELSE 0 END)
      WHEN 2 THEN (CASE WHEN (A.NT = 1) THEN A.VALOR ELSE -A.VALOR END)
    END)
INTO nresp
FROM mov_caja a
JOIN enc_movp b ON a.docid = b.docid
JOIN c_caja c ON a.cajaid = c.cajaid
WHERE c.cajaid

答案 1 :(得分:3)

您可以将其重写为:

SELECT SUM(
    CASE 
      WHEN PTIPO = 0 and A.NT  = 0 THEN A.VALOR 
      WHEN PTIPO = 0 and A.NT <> 0 THEN 0
      WHEN PTIPO = 1 and A.NT  = 1 THEN A.VALOR 
      WHEN PTIPO = 1 and A.NT <> 1 THEN 0
      WHEN PTIPO = 2 and A.NT  = 1 THEN A.VALOR 
      WHEN PTIPO = 2 and A.NT <> 1 THEN -A.VALOR 
    END)
INTO nresp
FROM mov_caja a
JOIN enc_movp b ON a.docid = b.docid
JOIN c_caja c ON a.cajaid = c.cajaid
WHERE c.cajaid