Execute For Each Table in PLSQL

吃可爱长大的小学妹 提交于 2021-02-07 14:26:08

问题


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;
/

回答1:


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.



来源:https://stackoverflow.com/questions/5142696/execute-for-each-table-in-plsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!