首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

一条简单的insert触发如何写不好

2012-01-23 
一条简单的insert触发怎么写不好?CREATETRIGGERins_salesON[dbo].[sales]FORINSERTASupdateproductssetcps

一条简单的insert触发怎么写不好?
CREATE   TRIGGER   ins_sales   ON   [dbo].[sales]  
FOR   INSERT  
AS
update   products   set   cpsl   =   cpsl   +   (select   sum(inserted.xssl)  
from   inserted   where   products.cpid   =   inserted.cpid   )  

update   products   set   cpsl   =   cpsl   +   (select   sum(inserted.xssl)  
from   inserted   group   by   cpid   having     products.cpid   =   inserted.cpid   )  

意思是在sales表中添一条记录,相应的把xssl累加到products表的cpsl中
上面两条都不行,应该怎么写?

[解决办法]
CREATE TRIGGER ins_sales ON [dbo].[sales]
FOR INSERT
AS
BEGIN
update p
set
cpsl = isnull(p.cpsl,0)+i.xssl
from
products p,inserted i
where
p.cpid=i.cpid

insert into products(cpid,cpsl)
select cpid,xssl from inserted
where
not exists(select 1 from products where cpid=inserted.cpid)
END
GO
[解决办法]
CREATE TRIGGER ins_sales ON [dbo].[sales]
FOR INSERT
AS
update products set cpsl = t.xssl
from procucts ,
(select cpid,sum(inserted.xssl) xssl from sales group by cpid) t
where products.cpid = t.cpid
go

热点排行