miercuri, 6 ianuarie 2016

Create incrementing triggers for all the PKs from all the tables of a schema

This is the procedure:

CREATE OR REPLACE PROCEDURE create_pk_triggers (table_owner VARCHAR2)
IS
   CURSOR c_tables (
      table_owner VARCHAR2)
   IS

        select * FROM ALL_CONS_COLUMNS
                WHERE
                    CONSTRAINT_NAME IN ( SELECT CONSTRAINT_NAME FROM ALL_CONSTRAINTS where CONSTRAINT_TYPE = 'P') and
                    lower(owner)=lower(table_owner);

   v_sql     VARCHAR2 (8000);
   v_count   NUMBER := 0;
   v_aud     VARCHAR2 (30);
   v_col     varchar2(50);

  
BEGIN
   FOR r_table IN c_tables (table_owner)
   LOOP
      BEGIN
         v_aud := r_table.table_name;
         v_col := r_table.column_name;
         v_sql :=
               'CREATE OR REPLACE TRIGGER inspk_'
            ||substr(v_aud,1,24)
            || CHR (10)
            ||' before insert on '
            ||table_owner
            ||'.'
            || v_aud
            || CHR (10)
            || ' for each row begin '
            || CHR (10)
            || ' if inserting and :new.'
            || v_col
            || ' is null then '
            || CHR (10)
            || ':new.'
            || v_col
            || ' :='
            || ' call4prop_seq.nextval;'
            || CHR (10)
            || '  end if;'
            || CHR (10)
            || '   end;'
            ;

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

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


And here is how to run the procedure, using as a parameter the name of the schema owner (the capitals rule will not apply):

 
begin
 create_pk_triggers('username');
end;
/

Niciun comentariu:

Trimiteți un comentariu