将表名作为 plsql 参数传入

passing in table name as plsql parameter(将表名作为 plsql 参数传入)
本文介绍了将表名作为 plsql 参数传入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数来返回名称作为变量传入的表的行数.这是我的代码:

I want to write a function to return the row count of a table whose name is passed in as a variable. Here's my code:

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;

我收到此错误:

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

我知道 tbl_nm 被解释为一个值而不是一个引用,我不知道如何逃避它.

I understand that tbl_nm is being interpreted as a value and not a reference and I'm not sure how to escape that.

推荐答案

可以使用动态 SQL:

You can use dynamic 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;

还有一种获取行数的间接方法(使用系统视图):

There is also an indirect way to get number of rows (using system views):

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;

第二种方法仅当您在调用此函数之前收集了表的统计信息时才有效.

The second way works only if you had gathered statistics on table before invoking this function.

这篇关于将表名作为 plsql 参数传入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

SQL to Generate Periodic Snapshots from Transactions Table(用于从事务表生成定期快照的SQL)
MyBatis support for multiple databases(MyBatis支持多个数据库)
Oracle 12c SQL: Missing column Headers in result(Oracle 12c SQL:结果中缺少列标题)
SQL query to find the number of customers who shopped for 3 consecutive days in month of January 2020(查询2020年1月连续购物3天的客户数量)
How to get top 10 data weekly (This week, Previous week, Last month, 2 months ago, 3 month ago)(如何每周获取前十大数据(本周、前一周、上个月、2个月前、3个月前))
Select the latest record for an Id per day - Oracle pl sql(选择每天ID的最新记录-Oracle pl SQL)