【发布时间】:2021-08-11 15:56:29
【问题描述】:
我正在尝试在包含数百个表的数据库中查找数据。我正在为所有表逐一检查它们并编写简单的select * 查询。它需要永远!我想知道是否有一种方法可以编写查询来过滤数据库中至少有 1 行的所有表。这可能吗?
【问题讨论】:
-
您打算如何处理至少有一行的表格列表?这里真正的最终目标是什么?
标签: oracle oracle-sqldeveloper
我正在尝试在包含数百个表的数据库中查找数据。我正在为所有表逐一检查它们并编写简单的select * 查询。它需要永远!我想知道是否有一种方法可以编写查询来过滤数据库中至少有 1 行的所有表。这可能吗?
【问题讨论】:
标签: oracle oracle-sqldeveloper
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
【讨论】:
如果您的数据库得到适当维护,您将获得优化器统计信息。
如果您的表格缺少统计信息,您可以这样收集它们:
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(*),并且您的架构和/或表非常庞大,那么您将获得非常糟糕的体验,并可能导致您的性能问题数据库。
【讨论】: