我有这个触发器:
CREATE trigger [dbo].[DeriveTheAge] on [dbo].[Student]
after insert,update
as
begin
declare @sid as int;
declare @sdate as date;
select @sid= [Student ID] from inserted;
select @sdate=[Date of Birth] from inserted;
commit TRANSACTION
if(@sdate is not null)
begin
update Student set Age=DATEDIFF(YEAR,@sdate,GETDATE()) where [Student ID]=@sid;
end
print 'Successfully Done'
end
正如它所暗示的那样,触发器会从出生日期自动计算派生属性“年龄”。但是当我执行插入时出现此错误:
(1 row(s) affected)
Successfully Done
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
最初我避免了这个错误,因为尽管出现了错误,行仍在更新。但是现在当我从 FORNT END 插入一条记录时,该记录没有更新。相反,它抛出了这个异常:
谁能帮帮我?
顺便说一句,我的是 SQL Server 2008 R2 和 Visual Studio 2010。
更正:记录仍在更新。但例外是维兰。
更新
CREATE TRIGGER [dbo].[DeriveTheAge]
ON [dbo].[Student]
FOR INSERT, UPDATE
AS
BEGIN
UPDATE s
SET Age = DATEDIFF(YEAR, [Date of Birth], CURRENT_TIMESTAMP)
FROM dbo.Student AS s
INNER JOIN inserted AS i
ON s.[Student ID] = i.[Student ID]
WHERE i.[Date of Birth] IS NOT NULL;
commit transaction
END
GO