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条产品记录,并且根据单价与数量计算出总价,如果插入的产品的名称 在表中已经存在了,那么 就更新他的数量(在原有的基础上累加新录入的)与总价即可。

解决方案 »

  1.   

    要是2008的话 直接MERGE就解决了
      

  2.   

    create     trigger inserttable
    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 
      

  3.   

    继续MARK 帮忙者都有分拿!
      

  4.   


    --需先在名称建唯一索引
    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
      

  5.   


    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
      

  6.   


    你这个写的不错 ,但同名的话 ,会有俩条数据,因为先INSERT 然后再 触发 触发器