在这种情况下,参数如何通过

时间:2017-06-01 11:48:29

标签: oracle procedure

我在oracle中有一个程序

CREATE OR REPLACE 
PROCEDURE ReportCalculate
  (
        param_acTypeId in NUMBER
)
  AS 
  sqlstr VARCHAR2(500);
  result NUMBER;
  BEGIN
    sqlstr:='select count(1) from table1 where 1=1 and AC_TYPE_LEVEL1_ID=:acTypeId';
    execute immediate sqlstr into result using param_acTypeId;
    DBMS_OUTPUT.PUT_LINE(result);
  END;

但有时我想查询所有数据,sql看起来像这样 select count (1) from table1 where 1 = 1 and AC_TYPE_LEVEL1_ID = AC_TYPE_LEVEL1_ID, 那么参数应该如何传递,或者param_acTypeId应该有任何默认值?难道只有在拼接sql时判断它吗?

2 个答案:

答案 0 :(得分:1)

一种典型的方法是接受NULL作为“全部”的意思:

sqlstr := 'select count(1) from table1 where AC_TYPE_LEVEL1_ID = :acTypeId or :acTypeId is null';

我应该注意到这个版本排除了索引的使用。如果性能是个问题,那么使用两个查询:

if param_acTypeId is null then
    sqlstr := 'select count(1) from table1';
    execute immediate sqlstr into result;
else 
    sqlstr := 'select count(1) from table1 where AC_TYPE_LEVEL1_ID = :acTypeId';
    execute immediate sqlstr into result using param_acTypeId;
end if;
DBMS_OUTPUT.PUT_LINE(result);

答案 1 :(得分:1)

您不需要动态SQL。如果您传入NULL,则会计算所有行:

CREATE OR REPLACE PROCEDURE ReportCalculate (
  param_acTypeId in NUMBER
)
AS 
  result NUMBER;
BEGIN
  select count(1)
  into   result
  from   table1
  where  ( param_acTypeId IS NULL OR AC_TYPE_LEVEL1_ID = param_acTypeId );

  DBMS_OUTPUT.PUT_LINE(result);
END;