日期:2014-05-17  浏览次数:20576 次

关于SQL SERVER 2008 R2触发器问题
两张表:A表两列:流水号(主键), 收款金额。B表两列:流水号(外键), 拆分金额。现在B表中加入一触发器,要求是当B表中插入、删除、更新后的结果满足 B表该流水号下的拆分金额之和小于A表中该流水单号下的收款金额。

若不采用触发器是否有其他更简单的方法?谢谢

------解决方案--------------------
create trigger inserttb
on b
INSTEAD OF INSERT 
as
begin

;with c1 as(
select 流水号,sum(拆分金额)as je from inserted group by 流水号
),c2 as(
select 流水号,sum(拆分金额)as je from B t where exists(select 1 from c1 where 流水号=t.流水号)
),c3 as(
select a.流水号,a.je+b.je as je from c1 a inner join c2 b on a.流水号=b.流水号
)
insert into B(流水号,拆分金额)
select i.* from inserted i inner join c3 c on i.流水号=c.流水号
where exists(select 1 from A where 流水号=i.流水号 and 金额<c.je)

end