【问题标题】:passing in table name as plsql parameter将表名作为 plsql 参数传入
【发布时间】:2015-02-19 22:37:54
【问题描述】:

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

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 被解释为一个值而不是一个引用,我不知道如何逃避它。

【问题讨论】:

    标签: oracle plsql oracle11g


    【解决方案1】:

    您可以使用动态 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;
    

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

    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;
    

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

    【讨论】:

    • @SylvainLeroux - Oracle 提供了 DBMS_ASSERT 包,因此我们可以轻松处理 SQL 注入攻击。第二种方法的问题在于它对统计数据的依赖意味着返回的值可能不准确或具有误导性,除非我们在运行计数之前立即收集表上的统计数据,这 (a) 耗时 (b) 可能会破坏持续性能.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2020-04-16
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多