有2个表,表A包含3列a0、a1、a2,表B包含2列b0、b1。我希望在A表插入新一行时输入a0、a1赋值,然后set b1=a1*2 where b0=a0。之后再根据b1确定新插入的行的a2的值,如a2=b1+5。能不能用一个表A的触发器解决?

解决方案 »

  1.   

    可以,用 INSTEAD OF 触发器.
    从 inserted 表中获取更新数据,向B表更新,再用B与inserted表连接获得a2,然后插入表A.
      

  2.   

    这儿
    http://blog.csdn.net/qianjin036a/article/details/6136588
    有instead of 触发器的例子.
      

  3.   

    /*
    有2个表,表A包含3列a0、a1、a2,表B包含2列b0、b1。我希望在A表插入新一行时输入a0、a1赋值,然后
    set b1=a1*2 where b0=a0。之后再根据b1确定新插入的行的a2的值,如a2=b1+5。能不能用一个表A的触发器解决?
    */
    create table t1(a0 int,a1 int,a2 int)
    insert into t1 select 1,23,31
    create table t2(b0 int,b1 int)
    insert into t2 select 1,10
    insert into t2 select 2,25
    insert into t2 select 3,18
    go
    create trigger updatetwotb
    on t1
    instead of insert
    as
    begin
    update b set b1=a.a1*2 from t2 b inner join inserted a on b.b0=a.a0
    insert into t1
    select a.a0,a.a1,b.b1+5 from inserted a inner join t2 b on a.a0=b.b0  --不过如果是这个算法的话,直接用 a1*2+5 不就行了么!
    end
    go
    insert into t1(a0,a1) select 2,50
    select * from t1
    select * from t2
    /*
    a0          a1          a2
    ----------- ----------- -----------
    1           23          31
    2           50          105(2 行受影响)b0          b1
    ----------- -----------
    1           10
    2           100
    3           18(3 行受影响)*/
    go
    drop table t1,t2