PL/SQL example to create a list of tables and execute a dynamic SQL on each of the tables

This PL/SQL code identifies a list of tables that exist in a schema. For each table, it issues a count(*) dynamically.

set serveroutput on;
spool get_all_tables
 
declare
    dyn_sql varchar(300);
    count_x number (10);
    temp_tab_name char(40);
begin
for t in(select owner, substr(table_name,01,40) as table_name from dba_tables where owner = '' order by table_name)
  loop
     temp_tab_name := t.table_name;
     dyn_sql := 'select count(*) from ' || t.owner || '.' || t.table_name;
     execute immediate dyn_sql into count_x;
     dbms_output.put_line(t.owner || ' ' || temp_tab_name || ' = ' || count_x || ' rows');
  end loop;
end;
/
spool off

Author: Dean Capps

Database consultant at Amazon Web Services.