 |
|
EnterpriseDB: Rules
Oracle Tips by Burleson Consulting
|
A rule
can be thought of as a special type of trigger. In most instances
where it is possible, I would recommend you use a trigger instead of
a rule. The benefit of a rule instead of a trigger is that the rule
can be an INSTEAD of rule which triggers do not support.
A rule
can be an ALSO rule or an INSTEAD rule. An ALSO rule will fire a
set of commands in addition to the executing command while an
INSTEAD rule will fire instead of the executing command.
A
restriction on a select rule is that it can only be an INSTEAD rule
and must consist of a single select. It is a better practice to
create a view instead of a select rule.
There
are six valid commands: NOTHING, NOTIFY, INSERT, UPDATE, DELETE,
SELECT. INSERT, UPDATE, DELETE and SELECT perform as expected.
NOTHING does just that, absolutely nothing. If you have an INSERT
INSTEAD trigger that does NOTHING, you will never be able to add
records to the table. NOTIFY is a database command that pushes a
message on a queue. It works a lot like DBMS_ALERT in Oracle. I
will discuss NOTIFY in detail in the next chapter.
CREATE RULE
CREATE OR REPLACE RULE <rule name>
AS ON SELECT|INSERT|UPDATE|DELETE
TO <table name>
[ WHERE <where clause> ]
DO [ ALSO | INSTEAD ]
{ NOTHING | command(s) }
We can
create a rule on the emp table that will also insert data into the
emp clone table whenever a record is added to emp.
CREATE OR REPLACE emp_insert_audit_rule
AS ON INSERT TO emp
DO ALSO INSERT INTO emp_clone (empno, ename)
VALUES (:new.empno, :new.ename);
ALTER RULE
You
cannot alter a rule. You should recreate it.
GRANT RULE
You
cannot grant to a rule. You would grant to the table that has the
rule.
REVOKE RULE
You
cannot revoke permissions from a rule. You would revoke permissions
from a table that has the rule.
DROP RULE
Drop a
rule:
DROP RULE emp_insert_audit_rule;
This
is an excerpt from the book "EnterpriseDB:
The Definitive Reference" by Rampant TechPress.