有两个表
表A
id,name,sourceid,sourcebillno表B
id,sourcebillno1,field1,field2在表A创建一个触发器,当更新或插入数据时,A表的sourceid的值是根据字段sourcebillno在表B查出的对应的ID。
即:表A的sourceid=select id from b where sourcebillno=sourcebillno1
这个触发器怎么写啊.

解决方案 »

  1.   


    create trigger name on 表A
    after update,insert
    as
    update 表A
    set sourceid=b.id
    from inserted a left join 表B b
    on  a.sourcebillno=b.sourcebillno1 
      

  2.   

    create   trigger   name   on   表A 
    for insert 
    as 
    begin
    update   表A 
    set   sourceid=b.id 
    from   inserted   a   inner join   表B   b 
    on   a.sourcebillno=b.sourcebillno1  
    end 
      

  3.   


    create table t1 
    (id int,name varchar(10),sourceid int, sourcebillno int)
    insert into t1
    select 1,'zhang','1','1'
    create table t2
    (id int,sourcebillno1 int,field1 int,field2 int)
    insert into t2
    select 3,1,2,3 union all
    select 5,3,2,3 union all
    select 6,4,2,3 union all
    select 8,8,2,3 union all
    select 10,5,2,3 union all
    select 11,9,2,3 create   trigger   name   on   t1 
    after   update,insert 
    as 
    update   t1 
    set   sourceid=b.id 
    from   inserted   a   join   t2   b 
    on     a.sourcebillno=b.sourcebillno1   
    where t1.id=a.idupdate t1
    set name='zhao'
    where id=1select * from t1 --sourceid由1 变成3/*
    id          name       sourceid    sourcebillno 
    ----------- ---------- ----------- ------------ 
    1           zhao       3           1(所影响的行数为 1 行)
    */insert into t1
    values(5,'zhang',12,9)select * from t1/*
    id          name       sourceid    sourcebillno 
    ----------- ---------- ----------- ------------ 
    1           zhao       3           1
    5           zhang      11          9(所影响的行数为 2 行)*/
      

  4.   

    CREATE TRIGGER my_trig ON A
    FOR INSERT, UPDATE 
    AS 
      update A set sourceid = b.id from a,b where a.sourcebillno=b.sourcebillno1
    GO
      

  5.   

    --慢了
    create trigger t on A 
    for insert,update
    as
    update A 
    set sourceid=select id from b where sourcebillno=sourcebillno1