有两个表,A表和B表,A表中有一个字段S,B表中有一个字段I,触发器要实现当B表中的I字段等于2时,A表的S字段加1,当B表中的I字段等于3时,A表的S字段减1.请问触发器的写法

解决方案 »

  1.   

    --不知道LZ是不是这个意思!
    Create Table Tb1 (S int)
    Insert tb1 select 8 
    Go
    Create Table Tb2 (I int)
    Insert tb2 select 5
    ----------
    Create Trigger Tri_tb2 
    On Tb2
    For Insert
    As
     Declare @A int
     Select @A=I From Inserted
     If @A=2 
      Update Tb1
       Set S=S+1
      If @A=3 
      Update Tb1
       Set S=S-1
    ------------测试1
    --向tb2中插入2时 
    Insert tb2 select 2
    --tb1中S值增1
    ------------测试2
    Select * from tb1
    --向tb2中插入3时 
    Insert tb2 select 3
    --tb1中S值减1
    Select * from tb1
      

  2.   

    两个表怎么连接?create trigger tr_b_update_insert
    on b
    for update,inserte
    as
    update a
    set s=s+case when i.i=2 then 1 when i.i=3 then -1 else 0 end
    from a,inserted i
    where a.连接字段=i.连接字段
    and i.i in (2,3)
    go
      

  3.   

    Create trigger T_B on B
    for insert,update
    as
    begin
    if exists (select 1 from deleted)
    begin
     update A
     set S=S+1
     from inserted INS
     where INS.I=2
    end
    else
    begin
     update A
     set S=S-1
     from inserted INS
     where INS.I=3
    end
    end
      

  4.   

    楼上的这种写法有一种问题,比如说我B表中的I字段本来就是等于3,我现在对该字段进行更新,更新后I字段还是3,但是按楼上的写法的话,A字段的S字段也会减1,应该不减1才对
      

  5.   

    已经解决了,我加一个条件 and i.i<>d.i (i是inserted d是deleted).谢谢各位!!