写两个触发器即可Create Trigger [Update_Main1] On Subone
FOR INSERT,DELETE
As
    Update Main Set count=(Select Count(1) from Inserted) Where tbName='Subone'
GO
Create Trigger [Update_Main2] On Subtwo
FOR INSERT,DELETE
As
    Update Main Set count=(Select Count(1) from Inserted) Where tbName='Subtwo'
GO

解决方案 »

  1.   

    你的思路不大对。应该在subone和subtwo进行更新的时候修改main。具体做法就很多了。可以建立insert和delete触发器。在subone和subtwo进行插入删除的时候修改main;
    或者直接在修改subone和subtwo的时候修改main。触发器的语法我不记得了,可以查下帮助。
    用客户端比较容易。
    每次insert into subone成功以后,就update main set count=count+1 where id=1
    每次delete from subone where id= 成功以后,就update main set count=count-1 where id=1
    subtwo也作同样处理。
    每次insert into subtwo成功以后,就update main set count=count+1 where id=2
    每次delete from subtwo where id= 成功以后,就update main set count=count-1 where id=2
      

  2.   

    使用触发器:create table main(
    id int identity,
    tbName NVarchar(100),
    count int
    )
    create table Subone(
    id int identity,
    fValue NVarchar(100),
    )
    create table Subtwo(
    id int identity,
    fValue NVarchar(100),
    )
    insert into main values('Subone',0)
    insert into main values('Subtwo',0)
    CREATE TRIGGER tr_alterCount
    on Subone
    after insert,delete
    as 
    update main set count=(select count(*) from Subone)
    where tbName='Subone'
    go
    CREATE TRIGGER tr_alterCount1
    on Subtwo
    after insert,delete
    as 
    update main set count=(select count(*) from Subone)
    where tbName='Subtwo'
    goinsert into Subone values('ad')
    select * from main
      

  3.   

    CREATE TRIGGER TRG1
    ON Subone
    FOR INSERT, DELETE
        UPDATE Main Set [count] = (SELECT COUNT(*) FROM Subone) WHERE tbName = N'Subone'
    GO
    CREATE TRIGGER TRG2
    ON Subone
    FOR INSERT, DELETE
        UPDATE Main Set [count] = (SELECT COUNT(*) FROM Subtwo) WHERE tbName = N'Subtwo'
    GO
      

  4.   

    哈哈,本来也想过这样,但是由于子表太多了,麻烦.所以才选择可不可以在main建触发器啊.
      

  5.   

    Main表建触发器是不可行的,子表建触发器才能及时更新嘛。语句大多类似,复制粘贴一下,就可以了,也不是太麻烦嘛。^_^
      

  6.   

    CREATE TRIGGER TRG1
    ON Subone
    FOR INSERT, DELETE
    AS
        UPDATE Main Set [count] = (SELECT COUNT(*) FROM Subone) WHERE tbName = N'Subone'
    GO
    CREATE TRIGGER TRG2
    ON Subone
    FOR INSERT, DELETE
    AS
        UPDATE Main Set [count] = (SELECT COUNT(*) FROM Subtwo) WHERE tbName = N'Subtwo'
    GO
      

  7.   

    如果子表太多,Main表用视图替代。
      

  8.   

    Create Trigger [Update_Main1] On Subone
    FOR INSERT,DELETE
    As
        Update Main Set count=(Select Count(1) from Subone) Where tbName='Subone'
    GO
    Create Trigger [Update_Main2] On Subtwo
    FOR INSERT,DELETE
    As
        Update Main Set count=(Select Count(1) from Subtwo) Where tbName='Subtwo'
    GO
      

  9.   

    create view main
    as
    select 1 as id,'Subone' as tbName,count(*) from Subone
    union all
    select 2 as id,'Subtwo' as tbName,count(*) from Subtwo
    ...
      

  10.   

    在从表上建insert和delete的触发器,把统计结果写到主表