执行立即绑定变量

Execute Immediate bind variable

我有以下函数计算 table 的内容,但是当我传递任何参数时它抛出:

EXEC DBMS_OUTPUT.PUT_LINE(get_size('employees'))
Error report -
ORA-00903: invalid table name
ORA-06512: at "HR.GET_SIZE", line 5
ORA-06512: at line 1
00903. 00000 -  "invalid table name"

函数

CREATE OR REPLACE FUNCTION get_size(v_table_name IN VARCHAR2) 
   RETURN NUMBER IS total_size NUMBER(16);
   plsql_statement VARCHAR2(500) := 'SELECT COUNT(*) FROM  :param';
BEGIN
    EXECUTE IMMEDIATE plsql_statement INTO total_size USING v_table_name;
    RETURN(total_size); 
END;
/


EXEC DBMS_OUTPUT.PUT_LINE(get_size('employees'));

你不能bind table names,它需要构建。

CREATE OR REPLACE FUNCTION get_size(v_table_name IN VARCHAR2) 
   RETURN NUMBER IS total_size NUMBER(16);
   plsql_statement VARCHAR2(500)
BEGIN
    plsql_statement := 'SELECT COUNT(*) FROM  ' || v_table_name;
    EXECUTE IMMEDIATE plsql_statement INTO total_size;
    RETURN(total_size); 
END;
/


EXEC DBMS_OUTPUT.PUT_LINE(get_size('employees'));

您不能绑定 table 名称或列名称。您只能绑定变量。

在你的情况下,你只需要立即执行动态SQL。

SQL> CREATE OR REPLACE FUNCTION get_size(v_table_name IN VARCHAR2)
  2     RETURN NUMBER IS total_size NUMBER(16);
  3     plsql_statement VARCHAR2(500);
  4  BEGIN
  5      plsql_statement := 'SELECT COUNT(*) FROM  ' || v_table_name;
  6      EXECUTE IMMEDIATE plsql_statement INTO total_size;
  7      RETURN(total_size);
  8  END;
  9  /

Function created.

SQL>
SQL>
SQL> EXEC DBMS_OUTPUT.PUT_LINE(get_size('EMP'));
14

PL/SQL procedure successfully completed.

SQL>