PL/SQL 触发器
触发器:触发器是一种特殊的存储过程,他与数据表紧密联系,用于保护表中的数据,当定义了特定类型触发器的基表执行插入、修改或删除表中的数据的操作时,将自动触发触发器中定义的操作,以实现数据的一致性和完整性
触事件发:insert delete update
触发时间: before after instead of
触发变量: old new
针对每一行: for each row
展示错误: show error
先创建一个表:
create table stemp(
ID number(10) primary key,
sname varchar2(20)
);
在插入一条数据的时候 触动 触发器
create or replace trigger tri_insert_stemp
after insert on stemp
begin
dbms_output.put_line('插入了新的数据');
end;
在输出的时候 触动 触发器
create or replace trigger tri_delete_stemp
before delete on stemp
for each row
begin
dbms_output.put_line('删除了数据 id='||:old.id||',sname='||:old.sname);
end;
日志 触发器
create table stempLog(
uname varchar2(30),
ddate date
);
create or replace trigger tri_insert_log
after delete on stemp
begin
insert into stempLog values(user,sysdate);
end;
例题:1.要求:把蔬菜改为有机蔬菜,把青菜改为芹菜(用触发器)
create table ptype(
pid number(8),
pname varchar2(30)
);
insert into ptype values(1,'水果');
insert into ptype values(2,'蔬菜');
create table goods(
gid number(8),
gname varchar2(30),
pid number(8)
);
insert into goods values(1,'芒果',1);
insert into goods values(2,'苹果',1);
insert into goods values(3,'香蕉',1);
insert into goods values(4,'萝卜',2);
insert into goods values(5,'青菜',2);
insert into goods values(6,'菠菜',2);
create view v_goods as
select goods.*,ptype.pname from goods inner join ptype on goods.pid=ptype.pid;
create or replace trigger tri_updateGoods
instead of update on v_goods
for each row
begin
update goods set gname=:new.gname where gid=:old.gid;
update ptype set pname=:new.pname where pid=:old.pid;
end;
来源:https://www.cnblogs.com/mumuda/p/6488802.html