[表A]有字段ID,Count,Right  
[表B]有字段ID,Right  
问如何令当[表B]删除,添加,修改数据时,[表A]对应的ID号的COUNT自动为[表B]的记录总数,Right为表B的Right等于1的总数
例如: 
[表B]          [表A] 自动为以下数
ID Right       ID Count Right  
1    1          1   2     1
1    0          2   2     2
2    1
2    1

解决方案 »

  1.   

    create table B(ID int,[Right] int)
    gocreate table A(ID int,[Count] int,[Right] int)
    gocreate trigger cfq on B
    for insert,update,delete
    asif @@rowcount=0 returndeclare @count_ins int
    declare @count_del int
    select @count_ins=count(*) from inserted
    select @count_del=count(*) from deletedif(@count_ins>0 and @count_del=0)
    begin
     delete from A
     insert into A select ID,(select count(*) from B) as [Count],count(*) as [right] from B where [Right]=1 group by ID
    endif(@count_ins>0 and @count_del>0)
    begin
     delete from A
     insert into A select ID,(select count(*) from B) as [Count],count(*) as [right] from B where [Right]=1 group by ID
    endif(@count_ins=0 and @count_del>0)
    begin
     delete from A
     insert into A select ID,(select count(*) from B) as [Count],count(*) as [right] from B where [Right]=1 group by ID
    end
    goinsert into B select 
    1,1 union all select    
    1,0 union all select
    2,1 union all select
    2,1
    select * from A
    godelete from A where ID=1
    select * from A
    goupdate B set ID=3
    select * from A
    godrop trigger cfq
    drop table B
    drop table A