Ser*_*rge 3 oracle plsql oracle11g
我想编写一个函数来返回一个表的行计数,该表的名称作为变量传入.这是我的代码:
create or replace function get_table_count (table_name IN varchar2)
return number
is
tbl_nm varchar(100) := table_name;
table_count number;
begin
select count(*)
into table_count
from tbl_nm;
dbms_output.put_line(table_count);
return table_count;
end;
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
FUNCTION GET_TABLE_COUNT compiled
Errors: check compiler log
Error(7,5): PL/SQL: SQL Statement ignored
Error(9,8): PL/SQL: ORA-00942: table or view does not exist
Run Code Online (Sandbox Code Playgroud)
我理解这tbl_nm被解释为一个价值而不是一个参考,我不知道如何逃避这一点.
您可以使用动态SQL:
create or replace function get_table_count (table_name IN varchar2)
return number
is
table_count number;
begin
execute immediate 'select count(*) from ' || table_name into table_count;
dbms_output.put_line(table_count);
return table_count;
end;
Run Code Online (Sandbox Code Playgroud)
还有一种获取行数的间接方法(使用系统视图):
create or replace function get_table_count (table_name IN varchar2)
return number
is
table_count number;
begin
select num_rows
into table_count
from user_tables
where table_name = table_name;
return table_count;
end;
Run Code Online (Sandbox Code Playgroud)
第二种方法只有在调用此函数之前已在表上收集统计信息时才有效.