oracle 触发器 实现出入库 |
本文标签:oracle,触发器,出入库 用语言实现 好处: 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. 。 这里插入和删除就不说了 。主要是更新操作,更新操作要注意的是更新应该是先减去旧值,在加上新值 。 以上就是触发器例子的实现 。文章写的不好请大家谅解 。 |