Execution for each table in PLSQL

I want the number of records in all tables to meet specific 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 change this so that it runs for all relevant tables?

Update:

Based on the response I received, I tried the following, but received nothing in 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;
/
+5
source share
1 answer
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 choose from all_tables, you cannot count on the grants needed to select from the table name. Therefore, you should check for errors ORA-00942: table or view does not exist.

: , select ( ), varchar2.

, , dbms_output SET SERVEROUT ON.

+9

All Articles