数据库为:sql2005
表Test,内容如下:字段A为int,B,C为日期,D为int
A  B                       C           D
1  2007-03-31 12:12:12     NULL        0 
2  2007-03-31 12:12:12     NULL        0求这样一个触发器
当更新C字段内容时,计算C与B的时间差,把值赋给D。如,以上两条记录,当我更新A=2那条记录的C字段后,触发计算C,B的时间差(时间差用datediff计算),然后把值赋给D字段。
谢谢

解决方案 »

  1.   

    --这是比较天的create trigger tu_test on test
    for update
    as
    if update(c) 
    and exists(select 1 from inserted i,deleted d where i.a=d.a and isnull(i.c,getdate())<>isnull(d.c,getdate()))
    begin
    update test
    set d=datediff(day,b,c)
    from test,inserted i,deleted d
    where test.a=i.a and i.a=d.a and isnull(i.c,getdate())<>isnull(d.c,getdate())
    end
      

  2.   


    create trigger tr on T for update
    as
    if update(C)
    update T set T.D=datediff(day, T.B, tmpB.C)
    from inserted tmpB
    where T.A=tmpB.A
      

  3.   

    --假設時間差是天Create Table Test
    (A int,
     B DateTime,
     C DateTime,
     D int)
    Insert Test Select 1,  '2007-03-29 12:12:12',     NULL,        0 
    Union All Select 2,  '2007-03-30 12:12:12',     NULL,        0
    GO
    Create Trigger TR_UpdateD On Test
    For Update
    As
    Begin
    If Update(C)
    Update A Set D = DateDiff(dd, B.B, B.C) From Test A Inner Join Inserted B On A.A = B.A
    End
    GO
    Update Test Set C = GetDate()Select * From Test
    GO
    Drop Table Test
    --Result
    /*
    A B C D
    1 2007-03-29 12:12:12.000 2007-03-31 15:25:04.397 2
    2 2007-03-30 12:12:12.000 2007-03-31 15:25:04.397 1
    */
      

  4.   

    其实在程序里写最适合,update test.c,test.d set c='data',d=时间减法(now-b)