一个库的两个表:
table1字段:indate id age sub ....
table2字段:DATE   id  F1  F2  F3  F4 ....我想在在table1中添加记录的同时,判断table2中有没有ID跟table1中ID相同的记录,
一库中两个不同table:
table1字段:indate      id      age  sub ....
          
           2005-09-08  3456    23   Atable2字段: DATE       id      f1     f2 ....
           
            200509     3456    null   null
如没有,就在table2中也添加记录:只取table1中的年indate中的年和月,如2005-09-08取到talble2中就为200509就行了,id也要取一样的,  而其它的为空!如table1中的indate=2005-09-08修改为了2005-08-30, 那么table2中的DATE也要改为200508.其它的记录(如F1 F2)不管谢谢!

解决方案 »

  1.   

    create trigger ti_table1 on tabble1
    for insert,update
    as
    if not exists(select 1 from deleted) --插入
    insert into table2 (date,id)
    select indate,id from insertedif exists(select 1 from deleted) --删除
    begin
    if update(indate)
    update table2 set [date]=b.indate from table2 a,inserted b where  a.id=b.idendgo
      

  2.   

    create trigger tr
    on table1
    for insert,update
    as
    begin tran--插入不存在的
    if not exists(select 1 from deleted)
    begin
          insert table2(id,[DATE])
          select id,replace(left(indate,7),'-','') from inserted
    end
    else
    begin
          if update(indate)
          begin
                update table2
                set [DATE]=replace(left(I.indate,7),'-','')
                from table2 A
                join inserted I on A.id=I.id
          end
    endif @@error=0
    begin
          commit tran
    end
    else
    begin
          rollback tran
          raiserror('操作失败,错误号码为%d',12,1,@@error)
    end
    go