替代触发器
替代触发器的意义在于:如果触发了触发器,则原先的DML操作不再进行,而是执行触发器中的操作。
替代触发器最常见的应用是在最view的操作时。由于不能对view直接进行操作,所以可以用替代触发器来替代。
1、创建一个简单的视图:
create
view
v_test
as
select
t11.a a1,t11.b b1,t22.a a2,t22.b b2
from
t11 ,t22
where
t11.a = t22.a;
2、创建替代触发器
create
or
replace
trigger
view_trigger
instead
of --等同于after
update
on
v_test
for
each
row
begin
update
t11
set
b=:new.b1
where
a=:new.a1;
end
;
注:具体逻辑不是很正确,只为举例方便。
3、不能修改的view类别:
* 含有表连接
* 有集合运算符(union、minus、intersect等)
* 含有集合函数(sum、count等)
* group by connect by start with字句
* 包含distinct运算符
系统事件触发器
1、系统事件触发器包括:
* 数据库的启动(STARTUP)
* 数据库的关闭(SHUTDOWN)
* 数据库服务器出错(SERVERERROR)
注:STARTUP和SERVERERROR只能使用BEFORE类型,只有SHUTDOWN才能用AFTER
2、创建语法:
CREATE OR REPALCE TRIGGER trigger_name
{ BEFORE | AFTER }
{ DATABASE _EVENT_LIST }
ON [ DATABASE | SCHEMA ]
trigger body;
注:SERVERERROR可以与SCHEMA关联,表示在该模式上发生错误时才触发。
3、举例:
create
or
replace
teigger dbstart_trigger
after
startup
on
database
begin
insert
into
t1_log
values
(
sysdate
);
end
;
用户事件触发器
1、包括以下几类:
* CREATE
* ALTER
* DROP
* ANALYZE
* ASSOCIATE STATISTICS
* DISASSOCIATE STATISTICS
* AUDIT
* NOTAUDIT
* COMMENT
* GRANT
* REVOKE
* RENAME
* TRUNCATE
* LOGON --只能用AFTER
* LOGOFF --只能用BEFORE
2、举例:
create
or
replace
teigger logon_trigger
after
logon
on
schema --若用on database则任何登陆均会触发
begin
insert
into
t1_log
values
(user,
sysdate
);
end
;
ALTER语句
1、重新编译
ALTER TRIGGER [schema.] trigger_name COMPILE;
作用:如果触发器调用了函数或过程,当函数或过程被删除或修改后,触发器被标记为INVALID,必须重新编译。
2、启用/禁用触发器
ALTER TRIGGER [schema.] trigger_name DISABLE | ENABLE;
作用:DBA要插入大量数据时,确定数据的正确性,禁用触发器后可节省大量时间。
3、启用/禁用某个表的所有触发器
ALTER TABLE table_name DISABLE | ENABLE ALL TRIGGERS; --注意S
触发器数据字典
使用USER_TRIGGERS、ALL_TRIGGERS、DBA_TRIGGERS查看触发器信息
SQL
>
desc
user_triggers
Name
Type
Nullable
Default
Comments
----------------- -------------- -------- ------- ---------------------------------------------------------------------------
TRIGGER_NAME
VARCHAR2
(
30
) Y
Name
of
the
trigger
TRIGGER_TYPE
VARCHAR2
(
16
) Y
Type
of
the
trigger
(
when
it fires) -
BEFORE
/
AFTER
and
STATEMENT
/
ROW
TRIGGERING_EVENT
VARCHAR2
(
227
) Y
Statement
that will fire
the
trigger
-
INSERT
,
UPDATE
and
/
or
DELETE
TABLE_OWNER
VARCHAR2
(
30
) Y Owner
of
the
table
that this
trigger
is
associated
with
BASE_OBJECT_TYPE
VARCHAR2
(
16
) Y
TABLE_NAME
VARCHAR2
(
30
) Y
Name
of
the
table
that this
trigger
is
associated
with
COLUMN_NAME
VARCHAR2
(
4000
) Y
The
name
of
the
column
on
which
the
trigger
is
defined over
REFERENCING_NAMES
VARCHAR2
(
128
) Y Names used
for
referencing
to
OLD
,
NEW
and
PARENT
values
within
the
trigger
WHEN_CLAUSE
VARCHAR2
(
4000
) Y
WHEN
clause must evaluate
to
true
in
order
for
triggering
body
to
execute
STATUS
VARCHAR2
(
8
) Y
If
DISABLED
then
trigger
will
not
fire
DESCRIPTION
VARCHAR2
(
4000
) Y
Trigger
description
, useful
for
re-creating
trigger
creation
statement
ACTION_TYPE
VARCHAR2
(
11
) Y
TRIGGER_BODY
LONG
Y Action taken
by
this
trigger
when
it fires