我正在使用Sql Server 2008
。我有Trigger
更新我的另外两张桌子。我已经阅读了这个链接enter link description here的Stack over flow,但它并没有满足我的需求。以下是我的Trigger
ALTER TRIGGER [Inventory].[StockUpdationOnIssue]
ON [Inventory].[StockIssueDetails]
AFTER INSERT
AS
BEGIN
BEGIN TRY
BEGIN TRAN
INSERT INTO TableA
(col1, col2,col3
)
SELECT I.col1,I.col2,si.col3
FROM inserted I
INNER JOIN Inventory.StockIssue SI
ON SI.StockIssueId = I.StockIssueId
INSERT INTO TableB
(col1, col2,col3
)
SELECT I.col1,I.col2,si.col3
FROM inserted I
INNER JOIN Inventory.StockIssue SI
ON SI.StockIssueId = I.StockIssueId
COMMIT TRAN
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE();
RollBack Tran;
END CATCH
END
向我显示以下错误......
答案 0 :(得分:9)
您可以将错误详细信息保存在错误日志表中,以便稍后再回来进行调查 像
这样的东西ALTER TRIGGER [Inventory].[StockUpdationOnIssue]
ON [Inventory].[StockIssueDetails]
AFTER INSERT
AS
BEGIN
BEGIN TRY
BEGIN TRAN
INSERT INTO TableA
(col1, col2,col3
)
SELECT I.col1,I.col2,si.col3
FROM inserted I
INNER JOIN Inventory.StockIssue SI
ON SI.StockIssueId = I.StockIssueId
INSERT INTO TableB
(col1, col2,col3
)
SELECT I.col1,I.col2,si.col3
FROM inserted I
INNER JOIN Inventory.StockIssue SI
ON SI.StockIssueId = I.StockIssueId
COMMIT TRAN
END TRY
BEGIN CATCH
DECLARE @ErrorMsg VARCHAR(MAX), @ErrorNumber INT, @ErrorProc sysname, @ErrorLine INT
SELECT @ErrorMsg = ERROR_MESSAGE(), @ErrorNumber = ERROR_NUMBER(), @ErrorProc = ERROR_PROCEDURE(), @ErrorLine = ERROR_LINE();
RollBack Tran;
INSERT INTO ErrorLog (ErrorMsg, ErrorNumber, ErrorProc, ErrorLine)
VALUES (@ErrorMsg, @ErrorNumber, @ErrorProc, @ErrorLine)
END CATCH
END
像表一样ErrorLog:
CREATE TABLE ErrorLog
(
ErrorLogID INT IDENTITY(1,1),
ErrorDate DATETIME DEFAULT (GETUTCDATE()),
ErrorMsg VARCHAR(MAX),
ErrorNumber INT,
ErrorProc sysname,
ErrorLine INT
)
答案 1 :(得分:2)
我收到了同样的错误消息。您不需要触发器内的事务,因为它默认具有事务;即你不需要begin tran或commit tran。但是你可以在catch中使用rollback tran,它会在异常的情况下回滚。
ALTER TRIGGER [Inventory].[StockUpdationOnIssue]
ON [Inventory].[StockIssueDetails]
AFTER INSERT
AS
BEGIN
BEGIN TRY
INSERT INTO TableA
(col1, col2,col3
)
SELECT I.col1,I.col2,si.col3
FROM inserted I
INNER JOIN Inventory.StockIssue SI
ON SI.StockIssueId = I.StockIssueId
INSERT INTO TableB
(col1, col2,col3
)
SELECT I.col1,I.col2,si.col3
FROM inserted I
INNER JOIN Inventory.StockIssue SI
ON SI.StockIssueId = I.StockIssueId
END TRY
BEGIN CATCH
RollBack Tran;
END CATCH
END