存储过程中的动态sql

时间:2017-06-01 09:33:22

标签: sql oracle dynamic

我想传入一个动态列名来计算它的标准差,在oracle中,以下是代码:

CREATE OR REPLACE 
PROCEDURE ReportCalculate
  (
    param_columnName IN VARCHAR2 DEFAULT 'COMPUTED_CP_MLIFTOFF_KNOT9OR10'
)
  AS 
  sqlstr VARCHAR2(500);
  result NUMBER;
  BEGIN
    sqlstr:='select stddev(:col) from LIDISUDUXIAO where 1=1 and NO_10_LIMITSIGN_DEPART_ID<>0';
    execute immediate sqlstr into result using param_columnName;
    DBMS_OUTPUT.PUT_LINE(result);
  END;

我用默认参数调用它,错误信息是:

Procedure execution failed
ORA-01722: invalid number
ORA-06512: at "AGS.REPORTCALCULATE", line 10
ORA-06512: at line 1

我该如何解决?

1 个答案:

答案 0 :(得分:1)

列名不能用作查询的参数。在执行之前,您需要编辑 sqlstr 变量以在查询中包含提供的 param_columnName

CREATE OR REPLACE 
PROCEDURE ReportCalculate
  (
    param_columnName IN VARCHAR2 DEFAULT 'COMPUTED_CP_MLIFTOFF_KNOT9OR10'
)
  AS 
  sqlstr VARCHAR2(500);
  result NUMBER;
  BEGIN
    sqlstr:='select stddev(' || param_columnName || ') from LIDISUDUXIAO where 1=1 and NO_10_LIMITSIGN_DEPART_ID<>0';
    execute immediate sqlstr into result;
    DBMS_OUTPUT.PUT_LINE(result);
  END;