我正在尝试在程序的WHERE子句中执行IF / ELSE,但似乎没有正确的工作。我不确定我是否正确构建它。
我得到PL / SQL:ORA-00933:SQL命令未正确结束于“IF p_job_year IS NOT NULL THEN”
这就是我所拥有的:
WHERE
(val1s.val1 = p_val1 OR p_val1 IS NULL) AND
(UPPER(val2s.val2) LIKE UPPER(p_val2) OR p_val2 IS NULL) AND
(jp.row_top.job_type_id = p_job_type_id OR p_job_type_id IS NULL)
AND ntab.group_id = pgds.id(+)
AND jp.row_top.val1_id = val1s.id(+)
AND val1s.val2_id = val2s.id(+)
IF p_job_year IS NOT NULL THEN <<<<<<<< ERROR HERE
AND p_job_year = ntab.fiscal_year(+)
AND jp.jobload_year = p_job_year
AND jp.row_top.fiscal_year = p_job_year
ELSE
AND jp.jobload_year < TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY')
AND jp.row_top.fiscal_year < TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY')
END IF;
AND JP.VER = (select MAX(jp2.ver) from job_plans jp2
WHERE JP.ID_NUMBER = JP2.ID_NUMBER)
AND jack_work_pkg.get_last_jack_work_first_type(jp.id) != 1;
RETURN result_cur;
END summarize_work_data;
答案 0 :(得分:3)
你不能以这种方式使用IF子句,你必须稍微不同地构造where子句。
AND
(
(
p_job_year IS NULL
AND jp.jobload_year < TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY')
AND jp.row_top.fiscal_year < TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY')
)
OR
(
p_job_year is not NULL
AND p_job_year = ntab.fiscal_year(+)
AND jp.jobload_year = p_job_year
AND jp.row_top.fiscal_year = p_job_year
)
)
答案 1 :(得分:0)
是什么让您认为可以将IF / ELSE / END IF写入WHERE子句?
基本上你可以添加到WHERE子句的是这样的:
AND (
(p_job_year IS NOT NULL AND (
AND p_job_year = ntab.fiscal_year(+)
AND jp.jobload_year = p_job_year
AND jp.row_top.fiscal_year = p_job_year))
OR (p_job_year IS NULL AND (
AND jp.jobload_year < TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY')
AND jp.row_top.fiscal_year < TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY')))
)
答案 2 :(得分:0)
我假设整个块只是where子句。如果是这种情况,则不能在where子句中使用“IF..ELSE”。
而不是使用
Where condition1
and condition2
and IF Condition3 then
AND condition4...
ELSE
condition5
and <.....>
像这样重写你的查询。只需要使用AND和OR以及括号
Where condition1
and condition2
and ((Condition3 and condition4) or (condition5))
and <.....>
答案 3 :(得分:0)
在WHERE子句中没有IF THEN ELSE - 但如果需要,可以使用CASE WHEN THEN ELSE进行补偿...
答案 4 :(得分:-1)
嗯,这并不像你想象的那么简单。您无法以这种方式创建动态查询。
一个选项是将查询创建为字符串,并使用execute immediate
来运行它。