【问题标题】:Identifying nonempty tables in Oracle SQL Developer在 Oracle SQL Developer 中识别非空表
【发布时间】:2021-08-11 15:56:29
【问题描述】:

我正在尝试在包含数百个表的数据库中查找数据。我正在为所有表逐一检查它们并编写简单的select * 查询。它需要永远!我想知道是否有一种方法可以编写查询来过滤数据库中至少有 1 行的所有表。这可能吗?

【问题讨论】:

  • 您打算如何处理至少有一行的表格列表?这里真正的最终目标是什么?

标签: oracle oracle-sqldeveloper


【解决方案1】:
with 
function f(tabname in varchar2) return int as
  res int;
begin
  execute immediate 'select count(*) cnt from "'||tabname||'" where rownum=1' into res;
  return res;
end;
select table_name, f(table_name) chk
from user_tables;

结果:

TABLE_NAME                            CHK
------------------------------ ----------
STRVALS                                 1
MY_EMP                                  1
TBL_3                                   1
TBL_1                                   1
TLOCK                                   1
DATES                                   1
B                                       1
A                                       1
C                                       1
T0                                      0

select count(*) from dual where exists(...):

with 
function f(tabname in varchar2) return int as
  res int;
begin
  execute immediate 'select count(*) cnt from dual where exists(select 1 from "'||tabname||'")' into res;
  return res;
end;
select table_name, f(table_name) chk
from user_tables

【讨论】:

    【解决方案2】:

    如果您的数据库得到适当维护,您将获得优化器统计信息。

    如果您的表格缺少统计信息,您可以这样收集它们:

    BEGIN
            dbms_stats.gather_schema_stats(
                                          ownname => 'HR'
                                        , estimate_percent => X -- note the higher you go here, the more work will be done
            );
        END;
    

    然后,查询统计信息,而不是您的表格。

    SELECT num_rows
         , table_name
      FROM sys.dba_all_tables
     WHERE owner      = 'HR'
    

    然后,您可以根据您的统计数据的准确程度快速查看哪些表是空的。

    如果您使用动态 SQL 在架构中的每个表上运行 SELECT COUNT(*),并且您的架构和/或表非常庞大,那么您将获得非常糟糕的体验,并可能导致您的性能问题数据库。

    【讨论】:

    • 如果只计算所有表中的行数会让 DBA 感到不安,那么收集关于它们的统计信息(这将多次读取它们、进行大量排序并可能导致执行计划发生变化)肯定会很烦人当您只想知道它们是否至少有一行时。
    • 如果你没有统计数据,优化器一开始就会有可怕的计划,一个
    • @AndrewSayer 正如您正确指出的那样,我已经用更多细微差别修改了我的答案
    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2011-08-10
    • 2021-09-11
    • 2014-08-25
    • 1970-01-01
    相关资源
    最近更新 更多