create table Products (
Pid int identity,
PName varchar(100) null,
Price decimal null,
InputCount int null,
TotalPrice decimal null,
constraint PK_PRODUCTS primary key (Pid)
)这个是产品表的 表结构,我想写段触发器,目的是:如果插入的产品在产品表中,没有重复的名称,那么新增1条产品记录,并且根据单价与数量计算出总价,如果插入的产品的名称 在表中已经存在了,那么 就更新他的数量(在原有的基础上累加新录入的)与总价即可。
Pid int identity,
PName varchar(100) null,
Price decimal null,
InputCount int null,
TotalPrice decimal null,
constraint PK_PRODUCTS primary key (Pid)
)这个是产品表的 表结构,我想写段触发器,目的是:如果插入的产品在产品表中,没有重复的名称,那么新增1条产品记录,并且根据单价与数量计算出总价,如果插入的产品的名称 在表中已经存在了,那么 就更新他的数量(在原有的基础上累加新录入的)与总价即可。
解决方案 »
- 哪位大侠 指点一下 (CTE知识)
- SQL查询语句中的问题!!
- 如何实现跨机器备份数据库
- 如何把表中一个数据赋值给变量
- ~~~~~~~~~~~~SQL中有数组吗?~~~~~~~~~~~~
- 看一下下面的触发器语句有没有错误啊。。。。。。。。。。。。
- 【请教】能否多个客户端直接连接,存储远程SQL数据库
- 事务(进程ID55)与另一个进程已被死锁在lock资源上,且该事务已被选作死锁牺牲品,请重新运行该事务。
- 系统错误:MSSqlServerADhelper,“0”是无效的启动参数数目。此服务需要两个启动参数。
- 大学生综合素质评价系统
- 一个简单的sql检索问题、在线等、谢谢了
- 从 Sql2000 导2千万数据 到Oracle 11g,有什么快速的方法吗
on products
for insert,update
as
begin
declare @pname varchar(100),@pid int
set @pid=(select pid from inserted)
set @pname=(select panme from inserted)
if exists(select *from products where pname=@pname)
begin
update a
set a.inputcount=a.inputcount+b.inputcount,
a.totalprice=a.totalprice+b.totalprice
from products a, inseted b
where a.pname=b.pname
--? delete from products where pid=@pid
end
end
--需先在名称建唯一索引
create trigger ti_Products on Products
insert as
as
begin
--存在的
if exists(select 1 from Products,inserted i
where Products.PName = i.PName)
begin
update Products
set InputCount = InputCount + isnull(i.InputCount,0),
TotalPrice = TotalPrice + isnull(i.TotalPrice,0)
from inserted i
where Products.PName = i.PName
end --不存在的
if exists(select 1 from inserted i where not exists(select 1 from Products where Products.PName = i.PName))
begin
insert into Products(PName,Price,InputCount,TotalPrice)
select i.PName,i.Price,i.InputCount,isnull(i.Price,0) * isnull(i.InputCount,0)
from inserted i
where not exists(select 1 from Products where Products.PName = i.PName)
endend
create table Products (
Pid int identity,
PName varchar(100) null,
Price decimal null,
InputCount int null,
TotalPrice decimal null,
constraint PK_PRODUCTS primary key (Pid)
)insert Products
select 'p1',10,3,30 union all
select 'p2',8,6,48 union all
select 'p3',5,5,25 union all
select 'p4',30,7,210 create trigger tri_Products on Products instead of insert
as
if(exists(select 1 from Products as p join inserted as i on p.PName=i.PName))
begin
update Products set InputCount=Products.InputCount+i.InputCount,
TotalPrice=Products.Price*(Products.InputCount+i.InputCount)
from inserted as i where Products.PName=i.PName
end
else
insert Products select PName,Price,InputCount,Price*InputCount from inserted
你这个写的不错 ,但同名的话 ,会有俩条数据,因为先INSERT 然后再 触发 触发器