Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute For Each Table in PLSQL

I want to the the number of records in all tables that match a specific name criteria. Here is the SQL I built

Declare SQLStatement VARCHAR (8000) :='';
BEGIN
  SELECT 'SELECT COUNT (*) FROM ' || Table_Name || ';'
  INTO SQLStatement
  FROM All_Tables
  WHERE 1=1
    AND UPPER (Table_Name) LIKE UPPER ('MSRS%');

  IF SQLStatement <> '' THEN
    EXECUTE IMMEDIATE SQLStatement;
  END IF;
END;
/

But I get the following error:

Error at line 1
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at line 3
Script Terminated on line 1.

How do I modify this so that it runs for all matching tables?

Update:

Based on an answer received, I tried the following but I do not get anything in the DBMS_OUTPUT

declare 
  cnt number;
begin
  for r in (select table_name from all_tables) loop
    dbms_output.put_line('select count(*) from CDR.' || r.table_name);
  end loop;
end;
/
like image 447
Raj More Avatar asked Feb 28 '11 13:02

Raj More


1 Answers

declare 
  cnt number;
begin
  for r in (select owner, table_name from all_tables
             where upper(table_name) like ('%MSRS%')) loop

    execute immediate 'select count(*) from "'
            || r.owner || '"."'
            || r.table_name || '"'
            into cnt;

    dbms_output.put_line(r.owner || '.' || r.table_name || ': ' || cnt);
  end loop;
end;
/

If you're selecting from all_tables you cannot count on having been given the grants necessary to select from the table name. You should therefore check for the ORA-00942: table or view does not exist error thrown.

As to the cause for your error: You get this error because the select statement returns a result set with more than one row (one for each table) and you cannot assign such a result set to a varchar2.

By the way, make sure you enable dbms_output with SET SERVEROUT ON before executing this block.

like image 98
René Nyffenegger Avatar answered Oct 05 '22 07:10

René Nyffenegger