面对ORA-01722:从表中选择数据时出现无效的数字错误

时间:2016-07-04 17:58:33

标签: oracle plsql

CREATE OR REPLACE FUNCTION XXCHR_FNC(
  P_EMP_ID         IN   NUMBER,
  P_COLUMN_NAME    IN   VARCHAR2
) RETURN VARCHAR2
IS
  lv_dyn_sql    VARCHAR2(2000):= NULL;
  lv_return_val VARCHAR2(200);
BEGIN
  lv_dyn_sql:='SELECT :2 FROM thirty_days '
               || 'WHERE salesrep_id=:1';

  EXECUTE IMMEDIATE lv_dyn_sql INTO lv_return_val
  USING P_EMP_ID,P_COLUMN_NAME;

  RETURN(lv_return_val);
EXCEPTION
  WHEN OTHERS THEN
    dbms_output.put_line('Returning Error : '||SQLERRM);
    RETURN (SQLERRM);
END XXCHR_FNC;

1 个答案:

答案 0 :(得分:0)

您不能将列名称作为绑定变量传递 - 如果这样做,您将返回列名称作为字符串文字,而不是从列中获取值。您需要在SQL字符串上使用连接:

CREATE OR REPLACE FUNCTION XXCHR_FNC(
  P_EMP_ID         IN   NUMBER,
  P_COLUMN_NAME    IN   VARCHAR2
) RETURN VARCHAR2
IS
  lv_return_val VARCHAR2(200);
BEGIN
  EXECUTE IMMEDIATE
    'SELECT ' || P_COLUMN_NAME || ' FROM thirty_days WHERE salesrep_id=:1'
  INTO  lv_return_val
  USING P_EMP_ID;

  RETURN lv_return_val;
EXCEPTION
  WHEN OTHERS THEN
    dbms_output.put_line('Returning Error : '||SQLERRM);
    RETURN SQLERRM;
END XXCHR_FNC;
/

<强>测试

CREATE TABLE thirty_days (
  salesrep_id NUMBER(8,0),
  a VARCHAR2(20),
  b VARCHAR2(20),
  c VARCHAR2(20),
  d VARCHAR2(20)
);

INSERT INTO thirty_days VALUES( 1, 'a', 'b', 'c', 'd' );

<强>输出

SELECT xxchr_fnc( 1, 'a' ) FROM DUAL;

XXCHR_FNC(1,'A')   
----------------
a