当前位置: 移动技术网 > IT编程>数据库>Oracle > oracle 触发器 实现出入库

oracle 触发器 实现出入库

2017年12月12日  | 移动技术网IT编程  | 我要评论
用语言实现
好处:
1、可以减少对数据库的访问。
2、可移植性好。
坏处:
1、操作起来考虑的东西较多,修改一处就要修改别一处。也就是说是相互关联的。如果少改了某一处,很可能使数据不一致。
用触发器实现
好处:
1、可以使程序员从复杂的相互关联中解放出来,把精力放在复杂的业务上。
坏处:
1、可移植性差。
下面我就用一个例子实现一个简单的出入库。因为是例子表中所用到的字段很少。这里的例子只做为抛砖引玉。
数据表为入库金额表(以下简称入库表)income,出库金额表(以下简称出库表)outlay,余额表balance
复制代码 代码如下:

income{
id number;
pay_amount number;(入库金额字段)
}
outlay{
id number;
outlay_amount number;(出库金额字段)
}
balance
{
id number;
balance number;(余额字段)
}

下面分别在入库和出库表中建立触发器
入库表(income):
复制代码 代码如下:

create trigger "aa"."tri_add" after
insert
or delete on "income" for each row begin
if deleting then
update balance set balance = nvl(balance,0) - :old.pay_amount;
elsif updating then
update balance set balance = nvl(balance,0) - :old.pay_amount + :new.pay_amount;
else
update balance set balance = nvl(balance,0) + :new.pay_amount;
end if;
end;

出库表(outlay):
复制代码 代码如下:

create trigger "aa"."tri_cut" after
insert
or delete
or update on "outlay" for each row begin
if deleting then
update balance set balance = nvl(balance,0) + :old.outlay_amount;
elsif updating then
update balance set balance = nvl(balance,0) + :old.outlay_amount - :new.outlay_amount;
else
update balance set balance = nvl(balance,0) - :new.outlay_amount;
end if;
end;

下面我解释一下
oracle触发器,触发事件分为插入,删除,更新列三种事件,分别对应inserting /deleting/updating关键字
可以用if语句分别实现
复制代码 代码如下:

if inserting then
-----
elsif updating then
-----
elsif deleting then
------
end if;

nvl(eexpression1, eexpression2)
如果 eexpression1 的计算结果为 null 值,则 nvl( ) 返回 eexpression2。
如果 eexpression1 的计算结果不是 null 值,则返回 eexpression1。eexpression1 和 eexpression2 可以是任意一种数据类型。
如果 eexpression1 与 eexpression2 的结果皆为 null 值,则 nvl( ) 返回 .null.。
这里插入和删除就不说了。主要是更新操作,更新操作要注意的是更新应该是先减去旧值,在加上新值。
以上就是触发器例子的实现。文章写的不好请大家谅解。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网