私はこのトリガーを持っています:
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