我正在创建一个函数,我需要根据参数值(PTIPO)在两个句子之间进行选择
以下是我的代码
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 = pcajaid AND(
CASE WHEN(PTIPO = 2) --this is what causes the issue.
THEN
b.cod_compro = ncompini OR (b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin)
ELSE
b.cod_compro != ncompini AND b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin
END);
错误是“缺少关键字”,但我知道问题是最后一个案例。 我怎么能在句子之间做出选择。案件是正确的方式还是我应该使用另一种陈述?
答案 0 :(得分:3)
案例可以返回值,但不能返回表达式。这应该可以解决问题,虽然我觉得它甚至可以更简单:
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 = pcajaid AND
(
(PTIPO = 2 and (b.cod_compro = ncompini OR b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin))
OR
(PTIPO <> 2 and (b.cod_compro != ncompini AND b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin))
)
答案 1 :(得分:1)
试试这个:
WHERE c.cajaid = pcajaid AND
(
PTIPO = 2
AND (
b.cod_compro = ncompini
OR b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin
)
OR
PTIPO != 2
AND (
b.cod_compro != ncompini
AND b.fecha_mov BETWEEN pfecha_ini AND pfecha_fin
)
)