如何从PL / SQL中的表列表中查找空表?

时间:2018-06-08 08:52:24

标签: oracle plsql oracle11g

我有一个表格列表,如table1,table2,.... table35。我需要找到空的。有没有更快的方法呢?我搜索了一些,但所有解决方案都是为了在模式中找到空表。这次我有一个表名列表,想要找到空表。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

从DBA_OBJECTS获取所有表并循环遍历:

DECLARE
    v_cnt          NUMBER;
    v_schemaname   VARCHAR(20) := 'myschema';
BEGIN
    FOR i IN (SELECT DISTINCT OWNER, OBJECT_NAME
                FROM DBA_OBJECTS
               WHERE OBJECT_TYPE = 'TABLE' AND OWNER = v_schemaname)
    LOOP
        BEGIN
            EXECUTE IMMEDIATE
                'select count(*) FROM ' || i.owner || '.' || i.object_name || ' WHERE rownum = 1'
                INTO v_cnt;

            IF v_cnt = 0
            THEN
                DBMS_OUTPUT.put_line (
                    i.owner || '.' || i.object_name || ' IS EMPTY');
            END IF;
        EXCEPTION
            WHEN OTHERS
            THEN
                DBMS_OUTPUT.put_line (
                    i.owner || '.' || i.object_name || ' ERROR: ' || SQLCODE);
        END;
    END LOOP;
END;

答案 1 :(得分:0)

一种选择是循环遍历所有表以及动态SQL。像这样:

SQL> DECLARE
  2     l_list   VARCHAR2 (50) := 'emp,dept';
  3     l_cnt    NUMBER;
  4  BEGIN
  5     FOR cur_t IN (WITH tabs AS (SELECT l_list FROM DUAL)
  6                       SELECT REGEXP_SUBSTR (l_list,
  7                                             '[^,]+',
  8                                             1,
  9                                             LEVEL)
 10                                 table_name
 11                         FROM tabs
 12                   CONNECT BY LEVEL <= REGEXP_COUNT (l_list, ',') + 1)
 13     LOOP
 14        EXECUTE IMMEDIATE 'select count(*) from ' || cur_t.table_name || ' where rownum = 1'
 15           INTO l_cnt;
 16
 17        DBMS_OUTPUT.put_line (
 18           cur_t.table_name || ' contains ' || l_cnt || ' row(s)');
 19     END LOOP;
 20  END;
 21  /
emp contains 14 row(s)
dept contains 4 row(s)

PL/SQL procedure successfully completed.

SQL>

您需要包含显示L_CNT = 0

表格的条件

答案 2 :(得分:0)

我知道的最快捷的方法是收集所有表格的新统计数据:

BEGIN dbms_stats.gather_schema_stats(user); END;
/

然后在数据字典中找到空表:

SELECT table_name 
  FROM user_tables 
 WHERE table_name LIKE 'TABLE%' 
   AND num_rows=0;