mssql触发器,加减问题
方法1:
CREATE TRIGGER ins_trigger
ON kc1
FOR INSERT
AS
if (select count(*) from kc2,
inserted where kc2.k1=inserted.k1) <> 0
begin
update kc2
set kc2.k2=(
select
sum(kc1.k2)
from kc1
where kc2.k1=kc1.k1)
end
else
begin
insert kc2 select k1,k2,k3,k4,k5 from inserted
end
方法2:
CREATE TRIGGER ins_trigger
ON kc1
FOR INSERT
AS
if (select count(*) from kc2,
inserted where kc2.k1=inserted.k1) <> 0
begin
update kc2
set kc2.k2=(
select
sum(inserted.k2)
from inserted
where kc2.k1=inserted.k1)
end
else
begin
insert kc2 select k1,k2,k3,k4,k5 from inserted
end
方法1没有问题,但要是遇到kc1表中有几十万条数据则运行起来服务器负担太大
方法2有问题,执行后,kc2表中只有最后执行的一条数据是有效的,表kc2的其他k2列的数据则为null,请问各位这是怎么回事
------解决方案--------------------方法二
的update改为
update kc2
set k2=k2+(select isnull(sum(k2),0) from inserted where k1=kc2.k1)
where exists(select * from inserted where k1=kc2.k1)
注意加上where 语句,这样kc2的记录就不用全部更新
变为null的原因,因为每列都更新,(select sum()...)中有很多返回null值,值+null会变为null
其实,如果每次添加的记录为一条,可改为
update kc2
set k2=k2+isnerted.k2
from kc2,inserted where kc2.k1=inserted.k1