create sequence seq_userInfo_usid start with 1001;
create or replace triggle tri_userInfo_usid --创建或替换触发器tri_userInfo_usid
before insert on userInfo --在向userInfo表中添加 记录之前的触发
for each row --没影响一行出发一次
begin --触发之后执行下面的语句
select seq_userInfo_usid.nextval into :new.usid from dual; --:new新值 :old老值
end;
案列
--日志 触发器讲解
--查看所有触发器
select * from user_triggers;
--禁用触发器
alert trigger tri_log_uname(触发器名字) disable;
--激活触发器
alert trigger tri_log_uname(触发器名字) enble;
--重新编译
alert trigger tri_log_uname complie;
--禁用某个表上的触发器
alert table <table_name> diable all triggers;
create table log(
uname varchar2(20),
action varchar2(10),
acttime date
);
--从U001开始,以递增的形式对uname进行命名
create sequence seq_log_uname start with 1001;
create or replace trigger tri_log_uname
before insert on log
for each row
begin
select 'U'||substr(seq_log_uname.nextval,1) into :new.uname from dual;
end;
insert into log values(1,'yc',sysdate);
select * from log;
create or replace trigger tri_log
after insert or update or delete on dept
for each row --for each 行级触发,执行语句没影响一行出发一次,默认是语句级触发,没执行一条语句触发一次,无论该语句影响多少行,
begin
if inserting then
insert into log values(user,'insert',sysdate);
elsif updating then
insert into log values(user,'update',sysdate);
elsif deleting then
insert into log values(user,'delete',sysdate);
end if;
end;
select * from dept;
insert into dept values(80,'技术部','湖南衡阳');
select * from log;
--更改dept和emp中的deptno的值(涉及主外键)
create or replace trigger tri_dept
before update on dept
for each row
begin
update emp set deptno=:new.deptno where deptno=:old.deptno;
end;
update dept set deptno=88 where deptno=20;
select * from dual;
select * from dept;
select * from emp;
create or replace trigger tri_emp
before update of sal on emp --当修改emp表中的sal列在值时
for each row
when(new.sal<=old.sal)
begin
select 3000 into :new.sal from dual;
end;
select * from emp;
update emp set sal=4000 where empno=7369;