SQL 插入更新触发器之后

SQL AFTER Insert Trigger for Update

我试图在使用触发器插入 lunOut 列值后更新 lunTot 列,但不知何故它没有更新。如果我使用 Update 语句查询,它运行良好。

插入触发器后(不工作):

create trigger trg_AfterInsertLunTot
on lunTime
after insert
as
begin
    update lunTime
    set lunTot = DATEDIFF(minute, lunIn, lunOut) 
    from lunTime
end
go

使用 Update 查询(有效)

update lunTime
set lunTot = DATEDIFF(minute, lunIn, lunOut) 
from lunTime

为什么不直接将 lunTot 设为 computed 列?无需为此使用触发器....

只需删除现有的 lunTot 列即可

ALTER TABLE dbo.lunTime
DROP COLUMN lunTot

然后再次将其定义为计算列:

ALTER TABLE lunTime 
ADD lunTot = DATEDIFF(minute, lunIn, lunOut)

现在您的列 lunTot始终 反映 lunInlunOut 之间的差异 - 对于所有现有行,并自动在您之后也插入新行。