加入Trigger?

时间:2011-03-08 20:42:24

标签: sql triggers

我正在尝试创建一个触发器,它将使用收据信息更新历史记录表。

我的源表有一个SourceID和一个ReceiptID。

因此,当我更新收据表时,我想将该记录复制到历史表中,但我首先需要获取正在更新的源的SourceID。

这就是我现在所拥有的:

ALTER TRIGGER [dbo].[trg_ReceiptHistory] 
ON [dbo].[tblReceipt]
for UPDATE
AS 
begin try
INSERT INTO tblHistorySource(RecShipName, RecShipAddress, sourceID)
select t1.shippingName, t1.shippingAddress, t2.sourceID
from [DELETED] t1, tblSource t2
where t2.receiptID = t1.receiptID
end try
begin catch
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
RAISERROR('Error in Source Hisotry Trigger' ,16,1)
ROLLBACK TRAN
END CATCH

当我尝试对tblReceipt进行简单更新时,我收到以下错误:

Msg 50000, Level 16, State 1, Procedure trg_ReceiptHistory, Line 24
Error in Source Hisotry Trigger
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.

我做错了吗?请帮忙:(

1 个答案:

答案 0 :(得分:2)

首先要做的是删除CATCH,以查看错误。我们可以从那里出发。

ALTER TRIGGER [dbo].[trg_ReceiptHistory] 
ON [dbo].[tblReceipt]
for UPDATE
AS 
--begin try
INSERT INTO tblHistorySource(RecShipName, RecShipAddress, sourceID)
select t1.shippingName, t1.shippingAddress, t2.sourceID
from [DELETED] t1, tblSource t2
where t2.receiptID = t1.receiptID
/*end try
begin catch
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
RAISERROR('Error in Source Hisotry Trigger' ,16,1)
ROLLBACK TRAN
END CATCH*/