首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求这样一个触发器,该如何处理

2012-01-30 
求这样一个触发器数据库为:sql2005表Test,内容如下:字段A为int,B,C为日期,D为intABCD12007-03-3112:12:12N

求这样一个触发器
数据库为: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字段。
谢谢

[解决办法]
--这是比较天的

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
[解决办法]
--假設時間差是天

Create Table Test
(Aint,
BDateTime,
CDateTime,
Dint)
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
/*
ABCD
12007-03-29 12:12:12.0002007-03-31 15:25:04.3972
22007-03-30 12:12:12.0002007-03-31 15:25:04.3971
*/

热点排行