一张表t,表头如下: 
----------------- 
Id  Code  Num 
----------------- 
希望当执行如下的插入语句:
insert into t values('1','A1',2)
insert into t values('1','A1',3)
insert into t values('1','B1',4)
insert into t values('1','B1',5)
后能得到如下结果:
----------------- 
Id  Code  Num 
----------------- 
1   A1    5
1   B1    9就是当有相同的Id和Code列时合并Num值,修改表时也一样,如何用触发器绑定实现呢

解决方案 »

  1.   

    --> (让你望见影子的墙)生成测试数据,时间:2008-12-13
     
    if not object_id('tb') is null
        drop table tb
    Go
    Create table tb([Id] int,[Code] nvarchar(2),[Num] int)
    Insert tb
    select 1,N'A1',1
    Go
    Select * from tb
    create trigger t1
    on tb
    instead of insert
    as
    if exists(select 1 from tb ,inserted where tb.id=inserted.id and tb.code=inserted.code)
        begin 
           update tb
           set num=num+(select num from inserted where tb.id=inserted.id and tb.code=inserted.code)
        end
    else
       insert into tb
       select * from inserted
    -->>
    insert into tb
    select 1,'a1',2select * from tb1    A1    3
    -->>
    insert into tb
    select 2,'a1',2select * from tb
    1    A1    3
    2    a1    2这个问题问第三遍了吧
      

  2.   

    create trigger trigI_t on t
    instead of insert
    as
    if exists(select * from inserted a,t where a.id=t.id and a.code=t.code)
    update t set num=t.num+a.num
    from t,inserted where a.id=t.id and a.code=t.code
    else
    insert into t (id,code,num) select id,code,num from  inserted
      

  3.   

    --> --> (Roy)生成測試數據
     
    Create table T([Id] int,[Code] nvarchar(2),[Num] int)
    go
    create trigger tr_t on t
    instead of insert
    as
    update t
    set Num=t.Num+i.Num
    from 
    (select ID,Code,sum(Num)Num from inserted group by ID,Code)i
    where
    t.ID=i.ID and t.Code=i.Codeinsert t 
    select 
    ID,Code,sum(Num)Num from inserted i
    where 
    not exists(select 1 from t where t.ID=i.ID and t.Code=i.Code)
    group by ID,Codego
    insert into t values('1','A1',2) 
    insert into t values('1','A1',3) 
    insert into t values('1','B1',4) 
    insert into t values('1','B1',5) select * from t/*
    Id          Code Num
    ----------- ---- -----------
    1           A1   5
    1           B1   9(2 行受影响)
    */