create trigger mytrigger on table1 instead of insert as
insert into table1
select a,b+a,c+a
from insertedcreate trigger mytrigger on table1 instead of update as
delete table1 where 主键 in select (主键)
insert into table1
select a,b+a,c+a
from inserted
删除就不用了吧。
insert into table1
select a,b+a,c+a
from insertedcreate trigger mytrigger on table1 instead of update as
delete table1 where 主键 in select (主键)
insert into table1
select a,b+a,c+a
from inserted
删除就不用了吧。
update table1
set b = table1.b+tbl2.b,
c = table1.c+tbl2.c
from
(select a,sum(b) as b,sum(c) as c
from
(select a,b,c from inserted
union all
select a,-b,-c from deleted) as tbl1
group by a
) as tbl2
where table1.a = tbl2.a
我用了你的触发器
从企业管理器中,我添加几条记录的时候,发现我的自增字段a的值一直是0
刷新一看一条记录都没有增加
我用了你的触发器
从企业管理器中,我添加几条记录的时候,发现我的自增字段a的值一直是0
刷新一看一条记录都没有增加啊!不信你试试,创建一个标,就 a b c三个整形字段,使用你自己创建的触发器
update table1
set b =(select top 1 b from table1 order by a desc)+b,c =(select top 1 c from table1 order by a desc)+c
where a = 1
Try It,;)
for insert
as
update A set A.c=A.c+isnull(B.c,0),A.b=A.b+isnull(B.b,0) from table1 A,(select sum(b) as b,sum(c) as c from inserted where a<>1 ) B
where A.a = 1
用子查询主要考虑到多条记录插入。
insert table1 select 1,2,3
select * from table1a b c
----------- ----------- -----------
1 2 3insert table1 select 2,2,3
select * from table1
a b c
----------- ----------- -----------
1 4 6
2 2 3
insert table1 select 3,2,3
select * from table1
a b c
----------- ----------- -----------
1 6 9
2 2 3
3 2 3
这个问题我最终采用了j9988兄的方法,
我对这句还是不明白
(select sum(b) as b,sum(c) as c from inserted where a<>1 ) B
insert只能插入一行,我觉得不没有必要加入 where a<>1 这句,不知道我理解得对不对我这还有一个问题,如下单位号 月份 本月产量 累计产量
------------------------------------
1 1 100 1234
1 2 200 1434我想用触发器实现累计产量的自动完成,因为我发现实际上是累计产量是可以算出来的 ,也就是说可以不要这个字段,但是查询的时候要一系列的第归查询,比如要查6月份的累计量,就要查5月、4月、3月.....的累计量但是我发现者有个缺陷:比如现在把7月份的数据都输入了,才发现3月份的数据有问题,也导致他月份的数据也是错误的,仅修改3月份的数据是不行的,请问有没有更好的方法解决这个问题?
不对! 你往一个空表插入a=1的数据时会出错.如果数据量不是相当大,不要累计产量
for insert
as
update A set A.c=A.b+A.a
-- +isnull(B.c,0),A.b=A.b+isnull(B.b,0)
from table2 A,(select * from inserted ) B
where A.a = B.a