我创建了两个表deposit
和final_balance
;我想在deposit_amount
表中求deposit
并将结果插入final_balance
表。
我可以使用触发器吗?
CREATE TABLE deposit(cust_id VARCHAR2(10),loan_id VARCHAR2(10),deposit_type VARCHAR2(10),deposit_amount NUMBER(20));
INSERT INTO deposit values ('001CUS1','001LOAN1','Fixed',3500);
INSERT INTO deposit values ('001CUS2','001LOAN2','Fixed',3900);
INSERT INTO deposit values ('001CUS3','001LOAN3','Fixed',7000);
INSERT INTO deposit values ('001CUS4','001LOAN4','Fixed',28000);
INSERT INTO deposit values ('001CUS5','001LOAN5','Fixed',15200);
INSERT INTO deposit values ('001CUS6','001LOAN6','Fixed',2420);
INSERT INTO deposit values ('001CUS7','001LOAN7','Primary',2420);
INSERT INTO deposit values ('002CUS1','002LOAN1','Primary',27000);
INSERT INTO deposit values ('002CUS2','002LOAN2','Primary',20200);
INSERT INTO deposit values ('002CUS3','002LOAN3','Primary',6900);
CREATE TABLE final_balance(
total_deposit NUMBER(20)
);
答案 0 :(得分:0)
如果您需要一次性评估,可以使用:
SQL> insert into final_balance
2 select sum(deposit_amount)
3 from deposit;
1 row created.
如果您需要自我更新结果,视图将是更好的解决方案:
SQL> CREATE VIEW v_final_balance(total_deposit) as
2 select sum(deposit_amount)
3 from deposit;
View created.
一开始,它们都显示相同的结果:
SQL> select * from final_balance;
TOTAL_DEPOSIT
-------------
116540
SQL> select * from v_final_balance;
TOTAL_DEPOSIT
-------------
116540
更新deposit
表格中的数据后,视图将显示更新的总金额,而无需触发器:
SQL> INSERT INTO deposit
2 VALUES (
3 'XX',
4 'YY',
5 'ZZ',
6 1000000000
7 );
1 row created.
SQL> select * from final_balance;
TOTAL_DEPOSIT
-------------
116540
SQL> select * from v_final_balance;
TOTAL_DEPOSIT
-------------
1000116540
您甚至可以使用基于触发器的方法,但它需要插入,更新,删除的触发器,从而产生更复杂的解决方案。如果您对触发器没有特定需求,我相信该视图是最佳解决方案。