我有以下函数来计算表的内容但是当我传递任何参数时它会抛出:
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'));
答案 0 :(得分:3)
你不能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'));
答案 1 :(得分:0)
您无法绑定表名或列名。您只能绑定变量。
在您的情况下,您只需要 EXECUTE IMMEDIATE 动态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>