在if语句中的子查询(plsql)

时间:2020-09-15 15:12:26

标签: oracle plsql

我想查找 p_param2 是否在子查询中,然后根据此结果执行一些操作。此子查询返回多于1行。

  if p_param1 = 1
     and p_param2 in (select code from x_table where code is not null) then
    --..Some operations..
  end if;

但是出现 PLS-00405 错误。如何才能有效地编写此代码?

2 个答案:

答案 0 :(得分:1)

声明一个变量v_dummy number。然后:

begin
   select 1
     into v_dummy
     from x_table
    where code = p_param2;

   exception
      when no_data_found then
         v_dummy := 0;
end;

if p_param1 = 1 and v_dummy = 1 then
.
.
.
end if;

如果x_table.code可以包含重复值,则必须决定在发现一个以上的p_param2事件时该怎么做。

答案 1 :(得分:1)

您需要在单独的SQL查询中的IF..THEN语句之前获取所需的值,而当前情况是不可能的。试试这种使用COUNT()聚合而不需要异常处理的方法:

DECLARE
  p_param1 ...
  p_param2 ... 
  p_exists INT;
BEGIN
   SELECT SIGN( COUNT(*) )
     INTO p_exists
     FROM x_table 
    WHERE code IS NOT NULL 
      AND code = p_param2;
      
 IF p_param1 = 1 AND p_exists = 1 THEN
   -- some operations
 END IF;
END; 
/
相关问题