Oracle DBA, How To, Error, Cause and Action

How To Make Table READ ONLY for Oracle Prior to 11g

To use before update/delete/insert trigger

CREATE OR REPLACE TRIGGER table_name_readonly 
BEFORE DELETE OR INSERT OR UPDATE ON <schema.table_name>
BEGIN
 RAISE_APPLICATION_ERROR(-20999, 'The table is READ ONLY');
END;
/



Following is to generate scripts for all tables within a schema.

SET PAGESIZE 0
SET LINESIZE 150

SELECT 'CREATE OR REPLACE TRIGGER ' || lower(table_name) || 
  '_readonly ' || chr(10) || 'BEFORE DELETE OR INSERT OR UPDATE ON ' 
  || lower(owner) || '.' || lower(table_name) || chr(10) 
  || 'BEGIN' || chr(10) ||'   RAISE_APPLICATION_ERROR(-20999,' 
  || chr(39) || 'Table : ' 
  || lower(owner) || '.' || lower(table_name) || ' is READ ONLY.' 
  || chr(39) || '); '|| chr(10) || 'END;' || chr(10)|| '/'
  AS "Trigger to make table RO"
FROM DBA_TABLES
WHERE owner = 'SCOTT' -- change to correct user here
/



Following is the example:

SQL> grant dba to testuser identified by test;

Grant succeeded.

SQL> connect testuser/test
Connected.
SQL> create table testtable (col int);

Table created.


SQL> SELECT 'CREATE OR REPLACE TRIGGER ' || lower(table_name) || 
  2    '_readonly ' || chr(10) || 'BEFORE DELETE OR INSERT OR UPDATE ON ' 
  3    || lower(owner) || '.' || lower(table_name) || chr(10) 
  4    || 'BEGIN' || chr(10) ||'   RAISE_APPLICATION_ERROR(-20999,' 
  5    || chr(39) || 'Table : ' 
  6    || lower(owner) || '.' || lower(table_name) || ' is READ ONLY.' 
  7    || chr(39) || '); '|| chr(10) || 'END;' || chr(10)|| '/'
  8    AS "Trigger to make table RO"
  9  FROM DBA_TABLES
 10  WHERE owner = 'TESTUSER' -- change to correct user here
 11  /

Trigger to make table RO
--------------------------------------------------------------------------------
CREATE OR REPLACE TRIGGER testtable_readonly
BEFORE DELETE OR INSERT OR UPDATE ON testuser.testtable
BEGIN
   RAISE_APPLICATION_ERROR(-20999,'Table : testuser.testtable is READ ONLY.');
END;
/


SQL> -- Create trigger based on above result.


SQL> CREATE OR REPLACE TRIGGER testtable_readonly
BEFORE DELETE OR INSERT OR UPDATE ON testuser.testtable
BEGIN
   RAISE_APPLICATION_ERROR(-20999,'Table : testuser.testtable is READ ONLY.');
END;
/  2    3    4    5    6  

Trigger created.


SQL> insert into testtable values(1);
insert into testtable values(1)
            *
ERROR at line 1:
ORA-20999: Table : testuser.testtable is READ ONLY.
ORA-06512: at "TESTUSER.TESTTABLE_READONLY", line 2
ORA-04088: error during execution of trigger 'TESTUSER.TESTTABLE_READONLY'


No comments:

Post a Comment

Thanks for your comment.