比如有一个表 a
Name Value
a 2
a 3
a 4
b 1
b 2
b 3
有另外一个表 b 部分是由 a的到的
Name AllValue OtherValue
a 10 ewfefasf
b 6 fafdas如何在更新表a 的时候 自动更新表 b了, 用触发器要怎么写了 ,当然b 表OtherValue不能变, 还有在a中添加一条 c 6 的记录
在 b表中也自动增加记录c
给个提示 写个触发器例子,或者提供别的思路也可以
Name Value
a 2
a 3
a 4
b 1
b 2
b 3
有另外一个表 b 部分是由 a的到的
Name AllValue OtherValue
a 10 ewfefasf
b 6 fafdas如何在更新表a 的时候 自动更新表 b了, 用触发器要怎么写了 ,当然b 表OtherValue不能变, 还有在a中添加一条 c 6 的记录
在 b表中也自动增加记录c
给个提示 写个触发器例子,或者提供别的思路也可以
update b set AllValues=(select sum(Value) from a) where name=(select name from inserted)
go
create trigger abc on a for insert,update as
if exists(select 1 from b where name in(select name from a))
update b set AllValues=(select sum(Value) from a) where name=(select name from inserted)
else
insert b select * from inserted
go
after insert,update
as
if update(Value) or update(Name) --判断用户是否在这两个列上进行了更新操作
update b set AllValue=(select sum(Value) from a) where name=(select Name from inserted) --重新进行统计,条件是inserted 临时表的Name字段
if exists(select * from inserted) --判断用户是否插入了数据
insert into b select * from inserted
我插入有记录 比如 insert a select 'b',3
它会在B添加一条记录 而没有跟 表B中'b'的相加
是这样的 虽然有点麻烦,但可以用
create trigger tri_upins on a --在A表建立触发器
after update
as
if update(Value) or update(Name) --判断用户是否在这两个列上进行了更新操作
update b set AllValue=(select sum(Value) from a where name=(select Name from inserted) )
where name=(select Name from inserted) --重新进行统计,条件是inserted 临时表的Name字段create trigger tri_upins2 on a --在A表建立触发器
after insert
as
if (select name from inserted) not in (select name from b)
insert b(name,allvalue) select name,value from inserted
else
update b set allvalue=(select sum(value) from a where name=(select Name from inserted))
where name=(select Name from inserted)