Search code examples
sqloracleoracle11gcursorprocedure

Oracle procedure cursor loop errors


Can you tell me what is wrong with this procedure that I'm trying to create?

CREATE OR REPLACE PROCEDURE create_audit_tables (table_owner VARCHAR2)
IS
CURSOR c_tables (
  table_owner VARCHAR2)
IS
SELECT ot.owner AS owner, ot.table_name AS table_name
    FROM all_tables ot
   WHERE     ot.owner = table_owner
         AND ot.table_name NOT LIKE 'AUDIT_%'
         AND ot.table_name <> 'EXAUDIT'
         AND NOT EXISTS
                (SELECT 1
                   FROM EXAUDIT efa
                  WHERE ot.table_name = efa.tname)
         AND NOT EXISTS
                    (SELECT 1
                       FROM all_tables at
                      WHERE at.table_name = 'AUDIT_'||ot.table_name);
v_sql     VARCHAR2 (8000);
v_count   NUMBER := 0;
v_aud     VARCHAR2 (30);
BEGIN

FOR r_table IN c_tables (table_owner)
LOOP
  BEGIN
     v_aud := 'AUDIT_'||r_table.table_name;
     v_sql :=
           'create table '
        || v_aud
        || ' as select * from '
        || r_table.owner
        || '.'
        || r_table.table_name
        || ' where 1 = 1';

     DBMS_OUTPUT.put_line ('Info: ' || v_sql);

     EXECUTE IMMEDIATE v_sql;

     v_sql :=
           'alter table '
        || v_aud
        || ' add ( AUDIT_ACTION char(1), AUDIT_BY varchar2(50), AUDIT_AT TIMESTAMP)';

     EXECUTE IMMEDIATE v_sql;

     v_count := c_tables%ROWCOUNT;
  EXCEPTION
     WHEN OTHERS
     THEN
        DBMS_OUTPUT.put_line (
              'Failed to create table '
           || v_aud
           || ' due to '
           || SQLERRM);
  END;
END LOOP;

IF v_count = 0
THEN
  DBMS_OUTPUT.put_line ('No audit tables created');
ELSE
  DBMS_OUTPUT.put_line (v_count || ' audit tables created.');
END IF;
END;
/

I checked it with show errors function and it gave me this:

LINE/COL ERROR
-------- --------------------------------------------
6/1      PL/SQL: SQL Statement ignored
16/3     PL/SQL: ORA-00906: missing left parenthesis

Perhaps the problem is quite simple, but I can't see it, so please help me if you can


Solution

  • I can compile procedure without problems after creating table

    create table EXAUDIT (tname varchar2(100));
    

    Check status of procedure:

    select status from user_objects where lower(object_name) = 'create_audit_tables';