从来没接触过oracle,领导要求写个触发器,求大侠帮忙~
要求是这样的:
有一个表是存放消费明细的,每个ID有N条消费明细,现在领导要求加一列余额,写入消费明细后,用触发器更新余额,余额=上一次消费余额+本次消费金额
PS:上一次消费余额为某ID时间最晚的一条消费记录中的余额
求该触发器,感激不尽。
------解决思路----------------------
CREATE TABLE TAB_CONSUME
(
ID INT,
PARID INT,
CON_NAME VARCHAR2(100),
CON_DATE DATE,
CON_MONDY NUMBER(5,2),
BALANCE NUMBER(5,2)
);
---新添加的列BALANCE 余额
---添加数据用于测试
insert into TAB_CONSUME values(1,1,'买好吃的',sysdate,100,100.71);
insert into TAB_CONSUME values(2,1,'买茶叶',sysdate,1,101.71);
insert into TAB_CONSUME values(3,1,'买书本',sysdate,500,601.71);
COMMIT;
---创建触发器
CREATE OR REPLACE TRIGGER TR_UPDATE_BALANCE
AFTER INSERT ON TAB_CONSUME
DECLARE
V_PARID INT;
V_ID INT;
V_CON_MONDY NUMBER(5,2);
V_BALANCE NUMBER(5,2);
BEGIN
SELECT ID,PARID,CON_MONDY INTO V_ID,V_PARID,V_CON_MONDY FROM TAB_CONSUME WHERE ID=(SELECT MAX(ID) FROM TAB_CONSUME);
SELECT BALANCE INTO V_BALANCE FROM TAB_CONSUME WHERE ID=(SELECT MAX(ID) FROM TAB_CONSUME WHERE PARID=V_PARID AND BALANCE>0);
UPDATE TAB_CONSUME SET BALANCE=V_BALANCE+V_CON_MONDY WHERE ID=V_ID;
END;
/
---开始测试
insert into TAB_CONSUME values(4,1,'买书本',sysdate,1,0);