user3919013
user3919013

Reputation: 11

query all tables in Oracle

I have this plsql code that will give me all tables in the database with name CUSTOMERS. Now I am struck how to insert another loop in to this. I want to get the output from this code and pass it on to next loop where I want to query something like, select count(*) from Schema.customers; for each schema.

DECLARE
    --c_id customers.id%type;
    c_name all_tables.table_name%type;
    c_tabs all_tables.owner%type;
    CURSOR c_tables is
      SELECT table_name, owner FROM all_tables where table_name='CUSTOMERS';
        BEGIN
        OPEN c_tables;
        LOOP
        FETCH c_tables into c_name, c_tabs;
        dbms_output.put_line(c_tabs || '.' || c_name );
        EXIT WHEN c_tables%notfound;
        END LOOP;
        CLOSE c_tables;
    END;
    /

------- Sample output of my code: ------------

UMICH2.CUSTOMERS
TRINITYDC.CUSTOMERS
BUFFALO.CUSTOMERS
SNOW.CUSTOMERS
PULASKITECH.CUSTOMERS
RARITANVAL.CUSTOMERS
STMARYSCA.CUSTOMERS

Upvotes: 0

Views: 209

Answers (2)

DrabJay
DrabJay

Reputation: 3099

You can get the same result in a single SQL statement

SELECT table_name
      ,to_number
         (extractvalue
            (xmltype
               (dbms_xmlgen.getxml
                  ('SELECT count(*) c FROM ' || owner || '.' || table_name)
               )
            ,'/ROWSET/ROW/C'
            )
         ) Count
  FROM all_tables
 WHERE table_name = 'CUSTOMERS'

Upvotes: 1

Matheus Segalotto
Matheus Segalotto

Reputation: 49

This way is one possibility that you can do that.

DECLARE
  --c_id customers.id%type;
  c_name  all_tables.table_name%TYPE;
  c_tabs  all_tables.owner%TYPE;

  v_value PLS_INTEGER;


  CURSOR c_tables  IS
    SELECT table_name
      FROM all_tables
     WHERE table_name = 'CUSTOMERS';

  CURSOR c_owner  IS
    SELECT DISTINCT owner
      FROM all_tables
     WHERE table_name = 'CUSTOMERS';
BEGIN
  OPEN c_tables;

  LOOP
    FETCH c_tables INTO c_name;

    OPEN c_owner;

    LOOP
      FETCH c_owner INTO c_tabs;

      BEGIN
        EXECUTE IMMEDIATE 'SELECT COUNT(1) FROM ' || c_tabs || '.' || c_name INTO v_value;
      EXCEPTION
        WHEN other THEN
          NULL;
      END;

      DBMS_OUTPUT.put_line ( v_value );
      EXIT WHEN c_owner%NOTFOUND;
    END LOOP;

    CLOSE c_owner;

    DBMS_OUTPUT.put_line ( c_tabs || '.' || c_name );
    EXIT WHEN c_tables%NOTFOUND;
  END LOOP;

  CLOSE c_tables;
END;

Any question just let me know.

Thanks.

Upvotes: 0

Related Questions