一条简单的insert触发怎么写不好?

sunrongxa 2007-09-18 11:13:02
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中
上面两条都不行,应该怎么写?
...全文
166 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2007-09-18
  • 打赏
  • 举报
回复
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

子陌红尘 2007-09-18
  • 打赏
  • 举报
回复
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

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧