ORA-00903, ORA-06512, while counting count of rows of all user tables(dynamic sql)

816 Views Asked by At

I want to count count of rows of every user table, but by means of dynamic sql, and there are such errors. ORA-00903: invalid table name ORA-06512: at line 19 SQL2.sql 20 2

DECLARE 
      TYPE cursor_type IS REF CURSOR;
      curs1 cursor_type;
      ammount NUMBER;
      stmnt1 VARCHAR2(200);
      stmnt2 VARCHAR2(200);
      T_NAME VARCHAR2(100);
    BEGIN 
      stmnt1 := 'SELECT TABLE_NAME FROM USER_TABLES';
      stmnt2 := 'SELECT COUNT(*) FROM :1';
      IF curs1%ISOPEN THEN
        CLOSE curs1;
      END IF;
      OPEN curs1 FOR stmnt1;

      LOOP
        FETCH curs1 INTO T_NAME;
        EXIT WHEN curs1%NOTFOUND; 
        EXECUTE IMMEDIATE stmnt2 INTO ammount USING T_NAME;
        DBMS_OUTPUT.PUT_LINE('Table ' || T_NAME || ' - ' || ammount || ' rows');
      END LOOP;
      CLOSE curs1;
    END;
1

There are 1 best solutions below

2
Frank Schmitt On

You cannot provide the table name as a bind variable. You have to concatenate it into your statement instead:

DECLARE
  TYPE cursor_type IS REF CURSOR;
  curs1   cursor_type;
  amount NUMBER;
  stmnt1  VARCHAR2(200);
  stmnt2  VARCHAR2(200);
  T_NAME  VARCHAR2(100);
BEGIN
  stmnt1 := 'SELECT TABLE_NAME FROM USER_TABLES';
  stmnt2 := 'SELECT COUNT(*) FROM ';
  IF curs1%ISOPEN THEN
    CLOSE curs1;
  END IF;
  OPEN curs1 FOR stmnt1;

  LOOP
    FETCH curs1
      INTO T_NAME;
    EXIT WHEN curs1%NOTFOUND;
    EXECUTE IMMEDIATE stmnt2 || t_name
      INTO amount;      
    DBMS_OUTPUT.PUT_LINE('Table ' || T_NAME || ' - ' || amount || ' rows');
  END LOOP;
  CLOSE curs1;
END;

UPDATE A much simpler (and IMHO more readable) version, using a cursor for loop:

declare
  amount number;
begin
  for cur in (select table_name from user_tables) 
  loop
    execute immediate 'SELECT COUNT(*) FROM ' || cur.table_name
      into amount;
    DBMS_OUTPUT.PUT_LINE('Table ' || cur.table_name || ' - ' || amount ||
                         ' rows');
  end loop;
end;